-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTask -1 - Stock Prediction Using LSTM.py
More file actions
382 lines (195 loc) · 7.46 KB
/
Copy pathTask -1 - Stock Prediction Using LSTM.py
File metadata and controls
382 lines (195 loc) · 7.46 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
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
#!/usr/bin/env python
# coding: utf-8
# # Intern - Data Science
# ## Task 1 : Stock Prediction Using LSTM:
# ----By Devalla Ganesh Babu
# Stock market prediction and forecasting are crucial tasks in the field of finance. Predicting the future trends and prices of stocks can assist investors, traders, and financial institutions in making informed decisions. In this project, we aim to predict and forecast the stock prices of the company "AMAZON(Amazon.csv)" using a Stacked Long Short-Term Memory (LSTM) model.
# In[2]:
# Import main libraries
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import seaborn as sns # for photing and viewing data
import matplotlib.pyplot as plt# plotting library
# In[3]:
df=pd.read_csv('F:/Bharat Intern/Amazon.csv')
# In[4]:
df.head()
# In[5]:
df.set_index('Date',inplace = True)# Set the date to be the index
# In[6]:
# resorting the data
df.index = pd.to_datetime(df.index,format='%Y-%m-%d')
# In[7]:
df.head()
# # Now Plots
# In[8]:
df[['Open','Close','High','Low']].plot(figsize = (20,12))
plt.title('Amazon Stock at all time')
# In[9]:
df[['Open','Close']].plot(figsize = (20,10), alpha = 1)
plt.title('Amazon Stock price action')
plt.xlabel('Date')
plt.ylabel('Stock action')
# In[10]:
df[['Open','High']].plot(figsize = (20,10), alpha = 1)
plt.title('Amazon Stock price action')
plt.xlabel('Date')
plt.ylabel('Stock action')
# In[11]:
df[['Low','Close']].plot(figsize = (20,10), alpha = 1)
plt.title('Amazon Stock price action')
plt.xlabel('Date')
plt.ylabel('Stock action')
# In[12]:
df['Volume'].plot(figsize = (20,10), alpha = 1)
plt.title('Amazon Stock price action')
plt.xlabel('Date')
plt.ylabel('Stock action')
# In[13]:
df['Adj Close'].plot(figsize = (20,10), alpha = 1)
plt.title('Amazon Stock price action')
plt.xlabel('Date')
plt.ylabel('Stock action')
# # From the previous analysis and visualization, it can take the data from 2015 as the previous years doesn't important, not have a stock price variance
# In[14]:
Ama = df['2010':'2022']
Ama['Open'].plot(figsize = (20,10), alpha = 1)
plt.title('Amazon Stock Price Action form 2012 to 2021')
# In[15]:
Ama[['Open','High']].plot(figsize = (20,10), alpha = 1)
plt.title('Amazon Stock Price Action form 2012 to 2021')
# In[16]:
Ama['Adj Close'].plot(figsize = (20,10), alpha = 1)
plt.title('Amazon Stock Price Action form 2010 to 2022')
# In[17]:
Ama['Volume'].plot(figsize = (20,10), alpha = 1)
plt.title('Amazon Stock Price Action form 2010 to 2022')
# In[18]:
Ama.describe()
# # Augmented Dickey Fuller Test (ADF)
# ADF test is used to determine the presence of unit root in the series, and hence helps in understand if the series is stationary or not
# In[19]:
from statsmodels.tsa.stattools import adfuller
def adf_test(timeseries):
#Perform Dickey-Fuller test:
print ('Results of Dickey-Fuller Test:')
dftest = adfuller(timeseries, autolag='AIC')
dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used'])
for key,value in dftest[4].items():
dfoutput['Critical Value (%s)'%key] = value
print (dfoutput)
# In[20]:
print(adf_test(df['High']))
# In[21]:
print(adf_test(df['High'].resample('MS').mean()))
# In[22]:
Ama_diff = Ama['Open'].resample('MS').mean() - Ama['Open'].resample('MS').mean().shift(1)
Ama_open_diff = Ama_diff.dropna()
Ama_open_diff.plot()
print(adf_test(Ama_open_diff))
# # Kwiatkowski-Phillips-Schmidt-Shin Test (KPSS)
# another test for checking the stationarity of a time series
# In[23]:
from statsmodels.tsa.stattools import kpss
def kpss_test(timeseries):
print("Results of KPSS Test:")
kpsstest = kpss(timeseries, regression="c", nlags="auto")
kpss_output = pd.Series(
kpsstest[0:3], index=["Test Statistic", "p-value", "Lags Used"]
)
for key, value in kpsstest[3].items():
kpss_output["Critical Value (%s)" % key] = value
print(kpss_output)
# In[24]:
kpss_test(Ama['High'])
# In[25]:
Ama["High_diff"] = Ama["High"] - Ama["High"].shift(1)
Ama["High_diff"].dropna().plot(figsize=(12, 8))
# In[26]:
kpss_test(Ama['High_diff'].dropna())
# In[27]:
kpss_test(Ama['High_diff'].resample('MS').mean().dropna())
# In[28]:
kpss_test(Ama['High_diff'].resample('MS').std().dropna())
# In[29]:
adf_test(Ama['High_diff'].dropna())
# # Data Preprocessing
# In[30]:
train_Ama = Ama['High'].iloc[:-4]
# Take ramdom 6 variables
X_train=[]
y_train=[]
for i in range(2, len(train_Ama)):
X_train.append(train_Ama[i-2:i])
y_train.append(train_Ama[i])
# In[31]:
import math
train_len = math.ceil(len(train_Ama)*0.8)
train_len
# In[32]:
# For Model and apply RNN + LSTM
from tensorflow.keras.layers import LSTM
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Dropout, TimeDistributed
# In[33]:
X_train, y_train= np.array(X_train), np.array(y_train)
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
# In[34]:
model=Sequential()
model.add(LSTM(50,activation='relu', input_shape=(X_train.shape[1],1)))
model.add(Dense(25))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.summary()
model.fit(X_train, y_train, epochs=10, batch_size=100, verbose=2)
# In[36]:
losse = pd.DataFrame(model.history.history)
losse[['loss']].plot()
# In[37]:
test_data = train_Ama[train_len-2:]
X_val=[]
Y_val=[]
for i in range(2, len(test_data)):
X_val.append(test_data[i-2:i])
Y_val.append(test_data[i])
# In[38]:
X_val, Y_val = np.array(X_val), np.array(Y_val)
X_val = np.reshape(X_val, (X_val.shape[0], X_val.shape[1],1))
prediction = model.predict(X_val)
# In[39]:
from sklearn.metrics import mean_squared_error
# Know the model error accuracy | the model accuracy
lstm_train_pred = model.predict(X_train)
lstm_valid_pred = model.predict(X_val)
print('Train rmse:', np.sqrt(mean_squared_error(y_train, lstm_train_pred)))
print('Validation rmse:', np.sqrt(mean_squared_error(Y_val, lstm_valid_pred)))
# In[40]:
valid = pd.DataFrame(train_Ama[train_len:])
valid['Predictions']=lstm_valid_pred
plt.figure(figsize=(16,8))
plt.plot(valid[['High','Predictions']])
plt.legend(['Validation','Predictions'])
plt.show()
# In[41]:
# data frame to see the percentage of error between real and predicted
variance = []
for i in range(len(valid)):
variance.append(valid['High'][i]-valid['Predictions'][i])
variance = pd.DataFrame(variance)
variance.describe()
# In[42]:
train = train_Ama[:train_len]
valid = pd.DataFrame(train_Ama[train_len:])
valid['Predictions']=lstm_valid_pred
plt.figure(figsize=(16,8))
plt.title('Model LSTM')
plt.xlabel('Date')
plt.ylabel('Amazon Price USD')
plt.plot(train)
plt.plot(valid[['High','Predictions']])
plt.legend(['Train','Val','Predictions'])
plt.show()
# # Results
# The results of the Stock Market Prediction and Forecasting project depend on the specific implementation and training of the Stacked LSTM model. By training the model on historical stock price data, we can obtain predictions and forecasts for future stock prices.
#
# The performance of the model can be analyzed using evaluation metrics such as mean absolute error (MAE) and root mean squared error (RMSE). Lower values of these metrics indicate better predictive accuracy. Additionally, visualizations, such as line plots, can be used to compare the predicted and actual stock prices, providing a visual assessment of the model's performance.