Skip to content

Commit 6861a9a

Browse files
authored
Added ValueAtRisk Tutorial
1 parent 2210474 commit 6861a9a

File tree

1 file changed

+146
-0
lines changed

1 file changed

+146
-0
lines changed

Diff for: ValueAtRisk.ipynb

+146
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "code",
5+
"execution_count": 1,
6+
"metadata": {},
7+
"outputs": [],
8+
"source": [
9+
"import pandas as pd \n",
10+
"import numpy as np\n",
11+
"import matplotlib.pyplot as plt\n",
12+
"from pandas_datareader import data as web\n",
13+
"from datetime import timedelta\n",
14+
"from datetime import datetime\n",
15+
"from pypfopt.discrete_allocation import DiscreteAllocation, get_latest_prices\n",
16+
"from scipy import stats\n",
17+
"import seaborn as sns\n",
18+
"import yfinance as yf\n",
19+
"import math"
20+
]
21+
},
22+
{
23+
"cell_type": "code",
24+
"execution_count": 2,
25+
"metadata": {},
26+
"outputs": [],
27+
"source": [
28+
"def getData(portfolio):\n",
29+
" df = pd.DataFrame()\n",
30+
" for stock in portfolio:\n",
31+
" s = yf.Ticker(stock)\n",
32+
" df[stock] = s.history(period='max')[\"Close\"]\n",
33+
" return df"
34+
]
35+
},
36+
{
37+
"cell_type": "code",
38+
"execution_count": 3,
39+
"metadata": {},
40+
"outputs": [],
41+
"source": [
42+
"def VaR(portfolio, weights, price, date = datetime.today()):\n",
43+
" '''\n",
44+
" Takes in the list of stocks in your portfolio, \n",
45+
" '''\n",
46+
" df = getData(portfolio)\n",
47+
" df = df[-501:]\n",
48+
" df_exp =(df)/df.iloc[0]\n",
49+
" df_exp = df_exp*weights*price\n",
50+
" df['Value'] = df_exp.sum(axis = 1)\n",
51+
" df_loss = df.set_index(np.arange(0,501,1))\n",
52+
" for i in range(1,501):\n",
53+
" df_loss.iloc[i-1] = (df.iloc[i]/df.iloc[i-1])*df.iloc[-1]\n",
54+
" df_loss = df_loss[:-1]\n",
55+
" for i in range (500):\n",
56+
" df_loss['Value'].iloc[i] = round(df_loss[\"Value\"].iloc[i]-df[\"Value\"].iloc[-1] , 2)\n",
57+
" arr = df_loss['Value'].values *-1\n",
58+
" arr = np.sort(arr)\n",
59+
" print(\"The 1 day 99 percent confidence VaR is: \",'{:2f}'.format(round(arr[4],2)*-1))\n",
60+
" print(\"The 10 day 99 percent confidence VaR is: \",'{:2f}'.format(round(arr[4],2)*math.sqrt(10)*-1))\n"
61+
]
62+
},
63+
{
64+
"cell_type": "code",
65+
"execution_count": 12,
66+
"metadata": {},
67+
"outputs": [
68+
{
69+
"name": "stdout",
70+
"output_type": "stream",
71+
"text": [
72+
"The 1 day 99 percent confidence VaR is: 1186213.420000\n",
73+
"The 10 day 99 percent confidence VaR is: 3751136.198258\n"
74+
]
75+
}
76+
],
77+
"source": [
78+
"portfolio = ['AMZN']\n",
79+
"weights = np.array([1])\n",
80+
"price = 10000000\n",
81+
"VaR(portfolio, weights, price)\n"
82+
]
83+
},
84+
{
85+
"cell_type": "code",
86+
"execution_count": 10,
87+
"metadata": {},
88+
"outputs": [
89+
{
90+
"name": "stdout",
91+
"output_type": "stream",
92+
"text": [
93+
"The 1 day 99 percent confidence VaR is: 888754.780000\n",
94+
"The 10 day 99 percent confidence VaR is: 2810489.386162\n"
95+
]
96+
}
97+
],
98+
"source": [
99+
"\n",
100+
"portfolio = ['FB', \"AAPL\", \"AMZN\", 'NFLX', 'GOOG']\n",
101+
"weights = np.array([0.2,0.2,0.2,0.2,0.2])\n",
102+
"start = '2013-01-01'\n",
103+
"VaR(portfolio, weights, price)\n"
104+
]
105+
},
106+
{
107+
"cell_type": "markdown",
108+
"metadata": {},
109+
"source": [
110+
"Value at Risk is the defined as the maximum loss that we are anticipating the N number of days with X% confidence. \n",
111+
"\n",
112+
"Here we can clearly see that if we invest the same amount of money(10 million dollars) in one stock(AMZN), the value at risk is much higher as compared to the diverse portfolio withing FAANG. This is still not the most optimal portfolio. We can optimize the portfolio and that would lead to even lower value at Risk. \n",
113+
"\n",
114+
"Value at Risk is a great indicator of the fact that diversification in portfolio is very important. "
115+
]
116+
},
117+
{
118+
"cell_type": "code",
119+
"execution_count": null,
120+
"metadata": {},
121+
"outputs": [],
122+
"source": []
123+
}
124+
],
125+
"metadata": {
126+
"kernelspec": {
127+
"display_name": "Python 3",
128+
"language": "python",
129+
"name": "python3"
130+
},
131+
"language_info": {
132+
"codemirror_mode": {
133+
"name": "ipython",
134+
"version": 3
135+
},
136+
"file_extension": ".py",
137+
"mimetype": "text/x-python",
138+
"name": "python",
139+
"nbconvert_exporter": "python",
140+
"pygments_lexer": "ipython3",
141+
"version": "3.8.3"
142+
}
143+
},
144+
"nbformat": 4,
145+
"nbformat_minor": 4
146+
}

0 commit comments

Comments
 (0)