@london_lueilwitz
To predict future stock prices using LSTM (Long Short-Term Memory) in Keras, you can follow the steps outlined below:
- Import the required libraries:
1
2
3
4
5
|
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import LSTM, Dropout, Dense
from sklearn.preprocessing import MinMaxScaler
|
- Load and preprocess the stock price data:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# Load the stock price data
df = pd.read_csv('stock_prices.csv')
# Select only the date and closing price columns
df = df[['date', 'close']]
# Normalize the closing prices between 0 and 1
scaler = MinMaxScaler(feature_range=(0, 1))
df['close'] = scaler.fit_transform(df['close'].values.reshape(-1, 1))
# Split the data into training and testing sets
train_size = int(len(df) * 0.8)
train_data = df.iloc[:train_size, :]
test_data = df.iloc[train_size:, :]
|
- Prepare the data for LSTM training:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
def create_lstm_dataset(dataset, time_step):
data_X, data_Y = [], []
for i in range(len(dataset) - time_step):
data_X.append(dataset[i:(i + time_step), 0])
data_Y.append(dataset[i + time_step, 0])
return np.array(data_X), np.array(data_Y)
# Convert the training and testing data into LSTM datasets
time_step = 60
X_train, y_train = create_lstm_dataset(train_data.values, time_step)
X_test, y_test = create_lstm_dataset(test_data.values, time_step)
# Reshape the input data for LSTM
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
|
- Build and train the LSTM model:
1
2
3
4
5
6
7
8
9
10
11
|
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1)))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=50))
model.add(Dropout(0.2))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(X_train, y_train, epochs=50, batch_size=32)
|
- Make predictions using the trained model:
1
2
3
4
5
6
7
8
9
10
|
# Predict the stock prices for the test data
predictions = model.predict(X_test)
predictions = scaler.inverse_transform(predictions)
# Compare the predicted prices with the actual prices
actual_prices = scaler.inverse_transform(test_data['close'].values.reshape(-1, 1))
# Calculate the root mean squared error (RMSE)
rmse = np.sqrt(np.mean((predictions - actual_prices)**2))
print('RMSE:', rmse)
|
This LSTM model can be used to predict future stock prices by feeding new input data and obtaining predictions from the model.