-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPycharmCodeStockPrediction.py
170 lines (88 loc) · 3.22 KB
/
PycharmCodeStockPrediction.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
#!/usr/bin/env python
# coding: utf-8
# In[16]:
#training code
import pandas as pd
import math
import pandas_datareader as dataread
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense,LSTM
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
df = dataread.DataReader('AAPL', data_source='yahoo', start='2012-01-03', end='2020-12-17')
data=df.filter(['Close'])
dataset =data.values
training_data_len = math.ceil( len(dataset)*.8 )
scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(dataset)
train_data = scaled_data[0: training_data_len, :]
x_train = []
y_train = []
for i in range (60, len(train_data)):
x_train.append(train_data[i-60:i,0])
y_train.append(train_data[i, 0])
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))
model = Sequential()
model.add(LSTM(50, return_sequences=True,input_shape=(x_train.shape[1], 1)))
model.add(LSTM(50, return_sequences=False))
model.add(Dense(25))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(x_train,y_train,
epochs = 100, batch_size=64,verbose=1)
# In[17]:
test_data = scaled_data[training_data_len - 60: , :]
x_test =[]
y_test= dataset[training_data_len:, :]
for i in range (60,len(test_data)):
x_test.append(test_data[i-60:i, 0])
x_test = np.array(x_test)
x_test = np.reshape(x_test,(x_test.shape[0], x_test.shape[1],1))
predictions = model.predict(x_test)
predictions = scaler.inverse_transform(predictions)
rmse = np.sqrt (np.mean(predictions - y_test) **2)
train = data[:training_data_len]
valid = data[training_data_len:]
valid['Predictions'] = predictions
#plotting predictrion of apple stock
plt.figure(figsize=(16, 7))
plt.title('Apple stock prediction Model')
plt.xlabel('Date', fontsize=17)
plt.ylabel('USD $', fontsize=17)
plt.plot(train ['Close'])
plt.plot(valid[['Close', 'Predictions']])
plt.legend (['Trained', 'actual Value', 'Predictions'], loc='lower right')
plt.show()
# In[20]:
print(valid)
# In[43]:
#evaluation
import math
from sklearn.metrics import mean_squared_error
rmse_score = math.sqrt(mean_squared_error(y_test,predictions))
print(f"Root Mean Squared Error(test) :{rmse_score}")
from sklearn.metrics import r2_score
print(f"prediction accuracy :{r2_score(y_test,predictions)}")
# In[30]:
#testing our model for given date for prediction of stock closing price
user=input("Enter date:")
aaple_stock = dataread.DataReader('AAPL', data_source='yahoo', start='2012-01-03', end=user)
new_df = aaple_stock.filter (['Close'])
prev_60_days = new_df[-60:].values
prev_60_days_scaled = scaler.transform(prev_60_days)
x_test= []
x_test.append(prev_60_days_scaled)
x_test = np.array(x_test)
x_test = np.reshape (x_test, (x_test.shape [0], x_test.shape[1], 1))
pred_price = model.predict(x_test)
pred_price = scaler.inverse_transform(pred_price)
print ('predicted prcice of stock is :US $',pred_price[0][0])
# In[33]:
#checking todays stock price
apple_stock2= dataread.DataReader('AAPL', data_source='yahoo', start='2020-07-01', end='2020-07-01')
print(apple_stock2['Close'])
# In[27]:
# In[ ]: