Skip to content

Commit 6341eb8

Browse files
jeffin07cclauss
authored andcommitted
Added Lstm example for stock predection (TheAlgorithms#1908)
* Added Lstm example for stock predection * Changes after review * changes after build failed * Add Kiera’s to requirements.txt * requirements.txt: Add keras and tensorflow * psf/black Co-authored-by: Christian Clauss <[email protected]>
1 parent 5fc012e commit 6341eb8

File tree

3 files changed

+1317
-1
lines changed

3 files changed

+1317
-1
lines changed
+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
"""
2+
Create a Long Short Term Memory (LSTM) network model
3+
An LSTM is a type of Recurrent Neural Network (RNN) as discussed at:
4+
* http://colah.github.io/posts/2015-08-Understanding-LSTMs
5+
* https://en.wikipedia.org/wiki/Long_short-term_memory
6+
"""
7+
8+
from keras.layers import Dense, LSTM
9+
from keras.models import Sequential
10+
import numpy as np
11+
import pandas as pd
12+
from sklearn.preprocessing import MinMaxScaler
13+
14+
15+
if __name__ == "__main__":
16+
"""
17+
First part of building a model is to get the data and prepare
18+
it for our model. You can use any dataset for stock prediction
19+
make sure you set the price column on line number 21. Here we
20+
use a dataset which have the price on 3rd column.
21+
"""
22+
df = pd.read_csv("sample_data.csv", header=None)
23+
len_data = df.shape[:1][0]
24+
# If you're using some other dataset input the target column
25+
actual_data = df.iloc[:, 1:2]
26+
actual_data = actual_data.values.reshape(len_data, 1)
27+
actual_data = MinMaxScaler().fit_transform(actual_data)
28+
look_back = 10
29+
forward_days = 5
30+
periods = 20
31+
division = len_data - periods * look_back
32+
train_data = actual_data[:division]
33+
test_data = actual_data[division - look_back :]
34+
train_x, train_y = [], []
35+
test_x, test_y = [], []
36+
37+
for i in range(0, len(train_data) - forward_days - look_back + 1):
38+
train_x.append(train_data[i : i + look_back])
39+
train_y.append(train_data[i + look_back : i + look_back + forward_days])
40+
for i in range(0, len(test_data) - forward_days - look_back + 1):
41+
test_x.append(test_data[i : i + look_back])
42+
test_y.append(test_data[i + look_back : i + look_back + forward_days])
43+
x_train = np.array(train_x)
44+
x_test = np.array(test_x)
45+
y_train = np.array([list(i.ravel()) for i in train_y])
46+
y_test = np.array([list(i.ravel()) for i in test_y])
47+
48+
model = Sequential()
49+
model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True))
50+
model.add(LSTM(64, input_shape=(128, 1)))
51+
model.add(Dense(forward_days))
52+
model.compile(loss="mean_squared_error", optimizer="adam")
53+
history = model.fit(
54+
x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4
55+
)
56+
pred = model.predict(x_test)

0 commit comments

Comments
 (0)