-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Stock Market Risk Analysis for Apple.py
231 lines (113 loc) · 3.93 KB
/
Stock Market Risk Analysis for Apple.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# coding: utf-8
# In[1]:
# Importing all the essential Python libraries
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
import seaborn as sns
import matplotlib.pyplot as plt
get_ipython().magic('matplotlib inline')
sns.set_style('whitegrid')
# In[2]:
# Importing Stock market data from the Internet
from pandas.io.data import DataReader
# In[3]:
# Importing datetime for setting start and end date of the stock market dataset
from datetime import datetime
# In[4]:
# Setting the Start and End date for Stock Market Analysis
end = datetime.now()
start = datetime(end.year-1,end.month,end.day)
# In[5]:
# Importing Apple Stock Prices
AAPL = DataReader('AAPL','yahoo',start,end)
# In[6]:
# Some Basic info about the Apple Stock
AAPL.describe()
# In[7]:
# Plotting Adjusted Closing price for Apple Stock
AAPL['Adj Close'].plot(legend=True,figsize=(10,4))
# In[8]:
# Plotting the total volume of stock being traded each day
AAPL['Volume'].plot(legend=True,figsize=(10,4))
# In[9]:
# Calculating Moving average for 10, 20 and 50 days of the stock price
ma_day = [10,20,50]
for ma in ma_day:
column_name = "MA for %s days" %(str(ma))
AAPL[column_name] = pd.rolling_mean(AAPL['Adj Close'],ma)
# In[10]:
# Plotting the moving averages
AAPL[['Adj Close', 'MA for 10 days','MA for 20 days','MA for 50 days']].plot(subplots=False,figsize=(10,4))
# In[11]:
# Plotting Daily returns as a function of Percent change in Adjusted Close value
AAPL['Daily Return'] = AAPL['Adj Close'].pct_change()
AAPL['Daily Return'].plot(legend=True)
# In[12]:
# Plotting the average daily returns of the stock
sns.distplot(AAPL['Daily Return'].dropna(),bins=100)
# In[13]:
# Risk Analysis -- Comparing the Risk vs Expected returns
rets = AAPL['Daily Return'].dropna()
area = np.pi*15
plt.scatter(rets.mean(),rets.std(),s=area)
plt.xlabel('Expected Returns')
plt.ylabel('Risk')
# In[14]:
# Visualizing the Value at Risk
sns.distplot(AAPL['Daily Return'].dropna(),bins=100)
# In[15]:
# Using Quantiles and the Bootstrap Method to calculate the numerical risk of the stock
AAPL['Daily Return'].quantile(0.05)
# In[16]:
## Monte Carlo Simulation
days = 365
dt = 1/days
mu = rets.mean()
sigma = rets.std()
# In[17]:
# Defining the Monte Carlo Simulation Function
def stock_monte_carlo(start_price,days,mu,sigma):
price = np.zeros(days)
price[0] = start_price
shock = np.zeros(days)
drift = np.zeros(days)
for x in range(1,days):
shock[x] = np.random.normal(loc=mu*dt,scale=sigma*np.sqrt(dt))
drift[x] = mu * dt
price[x] = price[x-1] + (price[x-1]* (drift[x] + shock[x]))
return price
# In[18]:
AAPL.head()
# In[19]:
# Running the Monte Carlo simulation a hundred times
start_price = 113.790001
for run in range(100):
plt.plot(stock_monte_carlo(start_price,days,mu,sigma))
plt.xlabel('Days')
plt.ylabel('Price')
plt.title('Monte Carlo Simulation for Apple')
# In[20]:
# Analysing the Monte Carlo Simulation for 10,000 simulations
runs = 10000
simulations = np.zeros(runs)
for run in range(runs):
simulations[run] = stock_monte_carlo(start_price,days,mu,sigma)[days-1]
# 1 percent impirical quantile or 99% Confidence Interval
q = np.percentile(simulations,1)
# In[21]:
# Plotting the final Risk Analysis plot using Monte Carlo Simulation
plt.hist(simulations,bins=200)
plt.figtext(0.6, 0.8, s="Start price: $%.2f" %start_price)
# Mean ending price
plt.figtext(0.6, 0.7, "Mean final price: $%.2f" % simulations.mean())
# Variance of the price (within 99% confidence interval)
plt.figtext(0.6, 0.6, "VaR(0.99): $%.2f" % (start_price - q,))
# Display 1% quantile
plt.figtext(0.15, 0.6, "q(0.99): $%.2f" % q)
# Plot a line at the 1% quantile result
plt.axvline(x=q, linewidth=4, color='r')
# Title
plt.title(u"Final price distribution for Apple Stock after %s days" % days, weight='bold');
# In[ ]:
# In[ ]: