-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbenchmark_model.py
176 lines (148 loc) · 5.85 KB
/
benchmark_model.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
import numpy as np
from numpy import random as rand
from numpy.random import normal
import pandas as pd
import helper_funcs as hf
from pysvihmm import hmmsvi, hmmsgd_metaobs
from pybasicbayes.distributions import gaussian
import matplotlib
from matplotlib import pyplot as plt
from pysvihmm import PositiveDefiniteException as PDE
import sys
debug = True
index = 100
# read in data
stock_data = pd.read_csv("../data/mquote201010.csv")
stock_symbols = hf.get_stock_symbols(stock_data)
single_stock = hf.stock_data_in_one_line(stock_data, stock_symbols, index)
# break up stock data into train and test sets
train_size = int(0.2*single_stock.size)
train_set = np.asarray(single_stock[:train_size])
train_data = train_set
test_set = np.asarray(single_stock[train_size:])
# add extra dimension's data
train_index = [i for i in range(train_set.size)]
test_index = [i for i in range(test_set.size)]
# putting two dimensions together into columns
test_data = np.column_stack([test_index, test_set])
train_data = np.column_stack([train_index, train_set])
# PARAMETERS FOR GAUSSIAN, TAKEN FROM TEST FILE
kappa_0 = 1
nu_0 = 4
# prior emissions are gaussian
prior_emit = [gaussian.Gaussian(mu = np.array([0,0,0,0,0]),
sigma = np.eye(5),
mu_0 = np.zeros(5),
kappa_0 = kappa_0,
nu_0 = nu_0),
gaussian.Gaussian(mu = np.array([1,1,1,1,1]),
sigma = np.eye(5),
mu_0 = np.zeros(5),
sigma_0 = np.eye(5),
kappa_0 = kappa_0,
nu_0 = nu_0),
gaussian.Gaussian(mu = np.array([2,2,2,2,2]),
sigma = np.eye(5),
mu_0 = np.zeros(5),
kappa_0 = kappa_0,
nu_0 = nu_0),
gaussian.Gaussian(mu = np.array([3,3,3,3,3]),
sigma = np.eye(5),
mu_0 = np.zeros(5),
sigma_0 = np.eye(5),
kappa_0 = kappa_0,
nu_0 = nu_0),
gaussian.Gaussian(mu = np.array([4,4,4,4,4]),
sigma = np.eye(5),
mu_0 = np.zeros(5),
sigma_0 = np.eye(5),
kappa_0 = kappa_0,
nu_0 = nu_0)]
obs = np.array([prior_emit[int(np.round(4*i/train_set.size))].rvs()[0]
for i in range(train_set.size)])
# set up parameters with intent to burn in
mu_0 = np.zeros(5)
sigma_0 = 0.75 * np.cov(obs.T)
kappa_0 = 0.01
nu_0 = 5
prior_emit = [gaussian.Gaussian(sigma = np.eye(5), mu = np.array([_,_,_,_,_]),
mu_0=mu_0, sigma_0=sigma_0, kappa_0=kappa_0, nu_0=nu_0)
for _ in range(5)]
prior_emit = np.array(prior_emit)
prior_init = np.ones(5)
prior_tran = np.ones((5,5))
maxit = 100
# instantiate model
'''
model = hmmsgd_metaobs.VBHMM(obs = single_stock[:train_size],
prior_init = prior_init,
prior_tran = prior_tran,
prior_emit = prior_emit,
mb_sz = 50,
maxit = maxit,
verbose = True)
'''
print("Model has been instantiated")
# used for keeping track of errors and whatnot
worked = False
iteration = 0
num_iter = [0]*maxit
num_success = 0
num_symmetric_fail = 0
num_positive_def_fail = 0
maxit_reach = -1
# inference step is unstable. Try until it works
trials = 10000
for iteration in range(trials):
try:
sys.stdout.write('\r')
sys.stdout.write("[%-40s] %d%%" % ('='*int(40*iteration/trials),
float(1000)/trials*iteration))
sys.stdout.flush()
model = hmmsgd_metaobs.VBHMM(obs = single_stock[:train_size],
prior_init = prior_init,
prior_tran = prior_tran,
prior_emit = prior_emit,
mb_sz = 50,
maxit = maxit,
verbose = False)
model.infer()
break
except PDE.PositiveDefiniteException as pde:
num_iter[pde.iteration] += 1
if(pde.iteration > 0):
num_success += 1
if(not(pde.symmetric)):
num_symmetric_fail += 1
if(not(pde.positive_definite)):
num_positive_def_fail += 1
if(pde.iteration > maxit_reach):
maxit_reach = pde.iteration
pass
print("\nPercent of errors due to symmetry: " +str(100*float(num_symmetric_fail)/trials))
print("Maximum iteration reached: " + str(maxit_reach))
print("Average number of iterations before one success: " + str(float(trials)/num_success))
if(worked):
# plotting
plt.style.use('ggplot')
matplotlib.rcParams.update({'font.size': 13})
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)
ax1 = fig.add_subplot(311)
ax2 = fig.add_subplot(312)
ax3 = fig.add_subplot(313)
# Turn off axis lines and ticks of the big subplot
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['right'].set_color('none')
ax.tick_params(labelcolor='w', top='off', bottom='off', left='off', right='off')
ax.set_xlabel("Minute")
ax.set_ylabel("Stock Price")
ax1.set_title("Actual Stock Data")
ax1.plot(single_stock[train_size:], 'b')
ax2.set_title("SVI-non-fitted HMM Model Output")
ax2.plot(obs_seq[1], 'k')
ax3.set_title("SVI-fitted HMM model Output")
ax3.plot(post_obs_seq[1], 'g')
plt.show()