-
Notifications
You must be signed in to change notification settings - Fork 0
/
02-temp_series_project.py
273 lines (175 loc) · 5.1 KB
/
02-temp_series_project.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#!pip install arch
#!pip install statsmodels
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
import csv
import datetime as datetime
import matplotlib.dates as mdates
import seaborn; seaborn.set()
from arch import arch_model
import statsmodels as sm
df = pd.read_csv('NFLX.csv')
df.head()
df.info()
df['Date'] = pd.to_datetime(df['Date'])
df.info()
## Returns ##
##preps
N = len(df['Date'])
c_values = df['Close'].values
d_valuess = df['Date'].values
d_values = []
l_return = []
log_return = []
n_return = []
##linear return
for i in range(N-1):
l_return.append(c_values[i + 1]/c_values[i] - 1)
d_values.append(d_valuess[i])
##log return
for i in range(N-1):
log_return.append(np.log(c_values[i+1]) - np.log(c_values[i]))
##normalized return
mean = np.average(log_return)
stdev = np.std(log_return)
for i in range(N-1):
n_return.append((log_return[i]-mean)/stdev)
fig, ax = plt.subplots(figsize=(16, 9))
plt.plot(d_values, l_return, c='green', label='Linear Return')
plt.legend(loc='upper right')
plt.title('Daily Returns of Netflix Stock', fontsize=16)
plt.legend(loc='best')
plt.xlabel('Date')
plt.ylabel('Return')
plt.show()
fig, ax = plt.subplots(figsize=(16, 9))
plt.plot(d_values, n_return, label='Normalized Return')
plt.legend(loc='upper right')
plt.title('Daily Returns of Netflix Stock', fontsize=16)
plt.legend(loc='best')
plt.xlabel('Date')
plt.ylabel('Return')
plt.show()
fig, ax = plt.subplots(figsize=(16, 9))
lags = 100
ACF = plt.acorr(l_return, maxlags=lags, label="Autocorrelation")
plt.title('Autocorrelation of Linear Return', fontsize=16)
plt.xlabel('Lags (k)')
plt.ylabel('$r_{xx}$ (k)')
plt.legend(loc="best")
plt.show()
R = []
phi = []
zero = int((len(ACF[1])-1)/2)
line = 0
while (line<zero):
row = []
for j in range(zero):
row.append(ACF[1][zero + j - line])
R.append(row)
line = line + 1
rxx = ACF[1][(zero+1):(zero+1+lags)]
R_inverse = np.linalg.inv(np.array(R))
phi = np.matmul(R_inverse, rxx)
phi = np.insert(phi, 0, 1)
fig, ax = plt.subplots(figsize=(16, 9))
plt.plot(phi, label="PACF", marker='o', color='red')
plt.title('Partial Autocorrelation Function', fontsize=16)
plt.legend(loc='best')
plt.xlabel('Lags (k)')
plt.ylabel('PACF')
plt.show()
mu = 0
sigma = 0.1
epsilon = np.random.normal(mu, sigma, N)
y_ar = []
for i in range(N-1):
sum = 0
n = 1
for n in range(1, len(phi)-1):
sum = phi[n]*n_return[i-n] + epsilon[n] + sum
y_ar.append(sum)
fig, ax = plt.subplots(figsize=(16, 9))
plt.plot(d_values, n_return, label="Normalized Return")
plt.plot(d_values, y_ar, label="AR Model", alpha=0.9)
plt.title('Autoregressive Model', fontsize=16)
plt.legend(loc='best')
plt.xlabel('Date')
plt.ylabel('Return')
plt.show()
var_xt = np.var(n_return)
var_e = np.var(epsilon)
theta = ((var_xt/var_e) - 1 )**(1/2)
arma = []
for j in range(len(y_ar)):
arma.append(y_ar[j] + theta*epsilon[j])
fig, ax = plt.subplots(figsize=(16, 9))
plt.plot(d_values, n_return, label="Normalized Return")
plt.plot(d_values, arma, label="ARMA with $Q = 1$", alpha=.9)
plt.title('ARMA Model', fontsize=16)
plt.legend(loc='best')
plt.xlabel('Date')
plt.ylabel('Return')
plt.show()
r_total = 0
residue = []
for i in range(len(arma)):
r = (n_return[i] - arma[i])**2
r_total = r + r_total
residue.append(r)
print(np.sqrt(r_total))
fig, ax = plt.subplots(figsize=(16, 9))
plt.plot(d_values, residue, label="Residue")
plt.title('Residue', fontsize=16)
plt.legend(loc='best')
plt.xlabel('Date')
plt.ylabel('Residue')
plt.show()
## GARCH Model ##
garch_model = arch_model(log_return, vol='Garch', p=1, q=1, dist='Normal')
model_fit = garch_model.fit()
estimation = model_fit.forecast()
print(model_fit)
omega = 7.0346e-05
alpha = 0.05
beta = 0.85
sig_garch = []
for i in range(len(n_return)):
sig_garch.append(omega + alpha*(l_return[i-1]**2) + beta*(varGARCH[i-1]**2))
fig, ax = plt.subplots(figsize=(16, 9))
plt.plot(d_values, sig_garch, color="royalblue", label="Volatility")
plt.title('Volatility of Log Return by GARCH Model',fontsize=16)
plt.ylabel('Volatility')
plt.xlabel('Date')
plt.legend()
plt.show()
## Markov Chain ##
mc = pd.DataFrame()
mc['labels'] = pd.qcut(n_return, 3, labels=["L", "M", "H"])
mc = mc.sort_index()
col = []
for i in range(0, len(markov_df)):
if markov_df['labels'][i]=='L':
col.append('green')
if markov_df['labels'][i]=='M':
col.append('red')
if markov_df['labels'][i]=='H':
col.append('blue')
fig, ax = plt.subplots(figsize=(16, 9))
plt.title('High, Mean and Low Market', fontsize=16)
for i in range(len(markov_df)):
plt.scatter(x=markov_df.index[i], y=markov_df['labels'][i], s=50, c=col[i])
plt.plot(markov_df['labels'], color="black", alpha=0.2)
plt.yticks()
plt.show()
def build_transition_grid(labelSeries, label):
list_seq = []
for i in range(len(labelSeries)-1):
list_seq.append(labelSeries[i] + '-' + labelSeries[i+1])
nlabels = pd.Series(data=list_seq)
uniqueValues = nlabels.unique()
count = nlabels.value_counts(normalize=True)
print(count)
build_transition_grid(markov_df['labels'], ['L', 'H', 'M'])