Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

newTrainLSTM.py 7.2 KB

You have to be logged in to leave a comment. Sign In
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
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import pandas as pd
  4. import yfinance as yf
  5. import pandas_ta as ta
  6. import sqlalchemy as db
  7. from sklearn.model_selection import train_test_split
  8. from sklearn.preprocessing import MinMaxScaler
  9. from keras.models import Sequential
  10. from keras.layers import LSTM, Dense, Dropout
  11. from keras.models import load_model as keras_load_model # Rename the imported function
  12. import matplotlib.pyplot as plt
  13. from keras.initializers import GlorotUniform
  14. from keras.models import Model
  15. from keras.layers import Input, LSTM, Dense, Activation
  16. from keras import optimizers
  17. from keras.callbacks import ModelCheckpoint, EarlyStopping
  18. import joblib
  19. def load_data(file_path, symbol):
  20. """
  21. Load the data for a given company (symbol) from the database
  22. :param file_path: str: The path to the database file (atradebot.db)
  23. :return: pd.DataFrame: The data for the given company
  24. """
  25. # connect to the database
  26. engine = db.create_engine(f'sqlite:///{file_path}', echo=True)
  27. connection = engine.connect()
  28. # fetch the data
  29. query = "SELECT * FROM stocks WHERE symbol = '{}'".format(symbol)
  30. data = pd.read_sql(query, connection)
  31. return data
  32. def preprocess_data(df):
  33. """
  34. Preprocess company data for training the LSTM model
  35. :param df: pd.DataFrame: The company data
  36. :return: np.array: The scaled features,
  37. np.array: The scaled target variable,
  38. np.array: The scaled dataset (features + target variable)
  39. """
  40. # Define the features and target variables
  41. target = ['TargetNextClose']
  42. symbol = df['symbol'].unique()[0] # Get the symbol name
  43. df.dropna(subset=['RSI', 'EMAF', 'EMAM', 'EMAS'], inplace=True)
  44. print(df)
  45. features = df.drop(['symbol', 'close', 'date', 'quarter', 'volume', 'daily_range', 'daily_return', 'high', 'low'], axis=1).columns.tolist() # list
  46. X = df[features].values
  47. y = df[target].values
  48. y_scaler = MinMaxScaler(feature_range=(0, 1))
  49. y_scaled = y_scaler.fit_transform(y)
  50. # Save the target variable scaler for this symbol
  51. y_scaler_filename = f"/Users/anujthakkar/Documents/Purdue/Projects/wisebucks.ai/LSTM/scalers/{symbol}_y_scaler.save"
  52. joblib.dump(y_scaler, y_scaler_filename)
  53. # Apply scaling to the features 'X'
  54. x_scaler = MinMaxScaler(feature_range=(0, 1))
  55. X_scaled = x_scaler.fit_transform(X)
  56. # Save the feature scaler for this symbol
  57. x_scaler_filename = f"/Users/anujthakkar/Documents/Purdue/Projects/wisebucks.ai/LSTM/scalers/{symbol}_x_scaler.save"
  58. joblib.dump(x_scaler, x_scaler_filename)
  59. data_set_scaled = np.concatenate((X_scaled, y_scaled), axis=1)
  60. return X_scaled, y_scaled, data_set_scaled
  61. def prepare_lstm_input(data_set_scaled, backcandles):
  62. """
  63. Prepare the input for the LSTM model
  64. :param data_set_scaled: np.array: The scaled dataset (features + target variable)
  65. :param backcandles: int: The number of previous candles to consider
  66. :return: np.array: The input for the LSTM model, shaped as (num_samples, backcandles, num_features)
  67. np.array: The target variable for the LSTM model
  68. """
  69. # multiple feature from data provided to the model
  70. X = []
  71. print(data_set_scaled.shape[0])
  72. for j in range(8):#data_set_scaled[0].size):#2 columns are target not X
  73. X.append([])
  74. for i in range(backcandles, data_set_scaled.shape[0]):#backcandles+2
  75. X[j].append(data_set_scaled[i-backcandles:i, j])
  76. X=np.moveaxis(X, [0], [2]) #move axis from 0 to position 2
  77. X, yi =np.array(X), np.array(data_set_scaled[backcandles:,-1])
  78. y=np.reshape(yi,(len(yi),1))
  79. print(f'X shape: {X.shape}')
  80. print(f'y shape: {y.shape}')
  81. return X, y
  82. def split_data(X, y, test_size, backcandles):
  83. """
  84. Split the data into training and testing
  85. :param X: np.array: The input for the LSTM model
  86. :param y: np.array: The target variable for the LSTM model
  87. :param test_size: float: The proportion of the dataset to include in the test split
  88. :param backcandles: int: The number of previous candles to consider
  89. :return: np.array: The input for the LSTM model (training set)
  90. """
  91. # Split the data into training and testing
  92. splitlimit = int((1-test_size)*len(X))
  93. X_train, X_test = X[:splitlimit], X[splitlimit:]
  94. y_train, y_test = y[:splitlimit], y[splitlimit:]
  95. print(f'X_train shape: {X_train.shape}'
  96. f' X_test shape: {X_test.shape}')
  97. print(f'y_train shape: {y_train.shape}'
  98. f' y_test shape: {y_test.shape}')
  99. return X_train, X_test, y_train, y_test, splitlimit, backcandles
  100. def build_lstm_model(input_shape, X_train, y_train):
  101. """
  102. Build an LSTM model
  103. :param input_shape: tuple: The shape of the input for the LSTM model
  104. :param X_train: np.array: The input for the LSTM model
  105. :param y_train: np.array: The target variable for the LSTM model
  106. :return: keras.Model: The LSTM model
  107. """
  108. model = Sequential()
  109. # must set return_sequence to False for last LSTM layer
  110. model.add(LSTM(100, input_shape=input_shape, activation='tanh', return_sequences=True))
  111. model.add(Dropout(0.5))
  112. model.add(LSTM(units=100,return_sequences=True))
  113. model.add(Dropout(0.4))
  114. model.add(LSTM(units=50,return_sequences=False))
  115. model.add(Dropout(0.05))
  116. model.add(Dense(1, activation='relu'))
  117. model.compile(loss='mean_squared_error', optimizer='adam')
  118. model.fit(x=X_train, y=y_train, batch_size=10, epochs=50, validation_split = 0.1)
  119. return model
  120. if __name__ == "__main__":
  121. data_file_path = '/Users/anujthakkar/Documents/Purdue/Projects/wisebucks.ai/data/atradebot.db'
  122. epochs = 100
  123. batch_size = 5
  124. backcandles = 6
  125. model_output_text_file = '/Users/anujthakkar/Documents/Purdue/Projects/wisebucks.ai/LSTM/outputs/newModelOutput.txt'
  126. # Get the list of stock symbols from the CSV
  127. stock_df = pd.read_csv('data/sp-500-index-10-29-2023.csv')
  128. symbols = stock_df['Symbol'].tolist()[0:2]
  129. for symbol in symbols:
  130. data_frame = load_data(data_file_path, symbol).drop(['id'], axis=1)
  131. dates = data_frame['date']
  132. X_scaled, y_scaled, data_set_scaled = preprocess_data(data_frame)
  133. X_lstm, y_lstm = prepare_lstm_input(data_set_scaled, backcandles)
  134. X_train, X_test, y_train, y_test, splitlimit, backcandles = split_data(X_lstm, y_lstm, test_size=0.1, backcandles=backcandles)
  135. dates_in_test = dates[splitlimit+backcandles:]
  136. model = build_lstm_model(input_shape=(X_train.shape[1], X_train.shape[2]), X_train=X_train, y_train=y_train)
  137. y_pred = model.predict(X_test)
  138. y_scaler_filename = f"/Users/anujthakkar/Documents/Purdue/Projects/wisebucks.ai/LSTM/scalers/{symbol}_y_scaler.save"
  139. x_scaler_filename = f"/Users/anujthakkar/Documents/Purdue/Projects/wisebucks.ai/LSTM/scalers/{symbol}_x_scaler.save"
  140. # load y_scaler and x_scaler given symbol
  141. y_scaler = joblib.load(y_scaler_filename)
  142. x_scaler = joblib.load(x_scaler_filename)
  143. # inverse transform the predictions
  144. y_pred = y_scaler.inverse_transform(y_pred)
  145. y_test = y_scaler.inverse_transform(y_test)
  146. for i in range(len(y_pred)):
  147. # get the value of the date from dates
  148. print(dates_in_test.iloc[i], y_pred[i], y_test[i])
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...