-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstock_pred.py
76 lines (57 loc) · 2.4 KB
/
stock_pred.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
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import LSTM, Dropout, Dense
from matplotlib.pylab import rcParams
rcParams['figure.figsize'] = 20, 10
from sklearn.preprocessing import MinMaxScaler
scalar = MinMaxScaler(feature_range=(0,1))
df = pd.read_csv("/home/lp-n-12/Downloads/NSE-Tata-Global-Beverages-Limited.csv")
# print(df.head())
df["Date"] = pd.to_datetime(df.Date, format="%Y-%m-%d")
df.index = df['Date']
# plt.figure(figsize=(16, 8))
# plt.plot(df['Close'], label='Close Price history')
# plt.show()
data = df.sort_index(ascending=True, axis=0)
new_dataset = pd.DataFrame(index=range(0,len(df)), columns=['Date', 'Close'])
for i in range(0, len(data)):
new_dataset['Date'][i] = data['Date'][i]
new_dataset['Close'][i] = data['Close'][i]
new_dataset.index = new_dataset.Date
new_dataset.drop("Date", axis=1, inplace=True)
final_dataset = new_dataset.values
train_data = final_dataset[0:987, :]
valid_data = final_dataset[987:, :]
scalar = MinMaxScaler(feature_range=(0,1))
scaled_data = scalar.fit_transform(final_dataset)
x_train_data, y_train_data = [], []
for i in range(60, len(train_data)):
x_train_data.append(scaled_data[i-60:i, 0])
y_train_data.append(scaled_data[i, 0])
x_train_data, y_train_data = np.array(x_train_data), np.array(y_train_data)
x_train_data = np.reshape(x_train_data,(x_train_data.shape[0], x_train_data.shape[1], 1))
lstm_model = Sequential()
lstm_model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train_data.shape[1],1)))
lstm_model.add(LSTM(units=50))
lstm_model.add(Dense(1))
lstm_model.compile(loss='mean_squared_error', optimizer='adam')
lstm_model.fit(x_train_data, y_train_data, epochs=1, batch_size=1, verbose=2)
inputs_data = new_dataset[len(new_dataset)-len(valid_data)-60:].values
inputs_data = inputs_data.reshape(-1, 1)
inputs_data = scalar.transform(inputs_data)
x_test = []
for i in range(60, inputs_data.shape[0]):
x_test.append(inputs_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))
closing_price = lstm_model.predict(x_test)
closing_price = scalar.inverse_transform(closing_price)
lstm_model.save('saved_lstm_model.h5')
train_data = new_dataset[:987]
valid_data = new_dataset[987:]
valid_data['Predictions'] = closing_price
plt.plot(train_data['Close'])
plt.plot(valid_data[['Close', "Predictions"]])
plt.show()