Prediction of Google Stocks Price

In this project, we are going to predict the stocks price of Alphabet Inc. The data contains the stocks price of Google from 2010 to 2019. This project will be implemented by Recurrent Neural Network and LSTM using Python.

The data contains the following columns:

  • Date
  • Open
  • High
  • Low
  • Close
  • Volume


let’s get our environment ready with the libraries we’ll need and then import the data!

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns'fivethirtyeight')

Check out the Data

google_train = pd.read_csv('~/DataSet GitHub/RNN/GOOGLE_STOCK_TRAIN.csv')

Let’s extract the Open feature from data to implement prediction based on that.

training_set = dataset_train.iloc[:, 1:2].values


Feature Scaling

Let’s scale our training data into 0 to 1

from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range = (0, 1))
training_set_scaled = sc.fit_transform(training_set)

Now let’s visualise the training set of data


Now let’s create a data structure with 60 timesteps and 1 output. Recurrent Neural Network will observe the previous 60 timestamps for computing the prediction of next stock price.

X_train = []
y_train = []
for i in range(60, 1258):
    X_train.append(training_set_scaled[i-60:i, 0])
    y_train.append(training_set_scaled[i, 0])
X_train, y_train = np.array(X_train), np.array(y_train)


X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))


Building the RNN

Importing the Keras libraries and packages

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout

Initialising the RNN

regressor = Sequential()

Adding the first LSTM layer and some Dropout regularisation

regressor.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 1)))

Adding a second LSTM layer and some Dropout regularisation

regressor.add(LSTM(units = 50, return_sequences = True))

Adding a third LSTM layer and some Dropout regularisation

regressor.add(LSTM(units = 50, return_sequences = True))

Adding a fourth LSTM layer and some Dropout regularisation

regressor.add(LSTM(units = 50))

Adding the output layer

regressor.add(Dense(units = 1))

Compiling the RNN

regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')

Fitting the RNN to the Training set, y_train, epochs = 200, batch_size = 32)


Making the predictions and visualising the results

Getting the real stock price of 2019

google_test = pd.read_csv('/Users/sadegh/Desktop/DataSet GitHub/RNN/GOOGLE_STOCK_TEST.csv')
real_stock_price = dataset_test.iloc[:, 1:2].values

Getting the predicted stock price of 2019

dataset_total = pd.concat((dataset_train['Open'], dataset_test['Open']), axis = 0)
inputs = dataset_total[len(dataset_total) - len(dataset_test) - 60:].values
inputs = inputs.reshape(-1,1)
inputs = sc.transform(inputs)
X_test = []
for i in range(60, 222):
    X_test.append(inputs[i-60:i, 0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
predicted_stock_price = regressor.predict(X_test)
predicted_stock_price = sc.inverse_transform(predicted_stock_price)


Visualising the results

plt.plot(real_stock_price, color = 'green', label = 'Real Google Stock Price')
plt.plot(predicted_stock_price, color = 'orange', label = 'Predicted Google Stock Price')
plt.title('Google Stock Price Prediction')
plt.ylabel('Google Stock Price')

2989cookie-checkPrediction of Google Stocks Price

Leave a Reply

Your email address will not be published.