Predicting Stock Prices with an LSTM Model in Python

Alberto Gálvez
3 min readFeb 10, 2024

--

Introduction

In the realm of financial analysis, the ability to predict future market trends and behaviors is paramount for informed decision-making. In this context, LSTM (Long Short-Term Memory) models have emerged as powerful tools for predicting financial time series. This article explores the workings of LSTM models and their application in predicting stock prices and other financial indicators.

What are LSTM Models?

LSTM models are a type of recurrent neural network (RNN) renowned for their ability to capture long-term dependencies in sequential data. Unlike traditional RNNs, which may struggle to remember relevant information over extended periods due to the vanishing gradient problem, LSTMs are designed with specialized memory units that enable them to learn and remember complex patterns in sequential data.

Using LSTM Models in Financial Prediction

One of the most prominent applications of LSTM models in the financial field is the prediction of time series, such as stock prices, exchange rates, and other financial indicators. Below is an example of how an LSTM model can be used to predict the closing prices of stocks:

  1. Data Collection

First, historical data on the desired stock’s closing prices, as well as other relevant factors such as trading volume, technical indicators, and economic data, are collected.

import yfinance as yf

# Download historical price data from Yahoo Finance
ticker = "AAPL" # Apple stock symbol
start_date = "2010-01-01"
end_date = "2024-01-01"
data = yf.download(ticker, start=start_date, end=end_date)

# Select closing prices
prices = data['Close'].values.reshape(-1, 1)

2. Data Preprocessing: The data is normalized to fit within the range (0, 1), and then split into training and testing sets.

from sklearn.preprocessing import MinMaxScaler

# Normalize the data
scaler = MinMaxScaler(feature_range=(0, 1))
prices_scaled = scaler.fit_transform(prices)

# Split the data into training and testing sets
train_size = int(len(prices_scaled) * 0.7)
train_data, test_data = prices_scaled[:train_size], prices_scaled[train_size:]

3. Building the LSTM Model: An LSTM model is constructed with an architecture suitable for the problem, including one or more LSTM layers and a dense output layer.

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense

# Build the LSTM model
model = Sequential([
LSTM(units=50, input_shape=(X_train.shape[1], X_train.shape[2])),
Dense(units=1)
])

4. Training and Evaluating the Model: The model is compiled and trained with the training data, and its performance is evaluated using the testing data.

# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')

# Train the model
model.fit(X_train, y_train, epochs=100, batch_size=32)

# Evaluate the model
train_loss = model.evaluate(X_train, y_train, verbose=0)
test_loss = model.evaluate(X_test, y_test, verbose=0)
print(f'Train Loss: {train_loss:.6f}')
print(f'Test Loss: {test_loss:.6f}')

5. Prediction and Results Visualization: Finally, the model is used to predict future closing prices, and the results are visualized alongside the actual data.

# Predict closing prices
train_predictions = model.predict(X_train)
test_predictions = model.predict(X_test)

# Denormalize the predictions
train_predictions = scaler.inverse_transform(train_predictions)
y_train_unscaled = scaler.inverse_transform(y_train)
test_predictions = scaler.inverse_transform(test_predictions)
y_test_unscaled = scaler.inverse_transform(y_test)

# Visualize the results

Conclusion

LSTM models offer an effective approach to predicting financial time series, enabling investors and analysts to anticipate market trends and make informed decisions. By leveraging historical data and advanced machine learning techniques, these models can provide a competitive edge in the financial arena, helping to identify investment opportunities and mitigate risks.

In summary, LSTM models are powerful tools in the toolkit of any financial professional, offering advanced prediction and analysis capabilities that can significantly enhance decision-making in financial markets.

--

--