Tutorial For Recurrent Neural Network (RNN)
Image by author
A recurrent neural network (RNN) is the type of artificial neural network (ANN) that is used in Apple’s Siri and Google’s voice search. RNN remembers past inputs due to an internal memory which is useful for predicting stock prices, generating sentences, transcriptions, and machine translation.
# !pip install kaggle
# !kaggle datasets download -d kalilurrahman/mastercard-stock-data-latest-and-updated
# !unzip mastercard-stock-data-latest-and-updated -d ./data
The code is inspired from Siddgarth Yadav Intro to RNN
In this project, we are going to use Kaggle’s MasterCard Stock Data from May-25-2006 to Oct-11-2021 and train the LSTM and GRU model to forecast the stock price.
# Importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, Dropout, GRU, Bidirectional
from tensorflow.keras.optimizers import SGD
from tensorflow.random import set_seed
set_seed(455)
np.random.seed(455)
Data Analysis
Converting the Date
column to DateTime format and adding it to index. Dropping irrelevant columns to make the final dataset cleaner.
# First, we get the data
dataset = pd.read_csv(
"data/Mastercard_stock_history.csv", index_col="Date", parse_dates=["Date"]
).drop(["Dividends", "Stock Splits"], axis=1)
print(dataset.head())
print(dataset.describe())
No missing values, the dataset is clean.
dataset.isna().sum()
MasterCard card stock prices have been on the high rise since 2016. It had a dip in the first quarter of 2020 but it gained a stable position in the latter half of the year.
tstart = 2016
tend = 2020
def train_test_plot(dataset, tstart, tend):
dataset.loc[f"{tstart}":f"{tend}", "High"].plot(figsize=(16, 4), legend=True)
dataset.loc[f"{tend+1}":, "High"].plot(figsize=(16, 4), legend=True)
plt.legend([f"Train (Before {tend+1})", f"Test ({tend+1} and beyond)"])
plt.title("MasterCard stock price")
plt.show()
train_test_plot(dataset,tstart,tend)