forked from OpenBB-finance/OpenBB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
neural_networks.py
348 lines (287 loc) · 17.5 KB
/
neural_networks.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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import argparse
from helper_funcs import *
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
from TimeSeriesCrossValidation import splitTrain
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, SimpleRNN, Dense, Dropout, Activation, RepeatVector, TimeDistributed
import config_neural_network_models as cfg_nn_models
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from warnings import simplefilter
simplefilter(action='ignore', category=FutureWarning)
# ----------------------------------------------------------------------------------------------------
def build_neural_network_model(Recurrent_Neural_Network, n_inputs, n_days):
model = Sequential()
for idx_layer, d_layer in enumerate(Recurrent_Neural_Network):
# Recurrent Neural Network
if str(*d_layer) is 'SimpleRNN':
# Is this the input layer? If so, define input_shape
if idx_layer == 0:
model.add(SimpleRNN(**d_layer['SimpleRNN'], input_shape=(n_inputs, 1)))
# Is this the last output layer? If so, set units to prediction days
elif idx_layer == (len(Recurrent_Neural_Network)-1):
model.add(SimpleRNN(**d_layer['SimpleRNN'], units=n_days))
else:
model.add(SimpleRNN(**d_layer['SimpleRNN']))
# Long-Short Term-Memory
elif str(*d_layer) is 'LSTM':
# Is this the input layer? If so, define input_shape
if idx_layer == 0:
model.add(LSTM(**d_layer['LSTM'], input_shape=(n_inputs, 1)))
# Is this the last output layer? If so, set units to prediction days
elif idx_layer == (len(Recurrent_Neural_Network)-1):
model.add(LSTM(**d_layer['LSTM'], units=n_days))
else:
model.add(LSTM(**d_layer['LSTM']))
# Dense (Simple Neuron)
elif str(*d_layer) is 'Dense':
# Is this the input layer? If so, define input_shape
if idx_layer == 0:
model.add(Dense(**d_layer['Dense'], input_dim=n_inputs))
# Is this the last output layer? If so, set units to prediction days
elif idx_layer == (len(Recurrent_Neural_Network)-1):
model.add(Dense(**d_layer['Dense'], units=n_days))
else:
model.add(Dense(**d_layer['Dense']))
# Dropout (Regularization)
elif str(*d_layer) is 'Dropout':
model.add(Dropout(**d_layer['Dropout']))
else:
print(f"Incorrect neuron type: {str(*d_layer)}")
return model
# -------------------------------------------------- MLP --------------------------------------------------
def mlp(l_args, s_ticker, s_interval, df_stock):
parser = argparse.ArgumentParser(prog='mlp',
description="""Multilayer Perceptron. """)
parser.add_argument('-d', "--days", action="store", dest="n_days", type=check_positive, default=5,
help='prediction days.')
parser.add_argument('-i', "--input", action="store", dest="n_inputs", type=check_positive, default=40,
help='number of days to use for prediction.')
parser.add_argument('-e', "--epochs", action="store", dest="n_epochs", type=check_positive, default=200,
help='number of training epochs.')
parser.add_argument('-j', "--jumps", action="store", dest="n_jumps", type=check_positive, default=1,
help='number of jumps in training data.')
parser.add_argument('-p', "--pp", action="store", dest="s_preprocessing", default='normalization',
choices=['normalization', 'standardization', 'none'], help='pre-processing data.')
parser.add_argument('-o', "--optimizer", action="store", dest="s_optimizer", default='adam',
choices=['adam', 'adagrad', 'adadelta', 'adamax', 'ftrl', 'nadam', 'optimizer', 'rmsprop', 'sgd'], help='optimization technique.')
parser.add_argument('-l', "--loss", action="store", dest="s_loss", default='mae',
choices=['mae', 'mape', 'mse', 'msle'], help='loss function.')
try:
(ns_parser, l_unknown_args) = parser.parse_known_args(l_args)
if l_unknown_args:
print(f"The following args couldn't be interpreted: {l_unknown_args}\n")
return
# Pre-process data
if ns_parser.s_preprocessing == 'standardization':
scaler = StandardScaler()
stock_train_data = scaler.fit_transform(np.array(df_stock['5. adjusted close'].values.reshape(-1, 1)))
elif ns_parser.s_preprocessing == 'normalization':
scaler = MinMaxScaler()
stock_train_data = scaler.fit_transform(np.array(df_stock['5. adjusted close'].values.reshape(-1, 1)))
else: # No pre-processing
stock_train_data = np.array(df_stock['5. adjusted close'].values.reshape(-1, 1))
# Split training data for the neural network
stock_x, stock_y = splitTrain.split_train(stock_train_data, ns_parser.n_inputs, ns_parser.n_days, numJumps=ns_parser.n_jumps)
stock_x = np.array(stock_x)
stock_x = np.reshape(stock_x, (stock_x.shape[0], stock_x.shape[1]))
stock_y = np.array(stock_y)
stock_y = np.reshape(stock_y, (stock_y.shape[0], stock_y.shape[1]))
# Build Neural Network model
model = build_neural_network_model(cfg_nn_models.MultiLayer_Perceptron, ns_parser.n_inputs, ns_parser.n_days)
model.compile(optimizer=ns_parser.s_optimizer, loss=ns_parser.s_loss)
# Train our model
model.fit(stock_x, stock_y, epochs=ns_parser.n_epochs, verbose=1);
print("")
print(model.summary())
print("")
# Prediction
yhat = model.predict(stock_train_data[-ns_parser.n_inputs:].reshape(1, ns_parser.n_inputs), verbose=0)
# Re-scale the data back
if (ns_parser.s_preprocessing == 'standardization') or (ns_parser.s_preprocessing == 'normalization'):
y_pred_test_t = scaler.inverse_transform(yhat.tolist())
else:
y_pred_test_t = yhat
l_pred_days = get_next_stock_market_days(last_stock_day=df_stock['5. adjusted close'].index[-1], n_next_days=ns_parser.n_days)
df_pred = pd.Series(y_pred_test_t[0].tolist(), index=l_pred_days, name='Price')
# Plotting
plt.plot(df_stock.index, df_stock['5. adjusted close'], lw=3)
plt.title(f"MLP on {s_ticker} - {ns_parser.n_days} days prediction")
plt.xlim(df_stock.index[0], get_next_stock_market_days(df_pred.index[-1], 1)[-1])
plt.xlabel('Time')
plt.ylabel('Share Price ($)')
plt.grid(b=True, which='major', color='#666666', linestyle='-')
plt.minorticks_on()
plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)
plt.plot([df_stock.index[-1], df_pred.index[0]], [df_stock['5. adjusted close'].values[-1], df_pred.values[0]], lw=1, c='tab:green', linestyle='--')
plt.plot(df_pred.index, df_pred, lw=2, c='tab:green')
plt.axvspan(df_stock.index[-1], df_pred.index[-1], facecolor='tab:orange', alpha=0.2)
xmin, xmax, ymin, ymax = plt.axis()
plt.vlines(df_stock.index[-1], ymin, ymax, colors='k', linewidth=3, linestyle='--', color='k')
plt.show()
# Print prediction data
print("Predicted share price:")
df_pred = df_pred.apply(lambda x: f"{x:.2f} $")
print(df_pred.to_string())
print("")
except:
print("")
# -------------------------------------------------- RNN --------------------------------------------------
def rnn(l_args, s_ticker, s_interval, df_stock):
parser = argparse.ArgumentParser(prog='rnn',
description="""Recurrent Neural Network. """)
parser.add_argument('-d', "--days", action="store", dest="n_days", type=check_positive, default=5,
help='prediction days.')
parser.add_argument('-i', "--input", action="store", dest="n_inputs", type=check_positive, default=40,
help='number of days to use for prediction.')
parser.add_argument('-e', "--epochs", action="store", dest="n_epochs", type=check_positive, default=200,
help='number of training epochs.')
parser.add_argument('-j', "--jumps", action="store", dest="n_jumps", type=check_positive, default=1,
help='number of jumps in training data.')
parser.add_argument('-p', "--pp", action="store", dest="s_preprocessing", default='normalization',
choices=['normalization', 'standardization', 'none'], help='pre-processing data.')
parser.add_argument('-o', "--optimizer", action="store", dest="s_optimizer", default='adam', help='optimizer technique',
choices=['adam', 'adagrad', 'adadelta', 'adamax', 'ftrl', 'nadam', 'optimizer', 'rmsprop', 'sgd'])
parser.add_argument('-l', "--loss", action="store", dest="s_loss", default='mae',
choices=['mae', 'mape', 'mse', 'msle'], help='loss function.')
try:
(ns_parser, l_unknown_args) = parser.parse_known_args(l_args)
if l_unknown_args:
print(f"The following args couldn't be interpreted: {l_unknown_args}\n")
return
# Pre-process data
if ns_parser.s_preprocessing == 'standardization':
scaler = StandardScaler()
stock_train_data = scaler.fit_transform(np.array(df_stock['5. adjusted close'].values.reshape(-1, 1)))
elif ns_parser.s_preprocessing == 'normalization':
scaler = MinMaxScaler()
stock_train_data = scaler.fit_transform(np.array(df_stock['5. adjusted close'].values.reshape(-1, 1)))
else: # No pre-processing
stock_train_data = np.array(df_stock['5. adjusted close'].values.reshape(-1, 1))
# Split training data for the neural network
stock_x, stock_y = splitTrain.split_train(stock_train_data, ns_parser.n_inputs, ns_parser.n_days, numJumps=ns_parser.n_jumps)
stock_x = np.array(stock_x)
stock_x = np.reshape(stock_x, (stock_x.shape[0], stock_x.shape[1], 1))
stock_y = np.array(stock_y)
stock_y = np.reshape(stock_y, (stock_y.shape[0], stock_y.shape[1], 1))
# Build Neural Network model
model = build_neural_network_model(cfg_nn_models.Recurrent_Neural_Network, ns_parser.n_inputs, ns_parser.n_days)
model.compile(optimizer=ns_parser.s_optimizer, loss=ns_parser.s_loss)
# Train our model
model.fit(stock_x, stock_y, epochs=ns_parser.n_epochs, verbose=1);
print("")
print(model.summary())
print("")
# Prediction
yhat = model.predict(stock_train_data[-ns_parser.n_inputs:].reshape(1, ns_parser.n_inputs, 1), verbose=0)
# Re-scale the data back
if (ns_parser.s_preprocessing == 'standardization') or (ns_parser.s_preprocessing == 'normalization'):
y_pred_test_t = scaler.inverse_transform(yhat.tolist())
else:
y_pred_test_t = yhat
l_pred_days = get_next_stock_market_days(last_stock_day=df_stock['5. adjusted close'].index[-1], n_next_days=ns_parser.n_days)
df_pred = pd.Series(y_pred_test_t[0].tolist(), index=l_pred_days, name='Price')
# Plotting
plt.plot(df_stock.index, df_stock['5. adjusted close'], lw=3)
plt.title(f"RNN on {s_ticker} - {ns_parser.n_days} days prediction")
plt.xlim(df_stock.index[0], get_next_stock_market_days(df_pred.index[-1], 1)[-1])
plt.xlabel('Time')
plt.ylabel('Share Price ($)')
plt.grid(b=True, which='major', color='#666666', linestyle='-')
plt.minorticks_on()
plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)
plt.plot([df_stock.index[-1], df_pred.index[0]], [df_stock['5. adjusted close'].values[-1], df_pred.values[0]], lw=1, c='tab:green', linestyle='--')
plt.plot(df_pred.index, df_pred, lw=2, c='tab:green')
plt.axvspan(df_stock.index[-1], df_pred.index[-1], facecolor='tab:orange', alpha=0.2)
xmin, xmax, ymin, ymax = plt.axis()
plt.vlines(df_stock.index[-1], ymin, ymax, colors='k', linewidth=3, linestyle='--', color='k')
plt.show()
# Print prediction data
print("Predicted share price:")
df_pred = df_pred.apply(lambda x: f"{x:.2f} $")
print(df_pred.to_string())
print("")
except:
print("")
# -------------------------------------------------- LSTM --------------------------------------------------
def lstm(l_args, s_ticker, s_interval, df_stock):
parser = argparse.ArgumentParser(prog='lstm',
description="""Long-Short Term Memory. """)
parser.add_argument('-d', "--days", action="store", dest="n_days", type=check_positive, default=5,
help='prediction days')
parser.add_argument('-i', "--input", action="store", dest="n_inputs", type=check_positive, default=40,
help='number of days to use for prediction.')
parser.add_argument('-e', "--epochs", action="store", dest="n_epochs", type=check_positive, default=200,
help='number of training epochs.')
parser.add_argument('-j', "--jumps", action="store", dest="n_jumps", type=check_positive, default=1,
help='number of jumps in training data.')
parser.add_argument('-p', "--pp", action="store", dest="s_preprocessing", default='normalization',
choices=['normalization', 'standardization', 'none'], help='pre-processing data.')
parser.add_argument('-o', "--optimizer", action="store", dest="s_optimizer", default='adam', help='optimization technique.',
choices=['adam', 'adagrad', 'adadelta', 'adamax', 'ftrl', 'nadam', 'optimizer', 'rmsprop', 'sgd'])
parser.add_argument('-l', "--loss", action="store", dest="s_loss", default='mae',
choices=['mae', 'mape', 'mse', 'msle'], help='loss function.')
try:
(ns_parser, l_unknown_args) = parser.parse_known_args(l_args)
if l_unknown_args:
print(f"The following args couldn't be interpreted: {l_unknown_args}\n")
return
# Pre-process data
if ns_parser.s_preprocessing == 'standardization':
scaler = StandardScaler()
stock_train_data = scaler.fit_transform(np.array(df_stock['5. adjusted close'].values.reshape(-1, 1)))
elif ns_parser.s_preprocessing == 'normalization':
scaler = MinMaxScaler()
stock_train_data = scaler.fit_transform(np.array(df_stock['5. adjusted close'].values.reshape(-1, 1)))
else: # No pre-processing
stock_train_data = np.array(df_stock['5. adjusted close'].values.reshape(-1, 1))
# Split training data for the neural network
stock_x, stock_y = splitTrain.split_train(stock_train_data, ns_parser.n_inputs, ns_parser.n_days, numJumps=ns_parser.n_jumps)
stock_x = np.array(stock_x)
stock_x = np.reshape(stock_x, (stock_x.shape[0], stock_x.shape[1], 1))
stock_y = np.array(stock_y)
stock_y = np.reshape(stock_y, (stock_y.shape[0], stock_y.shape[1], 1))
# Build Neural Network model
model = build_neural_network_model(cfg_nn_models.Long_Short_Term_Memory, ns_parser.n_inputs, ns_parser.n_days)
model.compile(optimizer=ns_parser.s_optimizer, loss=ns_parser.s_loss)
# Train our model
model.fit(stock_x, stock_y, epochs=ns_parser.n_epochs, verbose=1);
print("")
print(model.summary())
print("")
# Prediction
yhat = model.predict(stock_train_data[-ns_parser.n_inputs:].reshape(1, ns_parser.n_inputs, 1), verbose=0)
# Re-scale the data back
if (ns_parser.s_preprocessing == 'standardization') or (ns_parser.s_preprocessing == 'normalization'):
y_pred_test_t = scaler.inverse_transform(yhat.tolist())
else:
y_pred_test_t = yhat
l_pred_days = get_next_stock_market_days(last_stock_day=df_stock['5. adjusted close'].index[-1], n_next_days=ns_parser.n_days)
df_pred = pd.Series(y_pred_test_t[0].tolist(), index=l_pred_days, name='Price')
# Plotting
plt.plot(df_stock.index, df_stock['5. adjusted close'], lw=3)
plt.title(f"LSTM on {s_ticker} - {ns_parser.n_days} days prediction")
plt.xlim(df_stock.index[0], get_next_stock_market_days(df_pred.index[-1], 1)[-1])
plt.xlabel('Time')
plt.ylabel('Share Price ($)')
plt.grid(b=True, which='major', color='#666666', linestyle='-')
plt.minorticks_on()
plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)
plt.plot([df_stock.index[-1], df_pred.index[0]], [df_stock['5. adjusted close'].values[-1], df_pred.values[0]], lw=1, c='tab:green', linestyle='--')
plt.plot(df_pred.index, df_pred, lw=2, c='tab:green')
plt.axvspan(df_stock.index[-1], df_pred.index[-1], facecolor='tab:orange', alpha=0.2)
xmin, xmax, ymin, ymax = plt.axis()
plt.vlines(df_stock.index[-1], ymin, ymax, colors='k', linewidth=3, linestyle='--', color='k')
plt.show()
# Print prediction data
print("Predicted share price:")
df_pred = df_pred.apply(lambda x: f"{x:.2f} $")
print(df_pred.to_string())
print("")
except:
print("")