-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_model.py
More file actions
277 lines (206 loc) · 10 KB
/
build_model.py
File metadata and controls
277 lines (206 loc) · 10 KB
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
import pandas as pd
import yfinance as yf
from yahoo_earnings_calendar import YahooEarningsCalendar
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from tensorflow import keras
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.layers import LSTM
from keras.layers import GRU
import pandas as pd
import numpy as np
import math
import datetime
import time
def build_lstm_model(kode_saham):
ticker = yf.Ticker(kode_saham)
# Fetch the data
ticker = kode_saham
last_date = datetime.date.today()
csv_data = yf.download(ticker, '2017-01-01', last_date)
batch_size = 32
epoch = 100
csv_data.head()
# Create the data
csv_data['TradeDate'] = csv_data.index
# Plot the stock prices
csv_data.plot(x = 'TradeDate', y = 'Close', kind = 'line', figsize = (20,6), rot = 20)
full_data=csv_data[['Close']].values
print(full_data[0:5])
# Choosing between Standardization or normalization
sc = MinMaxScaler()
data_scaler = sc.fit(full_data)
x = data_scaler.transform(full_data)
print('### After Normalization ###')
x[0:5]
# Printing last 10 values of the scaled data which we have created above for the last model
# Here I am changing the shape of the data to one dimensional array because
# for Multi step data preparation we need to x input in this fashion
x = x.reshape(x.shape[0],)
print('Scaled Prices')
print(x[-10:])
# Split into samples
x_samples = list()
y_samples = list()
n_row = len(x)
last_time_step = 15 # next few day's Price Prediction is based on last how many past day's prices
future_time_step = 7 # How many days in future you want to predict the prices
# Iterate thru the values to create combinations
for i in range(last_time_step , n_row - future_time_step , 1):
x_sample = x[i-last_time_step:i]
y_sample = x[i:i+future_time_step]
x_samples.append(x_sample)
y_samples.append(y_sample)
################################################
# Reshape the Input as a 3D (samples, Time Steps, Features)
x_data = np.array(x_samples)
x_data = x_data.reshape(x_data.shape[0], x_data.shape[1], 1)
# We do not reshape y as a 3D data as it is supposed to be a single column only
y_data = np.array(y_samples)
# Choose the number of testing data records
# test_record = int(len(csv_data) - (len(csv_data) * 80 / 100))
# Split the data into train and test
# x_train = x_data[:-test_record]
# x_test = x_data[-test_record:]
# y_train = y_data[:-test_record]
# y_test = y_data[-test_record:]
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size = 0.2, random_state = 42)
############################################
# # Visualizing the input and output being sent to the LSTM model
# for inp, out in zip(x_train[0:2], y_train[0:2]):
# print(inp,'--', out)
# Defining Input shapes for LSTM
last_time_step = x_train.shape[1]
n_feature = x_train.shape[2]
print("Number of last_time_step:", last_time_step)
print("Number of Features:", n_feature)
# Initialising the RNN
regressor = Sequential()
# Adding the First input hidden layer and the LSTM layer
# return_sequences = True, means the output of every time step to be shared with hidden next layer
regressor.add(LSTM(units = 50, activation = 'relu', input_shape = (last_time_step, n_feature), return_sequences = True))
regressor.add(Dropout(0.2))
# Adding the Second Second hidden layer and the LSTM layer
regressor.add(LSTM(units = 50, activation = 'relu', input_shape = (last_time_step, n_feature), return_sequences = True))
regressor.add(Dropout(0.2))
# Adding the Second Third hidden layer and the LSTM layer
regressor.add(LSTM(units = 50, activation = 'relu', input_shape = (last_time_step, n_feature), return_sequences = True))
regressor.add(Dropout(0.2))
# Adding the Second Fourth hidden layer and the LSTM layer
regressor.add(LSTM(units = 50, activation = 'relu', return_sequences = False ))
regressor.add(Dropout(0.2))
# Adding the output layer
regressor.add(Dense(units = future_time_step))
# Compiling the RNN
regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')
##################################################
# Measuring the time taken by the model to train
start_time = time.time()
# Fitting the RNN to the Training set
result = regressor.fit(x_train, y_train, batch_size = batch_size, epochs = epoch, validation_data = [x_test, y_test])
end_time = time.time()
# Making predictions on test data
predicted_price = regressor.predict(x_test)
predicted_price = data_scaler.inverse_transform(predicted_price)
# Getting the actual price values for testing data
actual_value = y_test
actual_value = data_scaler.inverse_transform(y_test)
regressor.save('./model/' + kode_saham.replace('.', '').lower() + '_training_lstm_model_' + start_date + '_' + last_date + '_input' + str(last_time_step) + '_batch' + str(batch_size) + '_epoch' + str(epoch) + '.h5')
return "Success"
def build_gru_model(kode_saham):
ticker = yf.Ticker(kode_saham)
# Fetch the data
ticker = kode_saham
last_date = datetime.date.today()
csv_data = yf.download(ticker, '2017-01-01', last_date)
batch_size = 32
epoch = 100
csv_data.head()
# Create the data
csv_data['TradeDate'] = csv_data.index
# Plot the stock prices
csv_data.plot(x = 'TradeDate', y = 'Close', kind = 'line', figsize = (20,6), rot = 20)
full_data=csv_data[['Close']].values
print(full_data[0:5])
# Choosing between Standardization or normalization
sc = MinMaxScaler()
data_scaler = sc.fit(full_data)
x = data_scaler.transform(full_data)
print('### After Normalization ###')
x[0:5]
# Printing last 10 values of the scaled data which we have created above for the last model
# Here I am changing the shape of the data to one dimensional array because
# for Multi step data preparation we need to x input in this fashion
x = x.reshape(x.shape[0],)
# Split into samples
x_samples = list()
y_samples = list()
n_row = len(x)
last_time_step = 15 # next few day's Price Prediction is based on last how many past day's prices
future_time_step = 7 # How many days in future you want to predict the prices
# Iterate thru the values to create combinations
for i in range(last_time_step , n_row - future_time_step , 1):
x_sample = x[i-last_time_step:i]
y_sample = x[i:i+future_time_step]
x_samples.append(x_sample)
y_samples.append(y_sample)
################################################
# Reshape the Input as a 3D (samples, Time Steps, Features)
x_data = np.array(x_samples)
x_data = x_data.reshape(x_data.shape[0], x_data.shape[1], 1)
# We do not reshape y as a 3D data as it is supposed to be a single column only
y_data = np.array(y_samples)
# Choose the number of testing data records
# test_record = int(len(csv_data) - (len(csv_data) * 80 / 100))
# Split the data into train and test
# x_train = x_data[:-test_record]
# x_test = x_data[-test_record:]
# y_train = y_data[:-test_record]
# y_test = y_data[-test_record:]
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size = 0.2, random_state = 42)
############################################
# Defining Input shapes for GRU
last_time_step = x_train.shape[1]
n_feature = x_train.shape[2]
print("Number of last_time_step:", last_time_step)
print("Number of Features:", n_feature)
# Initialising the RNN
regressor = Sequential()
# Adding the First input hidden layer and the LSTM layer
# return_sequences = True, means the output of every time step to be shared with hidden next layer
regressor.add(GRU(units = 50, activation = 'relu', input_shape = (last_time_step, n_feature), return_sequences = True))
regressor.add(Dropout(0.2))
# Adding the Second Second hidden layer and the LSTM layer
regressor.add(GRU(units = 50, activation = 'relu', input_shape = (last_time_step, n_feature), return_sequences = True))
regressor.add(Dropout(0.2))
# Adding the Second Third hidden layer and the LSTM layer
regressor.add(GRU(units = 50, activation = 'relu', input_shape = (last_time_step, n_feature), return_sequences = True))
regressor.add(Dropout(0.2))
# Adding the Second Fourth hidden layer and the LSTM layer
regressor.add(GRU(units = 50, activation = 'relu', return_sequences = False ))
regressor.add(Dropout(0.2))
# Adding the output layer
regressor.add(Dense(units = future_time_step))
# Compiling the RNN
regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')
##################################################
# Measuring the time taken by the model to train
start_time = time.time()
# Fitting the RNN to the Training set
result = regressor.fit(x_train, y_train, batch_size = batch_size, epochs = epoch, validation_data = [x_test, y_test])
end_time = time.time()
# Making predictions on test data
predicted_price = regressor.predict(x_test)
predicted_price = data_scaler.inverse_transform(predicted_price)
print(predicted_price)
# Getting the actual_valueinal price values for testing data
actual_value=y_test
actual_value=data_scaler.inverse_transform(y_test)
print(actual_value)
# Accuracy of the predictions
# print('Accuracy:', 100 - (100*(abs(actual_value-predicted_price)/actual_value)).mean())
regressor.save('./model/' + kode_saham.replace('.', '').lower() + '_training_gru_model_' + start_date + '_' + last_date + '_input' + str(last_time_step) + '_batch' + str(batch_size) + '_epoch' + str(epoch) + '.h5')
return "Success"