A LSTM Time-Series Model for Multivariables Forecasting
A step-by-step guide using stock price data
Introduction
LSTM is a type of recurrent neural network (RNN) well-suited for time-series forecasting tasks, and we have built several LSTM models in the previous articles for one variable prediction. In this step-by-step tutorial, we will walk through the process of building an LSTM (Long Short-Term Memory) model for multiple variable prediction using the same stock price data. We will use historical stock price data for Apple (AAPL) and preprocess it to prepare it for training the LSTM model. The model will be trained to predict the future stock prices based on past prices and volume. We will evaluate the model’s performance using various metrics, including Mean Squared Error (MSE), R-squared (R2), and Root Mean Squared Error (RMSE). Additionally, we will implement the Checkpiont callbacks to save the best trained model.
Step 1: Import Libraries and Load the Dataset
Starting processing the data to create the model, we set up the necessary tools for working with data, scaling data, and building LSTM-based neural network models for sequential data processing.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import LSTM, Dense, Dropout
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from keras.models import load_model
import keras.utils
Step 2: Load the Dataset
In this step, we load the data into Pandas’ DataFrame, and then we visualize the data columns for modelling.
# Load the dataset
data = pd.read_csv("https://raw.githubusercontent.com/NourozR/Stock-Price-Prediction-LSTM/master/apple_share_price.csv")
features = ['Close', 'Volume']
data['Date'] = pd.to_datetime(data['Date'])
data.sort_values('Date', inplace=True)
We select two features, i.e., ‘Close’ and ‘Volume’, and create a LSTM model to forecast them. Now, let’s visualize them as follows.