Here's a comprehensive example of how to create and train an LSTM (Long Short-Term Memory) model using TensorFlow Keras to predict the closing price of the SPY stock. This code uses historical data with features like Date, Open, High, Low, Close, Volume, and RSI (Relative Strength Index).
# Import necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping
# Load the data
# Replace 'spy_data.csv' with the path to your actual data file
data = pd.read_csv('spy_data.csv', parse_dates=['Date'], index_col='Date')
# Ensure data is sorted by date
data.sort_index(inplace=True)
# Feature selection
features = ['Open', 'High', 'Low', 'Close', 'Volume', 'RSI']
data = data[features]
# Handle missing values if any
data.dropna(inplace=True)
# Feature scaling
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
# Convert the scaled data back to a DataFrame
scaled_data = pd.DataFrame(scaled_data, columns=features, index=data.index)
# Function to create sequences
def create_sequences(data, seq_length):
X = []
y = []
for i in range(seq_length, len(data)):
X.append(data.iloc[i - seq_length:i].values)
y.append(data.iloc[i]['Close'])
return np.array(X), np.array(y)
# Define sequence length
sequence_length = 60 # Using 60 past days to predict the next day
# Create sequences
X, y = create_sequences(scaled_data, sequence_length)
# Split data into training and testing sets (e.g., 80% training, 20% testing)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, shuffle=False
)
# Build the LSTM model
model = Sequential()
# First LSTM layer with Dropout regularization
model.add(
LSTM(
units=50,
return_sequences=True,
input_shape=(X_train.shape[1], X_train.shape[2]),
)
)
model.add(Dropout(0.2))
# Second LSTM layer with Dropout regularization
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
# Third LSTM layer
model.add(LSTM(units=50))
model.add(Dropout(0.2))
# Output layer
model.add(Dense(units=1))
# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
# Early stopping callback to prevent overfitting
early_stopping = EarlyStopping(
monitor='val_loss', patience=10, restore_best_weights=True
)
# Train the model
history = model.fit(
X_train,
y_train,
epochs=100,
batch_size=32,
validation_data=(X_test, y_test),
callbacks=[early_stopping],
verbose=1,
)
# Evaluate the model
loss = model.evaluate(X_test, y_test)
print(f'Test Loss: {loss}')
# Make predictions
predicted_prices = model.predict(X_test)
# Inverse transform the predicted and actual prices
scaler_for_close = MinMaxScaler(feature_range=(0, 1))
scaler_for_close.fit(data[['Close']])
predicted_prices = scaler_for_close.inverse_transform(
predicted_prices.reshape(-1, 1)
)
actual_prices = scaler_for_close.inverse_transform(y_test.reshape(-1, 1))
# Visualize the results
plt.figure(figsize=(14, 5))
plt.plot(
data.index[-len(actual_prices) :],
actual_prices,
color='blue',
label='Actual Close Price',
)
plt.plot(
data.index[-len(predicted_prices) :],
predicted_prices,
color='red',
label='Predicted Close Price',
)
plt.title('SPY Stock Closing Price Prediction')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()
Explanation:
-
Data Loading and Preprocessing:
- Load the Data: Read the CSV file containing historical SPY data. Make sure the 'Date' column is parsed as dates and set as the DataFrame index.
- Sort Data: Ensure the data is sorted in chronological order.
- Feature Selection: Select relevant features for the model.
- Handle Missing Values: Remove any rows with missing values.
- Feature Scaling: Normalize the features using
MinMaxScaler to scale data between 0 and 1.
-
Sequence Creation:
- Define
create_sequences Function: This function creates input sequences (X) and corresponding targets (y) for the LSTM model.
- Set
sequence_length: Determine how many past time steps the model will look at to make a prediction (e.g., 60 days).
-
Data Splitting:
- Train-Test Split: Split the data into training and testing sets without shuffling to maintain the time series order.
-
LSTM Model Building:
- Initialize the Model: Use Keras
Sequential model.
- Add LSTM Layers: Stack multiple LSTM layers with dropout regularization to prevent overfitting.
- Output Layer: Add a fully connected
Dense layer with one unit since we're predicting a single value.
- Compile the Model: Use the 'adam' optimizer and 'mean_squared_error' loss function suitable for regression tasks.
-
Model Training:
- Early Stopping: Use early stopping to monitor validation loss and prevent overfitting.
- Train the Model: Fit the model on the training data and validate on the test data.
-
Evaluation and Prediction:
- Model Evaluation: Evaluate the model's performance on the test set.
- Make Predictions: Use the trained model to predict closing prices.
- Inverse Scaling: Transform the scaled predictions and actual values back to the original scale.
Notes:
- Replace the Data File Path: Ensure you replace
'spy_data.csv' with the actual path to your dataset.
- Adjust Hyperparameters: You might need to adjust parameters like
sequence_length, units, batch_size, and epochs based on your dataset size and computational resources.
- Additional Features: Including technical indicators like RSI can help the model capture more complex patterns in the data.
- Model Improvements: Consider experimenting with different model architectures, adding more layers, or using different activation functions to potentially improve performance.
- Data Sufficiency: Ensure you have enough data to train the model effectively, especially if using longer sequences.
Requirements:
- Python Libraries:
pandas
numpy
matplotlib
scikit-learn
tensorflow
You can install any missing libraries using pip. For example:
pip install pandas numpy matplotlib scikit-learn tensorflow
Conclusion:
This code provides a solid foundation for predicting the SPY stock's closing price using an LSTM neural network. Remember that stock price prediction is complex and can be influenced by many unpredictable factors. It's essential to evaluate the model thoroughly and consider incorporating more features or different modeling techniques for better performance.
Let me know if you need any more assistance or explanations!