{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.2"
},
"colab": {
"name": "var_various_ways1.ipynb",
"provenance": [],
"collapsed_sections": [],
"include_colab_link": true
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "CZXIzNOM92Lp"
},
"source": [
"# Value at Risk, VaR\n",
"In this code, using Geometric Brownian Motion, simulate returns and create distribution. And then find the VaR.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Ye-MyiEscdyp"
},
"source": [
"###VaR\n",
"\n",
"Value at risk (VaR): Loss that will be incurred in the event of an extreme adverse price change with some given, usually low, probability. i.e., the worst-case outcome. For example, 1% VaR means that 99% of returns will exceed the VaR and 1% of returns will be worse.\n",
"\n",
"Assuming that portfolio returns are normally distributed, the VaR is fully determined by the mean and standard deviation of the distribution. \n",
"\n",
"For example, VaR(1%, normal) = Mean - 2.33SD\n",
"\n",
"To obtain a sample estimate of 1% VaR, we sort the observations from high to low. The VaR is the return at the 1st percentile of the sample distribution.\n",
"\n",
"For example, with 95% confidence, we expect that our worst daily loss will not exceed 4%. If we invest 100 dollars, we are 95% confident that our worst daily loss will not exceed 4 dollars (100 dollars x -4%).\n",
"\n"
]
},
{
"cell_type": "markdown",
"source": [
"|Confidence Level |Two sided CV |One sided CV | \n",
"|---|---|---|\n",
"| 90% |1.64 |1.28 | \n",
"| 95% |1.96 |1.64 | \n",
"| 99% |2.58 |2.33 | "
],
"metadata": {
"id": "tU9awDWYPwQ4"
}
},
{
"cell_type": "code",
"metadata": {
"id": "i2wlPW-1Mz_b",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "ff861571-8cc6-4b48-9185-2ed0a035977c"
},
"source": [
"!pip install pandas-datareader\n",
"!pip install --upgrade pandas-datareader \n",
"!pip install yfinance\n",
"\n",
"#Diable the warnings\n",
"#import warnings\n",
"#warnings.filterwarnings('ignore')"
],
"execution_count": 49,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
"Requirement already satisfied: pandas-datareader in /usr/local/lib/python3.7/dist-packages (0.10.0)\n",
"Requirement already satisfied: lxml in /usr/local/lib/python3.7/dist-packages (from pandas-datareader) (4.9.0)\n",
"Requirement already satisfied: pandas>=0.23 in /usr/local/lib/python3.7/dist-packages (from pandas-datareader) (1.3.5)\n",
"Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.7/dist-packages (from pandas-datareader) (2.27.1)\n",
"Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.23->pandas-datareader) (2.8.2)\n",
"Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.23->pandas-datareader) (2022.1)\n",
"Requirement already satisfied: numpy>=1.17.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.23->pandas-datareader) (1.21.6)\n",
"Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas>=0.23->pandas-datareader) (1.15.0)\n",
"Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader) (2.10)\n",
"Requirement already satisfied: charset-normalizer~=2.0.0 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader) (2.0.12)\n",
"Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader) (1.24.3)\n",
"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader) (2022.5.18.1)\n",
"Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
"Requirement already satisfied: pandas-datareader in /usr/local/lib/python3.7/dist-packages (0.10.0)\n",
"Requirement already satisfied: pandas>=0.23 in /usr/local/lib/python3.7/dist-packages (from pandas-datareader) (1.3.5)\n",
"Requirement already satisfied: lxml in /usr/local/lib/python3.7/dist-packages (from pandas-datareader) (4.9.0)\n",
"Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.7/dist-packages (from pandas-datareader) (2.27.1)\n",
"Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.23->pandas-datareader) (2022.1)\n",
"Requirement already satisfied: numpy>=1.17.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.23->pandas-datareader) (1.21.6)\n",
"Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.23->pandas-datareader) (2.8.2)\n",
"Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas>=0.23->pandas-datareader) (1.15.0)\n",
"Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader) (2.10)\n",
"Requirement already satisfied: charset-normalizer~=2.0.0 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader) (2.0.12)\n",
"Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader) (1.24.3)\n",
"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader) (2022.5.18.1)\n",
"Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
"Requirement already satisfied: yfinance in /usr/local/lib/python3.7/dist-packages (0.1.70)\n",
"Requirement already satisfied: requests>=2.26 in /usr/local/lib/python3.7/dist-packages (from yfinance) (2.27.1)\n",
"Requirement already satisfied: numpy>=1.15 in /usr/local/lib/python3.7/dist-packages (from yfinance) (1.21.6)\n",
"Requirement already satisfied: pandas>=0.24.0 in /usr/local/lib/python3.7/dist-packages (from yfinance) (1.3.5)\n",
"Requirement already satisfied: lxml>=4.5.1 in /usr/local/lib/python3.7/dist-packages (from yfinance) (4.9.0)\n",
"Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance) (0.0.10)\n",
"Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24.0->yfinance) (2.8.2)\n",
"Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24.0->yfinance) (2022.1)\n",
"Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas>=0.24.0->yfinance) (1.15.0)\n",
"Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.26->yfinance) (1.24.3)\n",
"Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.26->yfinance) (2.10)\n",
"Requirement already satisfied: charset-normalizer~=2.0.0 in /usr/local/lib/python3.7/dist-packages (from requests>=2.26->yfinance) (2.0.12)\n",
"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.26->yfinance) (2022.5.18.1)\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"import math\n",
"import numpy as np\n",
"import numpy.random as npr\n",
"import pandas as pd \n",
"import pandas_datareader as pdr\n",
"import yfinance as yf\n",
"\n",
"import scipy as sp\n",
"from scipy import stats \n",
"\n",
"from pylab import plt, mpl\n",
"plt.style.use('fivethirtyeight')\n",
"#plt.style.use('seaborn')\n",
"mpl.rcParams['font.family'] = 'DejaVu Sans'\n",
"\n",
"pd.set_option('precision', 3)\n",
"pd.set_option('display.max_colwidth', 100)\n",
"%matplotlib inline"
],
"metadata": {
"id": "KzheAcx--5Da"
},
"execution_count": 4,
"outputs": []
},
{
"cell_type": "code",
"source": [
"print(\"At 95% confidence level {:.2f}\".format(sp.stats.norm.ppf(1-.10/2)))\n",
"print(\"At 97.5% confidence level {:.2f}\".format(sp.stats.norm.ppf(1-.05/2)))\n",
"print(\"At 90% confidence level {:.2f}\".format(sp.stats.norm.ppf(1-.10)))\n",
"print(\"At 99% confidence level {:.2f}\".format(sp.stats.norm.ppf(1-.01)))"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "I0QCB0v5T-oi",
"outputId": "41f90559-246e-43c6-a48a-f09ad5310f57"
},
"execution_count": 5,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"At 95% confidence level 1.64\n",
"At 97.5% confidence level 1.96\n",
"At 90% confidence level 1.28\n",
"At 99% confidence level 2.33\n"
]
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "qXs2DPrQ3k4j"
},
"source": [
"def get_prices(tickers, freq_p, st_day, end_day):\n",
" mystock = pd.DataFrame()\n",
" for t in tickers:\n",
" mystock[t] = yf.download(t, start=st_day, end=end_day, interval=freq_p)['Adj Close']\n",
" return mystock"
],
"execution_count": 6,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "kEPgMkoq92Lw"
},
"source": [
"# for short time horizons er will be small, and therefore VaR estimations\n",
"# will not be much influenced by it\n",
"# assuming that portfolio is normally distributed, \n",
"\n",
"def var_calc(CL, days, p_val, vol, t):\n",
"\n",
" VaR = p_val * vol * np.sqrt(t/days) * sp.stats.norm.ppf(CL)\n",
" percent_loss = -VaR/p_val *100\n",
"\n",
" print(\"Assuming that we invest {:.2f}, for the next {:.1f} trading days\".format(p_val, days))\n",
" print(\"At {:.3f} confidence level, loss will not exceed {:,.2f}\".format(CL, VaR))\n",
" print(\"This represents a move of {:.2f} standard deviations below the expected return,\\\n",
" or a loss of {:.2f}%.\".format(sp.stats.norm.ppf(CL), percent_loss))\n",
" \n",
" return"
],
"execution_count": 16,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "ZlWV2Lgl3k7j",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 713
},
"outputId": "5859a42f-41a5-4f04-8cff-6ed2a401b6b1"
},
"source": [
"tic=['SPY', 'TLT', 'TSLA', 'AAPL', 'VNQ', 'BAC', 'WMT', 'AMD', 'JNJ', 'GM', 'CMG', 'SHV']\n",
"prices= get_prices(tic, freq_p='1wk', st_day=\"2011-01-01\", end_day=\"2022-05-31\") # id , 1wk, 1mo\n",
"\n",
"prices.info()\n",
"prices.tail(3)"
],
"execution_count": 14,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"[*********************100%***********************] 1 of 1 completed\n",
"[*********************100%***********************] 1 of 1 completed\n",
"[*********************100%***********************] 1 of 1 completed\n",
"[*********************100%***********************] 1 of 1 completed\n",
"[*********************100%***********************] 1 of 1 completed\n",
"[*********************100%***********************] 1 of 1 completed\n",
"[*********************100%***********************] 1 of 1 completed\n",
"[*********************100%***********************] 1 of 1 completed\n",
"[*********************100%***********************] 1 of 1 completed\n",
"[*********************100%***********************] 1 of 1 completed\n",
"[*********************100%***********************] 1 of 1 completed\n",
"[*********************100%***********************] 1 of 1 completed\n",
"\n",
"DatetimeIndex: 640 entries, 2011-01-01 to 2022-05-21\n",
"Data columns (total 12 columns):\n",
" # Column Non-Null Count Dtype \n",
"--- ------ -------------- ----- \n",
" 0 SPY 595 non-null float64\n",
" 1 TLT 595 non-null float64\n",
" 2 TSLA 595 non-null float64\n",
" 3 AAPL 595 non-null float64\n",
" 4 VNQ 595 non-null float64\n",
" 5 BAC 595 non-null float64\n",
" 6 WMT 595 non-null float64\n",
" 7 AMD 595 non-null float64\n",
" 8 JNJ 595 non-null float64\n",
" 9 GM 595 non-null float64\n",
" 10 CMG 595 non-null float64\n",
" 11 SHV 595 non-null float64\n",
"dtypes: float64(12)\n",
"memory usage: 65.0 KB\n"
]
},
{
"output_type": "execute_result",
"data": {
"text/plain": [
" SPY TLT TSLA AAPL VNQ BAC WMT AMD \\\n",
"Date \n",
"2022-05-07 401.72 115.98 769.59 147.11 96.78 35.17 148.05 95.12 \n",
"2022-05-14 389.63 118.51 663.90 137.59 94.83 33.86 119.20 93.50 \n",
"2022-05-21 415.26 119.08 759.63 149.64 100.30 37.02 128.48 102.26 \n",
"\n",
" JNJ GM CMG SHV \n",
"Date \n",
"2022-05-07 175.721 38.21 1318.28 110.22 \n",
"2022-05-14 175.850 35.40 1294.11 110.23 \n",
"2022-05-21 179.934 38.57 1402.42 110.27 "
],
"text/html": [
"\n",
"
\n",
"
\n",
"
\n",
"\n",
"
\n",
" \n",
"
\n",
"
\n",
"
SPY
\n",
"
TLT
\n",
"
TSLA
\n",
"
AAPL
\n",
"
VNQ
\n",
"
BAC
\n",
"
WMT
\n",
"
AMD
\n",
"
JNJ
\n",
"
GM
\n",
"
CMG
\n",
"
SHV
\n",
"
\n",
"
\n",
"
Date
\n",
"
\n",
"
\n",
"
\n",
"
\n",
"
\n",
"
\n",
"
\n",
"
\n",
"
\n",
"
\n",
"
\n",
"
\n",
"
\n",
" \n",
" \n",
"
\n",
"
2022-05-07
\n",
"
401.72
\n",
"
115.98
\n",
"
769.59
\n",
"
147.11
\n",
"
96.78
\n",
"
35.17
\n",
"
148.05
\n",
"
95.12
\n",
"
175.721
\n",
"
38.21
\n",
"
1318.28
\n",
"
110.22
\n",
"
\n",
"
\n",
"
2022-05-14
\n",
"
389.63
\n",
"
118.51
\n",
"
663.90
\n",
"
137.59
\n",
"
94.83
\n",
"
33.86
\n",
"
119.20
\n",
"
93.50
\n",
"
175.850
\n",
"
35.40
\n",
"
1294.11
\n",
"
110.23
\n",
"
\n",
"
\n",
"
2022-05-21
\n",
"
415.26
\n",
"
119.08
\n",
"
759.63
\n",
"
149.64
\n",
"
100.30
\n",
"
37.02
\n",
"
128.48
\n",
"
102.26
\n",
"
179.934
\n",
"
38.57
\n",
"
1402.42
\n",
"
110.27
\n",
"
\n",
" \n",
"
\n",
"
\n",
" \n",
" \n",
" \n",
"\n",
" \n",
"
\n",
"
\n",
" "
]
},
"metadata": {},
"execution_count": 14
}
]
},
{
"cell_type": "code",
"source": [
"for t in tic:\n",
" confidence_l = .95\n",
" annual_volatility = np.std(prices[t].pct_change()*np.sqrt(252))\n",
" most_recent_p = prices[t][-1]\n",
" holding_period = 252\n",
" frequency = 21\n",
" print(\"Historical annual volatility of {} = {:.4f}\".format(t, annual_volatility))\n",
" var_calc(confidence_l, holding_period, most_recent_p, annual_volatility, frequency)\n",
" print(50 * \"-\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Q1n7ERLvB16m",
"outputId": "c4179fe6-a65f-442c-f081-be3dae369659"
},
"execution_count": 17,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Historical annual volatility of SPY = 0.3427\n",
"Assuming that we invest 415.26, for the next 252.0 trading days\n",
"At 0.950 confidence level, loss will not exceed 67.56\n",
"This represents a move of 1.64 standard deviations below the expected return, or a loss of -16.27%.\n",
"--------------------------------------------------\n",
"Historical annual volatility of TLT = 0.2965\n",
"Assuming that we invest 119.08, for the next 252.0 trading days\n",
"At 0.950 confidence level, loss will not exceed 16.77\n",
"This represents a move of 1.64 standard deviations below the expected return, or a loss of -14.08%.\n",
"--------------------------------------------------\n",
"Historical annual volatility of TSLA = 1.1661\n",
"Assuming that we invest 759.63, for the next 252.0 trading days\n",
"At 0.950 confidence level, loss will not exceed 420.60\n",
"This represents a move of 1.64 standard deviations below the expected return, or a loss of -55.37%.\n",
"--------------------------------------------------\n",
"Historical annual volatility of AAPL = 0.5918\n",
"Assuming that we invest 149.64, for the next 252.0 trading days\n",
"At 0.950 confidence level, loss will not exceed 42.05\n",
"This represents a move of 1.64 standard deviations below the expected return, or a loss of -28.10%.\n",
"--------------------------------------------------\n",
"Historical annual volatility of VNQ = 0.4469\n",
"Assuming that we invest 100.30, for the next 252.0 trading days\n",
"At 0.950 confidence level, loss will not exceed 21.28\n",
"This represents a move of 1.64 standard deviations below the expected return, or a loss of -21.22%.\n",
"--------------------------------------------------\n",
"Historical annual volatility of BAC = 0.6979\n",
"Assuming that we invest 37.02, for the next 252.0 trading days\n",
"At 0.950 confidence level, loss will not exceed 12.27\n",
"This represents a move of 1.64 standard deviations below the expected return, or a loss of -33.14%.\n",
"--------------------------------------------------\n",
"Historical annual volatility of WMT = 0.4125\n",
"Assuming that we invest 128.48, for the next 252.0 trading days\n",
"At 0.950 confidence level, loss will not exceed 25.17\n",
"This represents a move of 1.64 standard deviations below the expected return, or a loss of -19.59%.\n",
"--------------------------------------------------\n",
"Historical annual volatility of AMD = 1.2085\n",
"Assuming that we invest 102.26, for the next 252.0 trading days\n",
"At 0.950 confidence level, loss will not exceed 58.68\n",
"This represents a move of 1.64 standard deviations below the expected return, or a loss of -57.38%.\n",
"--------------------------------------------------\n",
"Historical annual volatility of JNJ = 0.3385\n",
"Assuming that we invest 179.93, for the next 252.0 trading days\n",
"At 0.950 confidence level, loss will not exceed 28.92\n",
"This represents a move of 1.64 standard deviations below the expected return, or a loss of -16.08%.\n",
"--------------------------------------------------\n",
"Historical annual volatility of GM = 0.7413\n",
"Assuming that we invest 38.57, for the next 252.0 trading days\n",
"At 0.950 confidence level, loss will not exceed 13.58\n",
"This represents a move of 1.64 standard deviations below the expected return, or a loss of -35.20%.\n",
"--------------------------------------------------\n",
"Historical annual volatility of CMG = 0.7466\n",
"Assuming that we invest 1402.42, for the next 252.0 trading days\n",
"At 0.950 confidence level, loss will not exceed 497.18\n",
"This represents a move of 1.64 standard deviations below the expected return, or a loss of -35.45%.\n",
"--------------------------------------------------\n",
"Historical annual volatility of SHV = 0.0086\n",
"Assuming that we invest 110.27, for the next 252.0 trading days\n",
"At 0.950 confidence level, loss will not exceed 0.45\n",
"This represents a move of 1.64 standard deviations below the expected return, or a loss of -0.41%.\n",
"--------------------------------------------------\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"Monte Carolo approach using stochastic geometric Borwnian motion, "
],
"metadata": {
"id": "A9xsl2w6W-1r"
}
},
{
"cell_type": "code",
"source": [
"S0 = prices['AAPL'][-1]\n",
"print(S0)\n",
"r = 0.05 \n",
"sigma = np.std(prices['AAPL'].pct_change()*np.sqrt(252))\n",
"T = 21.0 \n",
"I = 10000 \n",
"\n",
"ST1 = S0 * np.exp((r - 0.5 * sigma ** 2) * T +\n",
" sigma * math.sqrt(T) * np.random.standard_normal(I)) \n",
"\n",
"ST2 = S0 * np.random.lognormal((r - 0.5 * sigma ** 2) * T,\n",
" sigma * math.sqrt(T), size=I) "
],
"metadata": {
"id": "_bOVC-pKfpEF",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "838d7c11-440f-479c-db98-bceaa7e915f7"
},
"execution_count": 18,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"149.63999938964844\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"def print_statistics(a1, a2):\n",
" '''\n",
" Parameters\n",
" ==========\n",
" a1, a2: ndarray objects\n",
" results objects from simulation\n",
" '''\n",
"\n",
" sta1 = sp.stats.describe(a1) \n",
" sta2 = sp.stats.describe(a2) \n",
" print('%14s %14s %14s' % ('statistic', 'data set 1', 'data set 2'))\n",
" print(45 * \"-\")\n",
" print('%14s %14.3f %14.3f' % ('size', sta1[0], sta2[0]))\n",
" print('%14s %14.3f %14.3f' % ('min', sta1[1][0], sta2[1][0]))\n",
" print('%14s %14.3f %14.3f' % ('max', sta1[1][1], sta2[1][1]))\n",
" print('%14s %14.3f %14.3f' % ('mean', sta1[2], sta2[2]))\n",
" print('%14s %14.3f %14.3f' % ('std', np.sqrt(sta1[3]), np.sqrt(sta2[3])))\n",
" print('%14s %14.3f %14.3f' % ('skew', sta1[4], sta2[4]))\n",
" print('%14s %14.3f %14.3f' % ('kurtosis', sta1[5], sta2[5]))"
],
"metadata": {
"id": "bza2fBkVfpBD"
},
"execution_count": 19,
"outputs": []
},
{
"cell_type": "code",
"source": [
"print_statistics(ST1, ST2)"
],
"metadata": {
"id": "Hb2OePGXfo-m",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "4d200237-b705-42d6-9ff8-b365a30ae76b"
},
"execution_count": 20,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
" statistic data set 1 data set 2\n",
"---------------------------------------------\n",
" size 10000.000 10000.000\n",
" min 0.000 0.001\n",
" max 300993.143 114507.025\n",
" mean 445.331 313.031\n",
" std 5473.487 2648.420\n",
" skew 36.528 28.691\n",
" kurtosis 1653.676 1042.670\n"
]
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "lqzwBgDb3k-m"
},
"source": [
""
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "pMsb_TvV4NF7"
},
"source": [
"### Let's assume that we buy 5000 shares of AAPL. And using historical returns, let's estimate mean and standard deviation of returns on AAPL. In order to save time, let's assume they are 19% and 30.7%, respectively. "
]
},
{
"cell_type": "code",
"metadata": {
"id": "SAWrAYn692Lx"
},
"source": [
"aapl = 1\n",
"aapl_price = pdr.get_quote_yahoo('AAPL')['price'] # the most recent price\n",
"aapl_value = aapl * aapl_price\n",
"aapl_value = aapl_value.at['AAPL']\n",
"t = 21/252\n",
"mu = .05\n",
"volatility = .307\n",
"iterations = 10000"
],
"execution_count": 21,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "49QQd-N8ZT52",
"outputId": "b5954bb0-90e6-48fb-8c00-5571002995dc"
},
"source": [
"type(aapl_price)"
],
"execution_count": 22,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"pandas.core.series.Series"
]
},
"metadata": {},
"execution_count": 22
}
]
},
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "DlSeBhhiyYOz",
"outputId": "e8c7847c-c903-4300-f048-f474883c517a"
},
"source": [
"aapl_price.describe()"
],
"execution_count": 23,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"count 1.00\n",
"mean 148.84\n",
"std NaN\n",
"min 148.84\n",
"25% 148.84\n",
"50% 148.84\n",
"75% 148.84\n",
"max 148.84\n",
"Name: price, dtype: float64"
]
},
"metadata": {},
"execution_count": 23
}
]
},
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 191
},
"id": "2Yq4jmIeuDSi",
"outputId": "947c4806-d28d-4fc8-814b-4d9fb535077d"
},
"source": [
"# checking to see what get_quote_yahoo is retreveing\n",
"pdr.get_quote_yahoo('AAPL')\n"
],
"execution_count": 24,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
" language region quoteType typeDisp quoteSourceName triggerable \\\n",
"AAPL en-US US EQUITY Equity Nasdaq Real Time Price True \n",
"\n",
" customPriceAlertConfidence currency marketState gmtOffSetMilliseconds \\\n",
"AAPL HIGH USD PREPRE -14400000 \n",
"\n",
" ... earningsTimestamp earningsTimestampStart earningsTimestampEnd \\\n",
"AAPL ... 1651163400 1658779200 1659124800 \n",
"\n",
" trailingAnnualDividendRate trailingPE trailingAnnualDividendYield \\\n",
"AAPL 0.88 24.253 0.006 \n",
"\n",
" epsTrailingTwelveMonths epsForward displayName price \n",
"AAPL 6.137 6.56 Apple 148.84 \n",
"\n",
"[1 rows x 78 columns]"
],
"text/html": [
"\n",
"