-
Notifications
You must be signed in to change notification settings - Fork 4
/
StockPrediction_mv_Model2.py
258 lines (180 loc) · 8.24 KB
/
StockPrediction_mv_Model2.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
import tensorflow as tf
import matplotlib as mplt
mplt.use('agg') # Must be before importing matplotlib.pyplot or pylab!
import matplotlib.pyplot as plt
import numpy as np
import random
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from math import sqrt
np.random.seed(1)
tf.set_random_seed(1)
class RNNConfig():
input_size = 1
num_steps = 2
lstm_size = 128
num_layers = 1
keep_prob = 0.8
batch_size = 64
init_learning_rate = 0.001
learning_rate_decay = 0.99
init_epoch = 3 # 5
max_epoch = 30 # 100 or 50
features = 2
test_ratio = 0.2
fileName = 'AIG.csv'
tf.reset_default_graph()
graph = tf.Graph()
column1_min = 10
column1_max = 2000
column2_min = 0
column2_max = 50000000
hiddenunits = 10
column1 = 'Close'
column2 = 'Volume'
config = RNNConfig()
def segmentation(data):
seq = [price for tup in data[[config.column2, config.column1]].values for price in tup]
seq = np.array(seq)
# split into items of features
seq = [np.array(seq[i * config.features: (i + 1) * config.features])
for i in range(len(seq) // config.features)]
# split into groups of num_steps
X = np.array([seq[i: i + config.num_steps] for i in range(len(seq) - config.num_steps)])
y = np.array([seq[i + config.num_steps] for i in range(len(seq) - config.num_steps)])
return X, y
def scale(data):
data[config.column1] = (data[config.column1] - config.column1_min) / (config.column1_max - config.column1_min)
data[config.column2] = (data[config.column2] - config.column2_min) / (config.column2_max - config.column2_min)
return data
def pre_process():
stock_data = pd.read_csv(config.fileName)
stock_data = stock_data.reindex(index=stock_data.index[::-1])
# ---for segmenting original data ---------------------------------
original_data = pd.read_csv(config.fileName)
original_data = original_data.reindex(index=original_data.index[::-1])
train_size = int(len(stock_data) * (1.0 - config.test_ratio))
train_data = stock_data[:train_size]
test_data = stock_data[train_size:]
original_data = original_data[train_size:]
# -------------- processing train data---------------------------------------
scaled_train_data = scale(train_data)
train_X, train_y = segmentation(scaled_train_data)
# get only close value
train_y = [train_y[i][1] for i in range(len(train_y))]
# -------------- processing test data---------------------------------------
scaled_test_data = scale(test_data)
test_X, test_y = segmentation(scaled_test_data)
# get only close value
test_y = [test_y[i][1] for i in range(len(test_y))]
# ----segmenting original test data-----------------------------------------------
nonescaled_X, nonescaled_y = segmentation(original_data)
# get only close value
nonescaled_y = [nonescaled_y[i][1] for i in range(len(nonescaled_y))]
return train_X, train_y, test_X, test_y, nonescaled_y
def generate_batches(train_X, train_y, batch_size):
num_batches = int(len(train_X)) // batch_size
if batch_size * num_batches < len(train_X):
num_batches += 1
batch_indices = range(num_batches)
for j in batch_indices:
batch_X = train_X[j * batch_size: (j + 1) * batch_size]
batch_y = train_y[j * batch_size: (j + 1) * batch_size]
assert set(map(len, batch_X)) == {config.num_steps}
yield batch_X, batch_y
def mean_absolute_percentage_error(y_true, y_pred):
y_true, y_pred = np.array(y_true), np.array(y_pred)
return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
def plot(true_vals,pred_vals,name):
days = range(len(true_vals))
plt.plot(days, pred_vals, label='pred close')
plt.plot(days, true_vals, label='truth close')
plt.legend(loc='upper left', frameon=False)
plt.xlabel("day")
plt.ylabel("closing price")
plt.grid(ls='--')
plt.savefig(name, format='png', bbox_inches='tight', transparent=False)
plt.close()
def _create_one_cell():
with config.graph.as_default():
tf.set_random_seed(1)
lstm_cell = tf.contrib.rnn.LSTMCell(config.lstm_size, state_is_tuple=True)
lstm_cell = tf.contrib.rnn.DropoutWrapper(lstm_cell, output_keep_prob=config.keep_prob)
return lstm_cell
def train_test():
train_X, train_y, test_X, test_y, nonescaled_y = pre_process()
# Add nodes to the graph
with config.graph.as_default():
tf.set_random_seed(1)
learning_rate = tf.placeholder(tf.float32, None, name="learning_rate")
inputs = tf.placeholder(tf.float32, [None, config.num_steps, config.features], name="inputs")
targets = tf.placeholder(tf.float32, [None], name="targets")
keep_prob = tf.placeholder(tf.float32, None, name="keep_prob")
# Stack up multiple LSTM layers, for deep learning
cell = tf.contrib.rnn.MultiRNNCell(
[_create_one_cell() for _ in range(config.num_layers)],
state_is_tuple=True
) if config.num_layers > 1 else _create_one_cell()
val1, _ = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32)
val = tf.transpose(val1, [1, 0, 2])
last = tf.gather(val, int(val.get_shape()[0]) - 1, name="last_lstm_output")
# hidden = tf.layers.dense(last, units=config.hiddenunits, activation=tf.nn.relu)
weight = tf.Variable(tf.truncated_normal([config.lstm_size, config.input_size]))
bias = tf.Variable(tf.constant(0.1, shape=[config.input_size]))
prediction = tf.matmul(last, weight) + bias
loss = tf.reduce_mean(tf.square(prediction - targets))
optimizer = tf.train.AdamOptimizer(learning_rate)
minimize = optimizer.minimize(loss)
# --------------------training------------------------------------------------------
with tf.Session(graph=config.graph) as sess:
tf.set_random_seed(1)
tf.global_variables_initializer().run()
iteration = 1
learning_rates_to_use = [
config.init_learning_rate * (
config.learning_rate_decay ** max(float(i + 1 - config.init_epoch), 0.0)
) for i in range(config.max_epoch)]
for epoch_step in range(config.max_epoch):
current_lr = learning_rates_to_use[epoch_step]
for batch_X, batch_y in generate_batches(train_X, train_y, config.batch_size):
train_data_feed = {
inputs: batch_X,
targets: batch_y,
learning_rate: current_lr,
keep_prob: config.keep_prob
}
train_loss, _, value = sess.run([loss, minimize, val1], train_data_feed)
if iteration % 5 == 0:
print("Epoch: {}/{}".format(epoch_step, config.max_epoch),
"Iteration: {}".format(iteration),
"Train loss: {:.3f}".format(train_loss))
iteration += 1
saver = tf.train.Saver()
saver.save(sess, "checkpoints_stock/stock_pred.ckpt")
# --------------------testing------------------------------------------------------
with tf.Session(graph=config.graph) as sess:
tf.set_random_seed(1)
saver.restore(sess, tf.train.latest_checkpoint('checkpoints_stock'))
test_data_feed = {
learning_rate: 0.0,
keep_prob: 1.0,
inputs: test_X,
targets: test_y,
}
test_pred = sess.run(prediction, test_data_feed)
pred_vals = [(pred * (config.column1_max - config.column1_min)) + config.column1_min for pred in test_pred]
pred_vals = np.array(pred_vals)
pred_vals = pred_vals.flatten()
pred_vals = pred_vals.tolist()
plot(nonescaled_y, pred_vals, "Stock price Prediction VS Truth mv2.png")
meanSquaredError = mean_squared_error(nonescaled_y, pred_vals)
rootMeanSquaredError = sqrt(meanSquaredError)
print("RMSE:", rootMeanSquaredError)
mae = mean_absolute_error(nonescaled_y, pred_vals)
print("MAE:", mae)
mape = mean_absolute_percentage_error(nonescaled_y, pred_vals)
print("MAPE:", mape)
if __name__ == '__main__':
train_test()