Predicting Stock Prices using Tensorflow (LSTM)

Fouad Roumieh
4 min readOct 17, 2023

Predicting stock prices is a challenging task due to the inherent complexity and volatility of financial markets. Machine learning models, particularly Long Short-Term Memory (LSTM) neural networks, can be employed to analyze historical data and attempt to forecast future stock prices.

In this article, we’ll walk through a practical example of utilizing LSTM to predict stock prices using Python and TensorFlow.

Please note that this example uses a simulated dataset for demonstration purposes. The example provided is a simplified demonstration to introduce the concept of using LSTM for predicting stock prices, the LSTM model used here is quite basic. For real-world applications, you would likely need a more sophisticated and well-tuned model to accurately capture the complexities of stock price movements.

What is LSTM?

LSTM, or Long Short-Term Memory, is a type of recurrent neural network (RNN) architecture, which is a class of artificial neural networks well-suited for processing sequences of data. LSTM networks are particularly useful for tasks involving time series analysis, natural language processing, speech recognition, and more.

Let’s explore an example.

1. Data Preprocessing

Before we start, let’s prepare the data for our model. This involves loading, cleaning, and organizing the data into a suitable format.

# Import necessary libraries
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler

# Simulated dataset (replace with your real financial data)
np.random.seed(0)
n = 100 # Number of data points
dates = pd.date_range(start="1/1/2020", periods=n, freq="D")
prices = np.cumsum(np.random.randn(n)) # Simulated stock prices
df = pd.DataFrame({"Date": dates, "Price": prices})

# Normalize the Price column
scaler = MinMaxScaler()
df["Price"] = scaler.fit_transform(df["Price"].values.reshape(-1, 1))

In this step, we load a simulated dataset or your actual stock data. We ensure the prices are on a similar scale to facilitate model training and to make sure if conforms to time-series data.

2. Building the Model

We’ll use a special type of neural network called an LSTM to build our predictive model. Let’s set up the architecture of this model

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

# Prepare the dataset
# n_steps is the number of previous days' prices to consider for prediction
def prepare_data(data, n_steps):
X, y = [], []
for i in range(len(data)):
end_ix = i + n_steps
if end_ix > len(data) - 1:
break
seq_x, seq_y = data[i:end_ix], data[end_ix]
X.append(seq_x)
y.append(seq_y)
return np.array(X), np.array(y)

n_steps = 10 # Number of time steps to consider for prediction

# Prepare the training data
data = df["Price"].values
X, y = prepare_data(data, n_steps)

Here, we defined a function prepare_data that organizes our data into suitable input-output pairs for the LSTM model.

3. Training the Model

Now, let’s train the LSTM model using the training data we prepared.

# Split the data into training and testing sets
train_size = int(0.8 * len(X))
X_train, X_test, y_train, y_test = X[:train_size], X[train_size:], y[:train_size], y[train_size:]

# Reshape the input data for LSTM
X_train = X_train.reshape(-1, n_steps, 1)
X_test = X_test.reshape(-1, n_steps, 1)

# Define the LSTM model
model = Sequential()
model.add(LSTM(50, activation="relu", input_shape=(n_steps, 1)))
model.add(Dense(1))
model.compile(optimizer="adam", loss="mse")

# Train the model
model.fit(X_train, y_train, epochs=50, batch_size=16, verbose=1)

In this step, we split our data into training and testing sets. The LSTM model is then defined and trained using the training data.

4. Making Predictions

Now, let’s use our trained LSTM model to predict future stock prices.

# Predict using the trained model
future_steps = 10 # Number of days to predict
future_data = data[-n_steps:].reshape(-1, n_steps, 1)
predicted_prices = []

for i in range(future_steps):
prediction = model.predict(future_data)[0, 0]
predicted_prices.append(prediction)
future_data = np.roll(future_data, -1, axis=1)
future_data[0, -1] = prediction

# Inverse transform the predicted prices to original scale
predicted_prices = scaler.inverse_transform(np.array(predicted_prices).reshape(-1, 1)).flatten()

This section explains how the trained model predicts future stock prices by iteratively forecasting each day’s value.

5. Visualizing the Predictions

Lastly, let’s visualize the predicted stock prices.

import matplotlib.pyplot as plt

# Plot the predicted prices
plt.plot(predicted_prices, label="Predicted Prices")
plt.xlabel("Days")
plt.ylabel("Price")
plt.legend()
plt.show()

We use a simple plot to visualize the predicted stock prices, making it easier for you to interpret the results.

Unfortunately, the prices going down for the coming day :)

However, in a real-world scenario with actual stock market data, predicting price movements accurately is a very complex task. Stock prices are influenced by a multitude of factors such as market sentiment, economic indicators, news, geopolitical events, and more, making accurate predictions challenging. It’s important to remember that predicting stock prices is inherently uncertain, and models may not capture all the intricacies of the market.

--

--