Stock Price Prediction (Apple) with SimpleRNN

 


Stock Price Prediction (Apple) with SimpleRNN


Recurrent neural networks (RNN) are a class of neural networks that is powerful for modeling sequence data such as time series or natural language.

Schematically, a RNN layer uses a for loop to iterate over the timesteps of a sequence, while maintaining an internal state that encodes information about the timesteps it has seen so far.

In this exercise I'm going to use keras.layers.SimpleRNN, a fully-connected RNN where the output from previous timestep is to be fed to next timestep.

By default, the output of a RNN layer contains a single vector per sample. This vector is the RNN cell output corresponding to the last timestep, containing information about the entire input sequence. The shape of this output is (batch_size, units) where units corresponds to the units argument passed to the layer's constructor.

A RNN layer can also return the entire sequence of outputs for each sample (one vector per timestep per sample), if you set return_sequences=True. The shape of this output is (batch_size, timesteps, units)


Data downloaded from Kaggle:

https://www.kaggle.com/datasets/soheiltehranipour/apple-stock-20132018 


import pandas as pd  
import numpy as np  
from sklearn.preprocessing import MinMaxScaler  
from keras.models import Sequential  
from keras.layers import SimpleRNN, Dropout, Dense  
import matplotlib.pyplot as plt 

Loading data: I am going to read the data from the excel file and extract the values we

want to use to train our model


stock_data = pd.read_csv("AAPL.xls") 
stock_prices = stock_data.iloc[:, 1:2].values 

Scaling the data to improve training stability and convergence:

I am going to scale the stock_prices between 0 and 1 using the MinMaxScaler.


scaler = MinMaxScaler()  # Creating a scaler object
scaled_prices = scaler.fit_transform(stock_prices)

Creating Input Sequences and Labels:

The goal here is to create pairs of input sequences (60 days of stock prices) and corresponding labels (the next day's stock price) for training the model

features, labels = [], [] for i in range(60, len(stock_prices)): features.append(scaled_prices[i-60:i, 0]) labels.append(scaled_prices[i, 0])

features, labels = np.array(features), np.array(labels)

Reshaping data for SimpleRNN:

SimpleRNN layers expect input in a specific shape. Reshaping is done to accommodate the input shape required by the SimpleRNN layer

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

Building the SimpleRNN model:

model = Sequential() 
model.add(SimpleRNN(units=200, activation='relu', input_shape=(features.shape[1], 1)))
model.ad(Dropout(0.3)) 
model.add(Dense(units=1))

Compile and set the optimizer: Configuring the model for training with the Adam optimizer and mean squared error loss

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

Train the model: Fitting the model to the training data for 250 epochs with a batch size of 32

model.fit(features, labels, epochs=250, batch_size=32)

Now we are going to prepare the testing data which is located in another file.

test_data = pd.read_csv("AAPL - Jan2018.xls")
test_prices = test_data.iloc[:, 1:2].values  # Extracting 'Open' stock prices for testing

Concatenate training and testing data:

total_prices = pd.concat((stock_data['Open'], test_data['Open']), axis=0) 

Select the last 60 days for testing: Choosing the last 60 days from the combined data for testing, ensuring continuity with the training data

Similar to the training data, the test input data is scaled to the same range as the training data using the same scaler

test_inputs = total_prices[len(total_prices) - len(test_data) - 60:].values  

test_inputs = test_inputs.reshape(-1, 1)
test_inputs = scaler.transform(test_inputs)

Create sequences for testing:Sequences of 60 days are created for testing, mimicking the input format used during training

test_features = []
for i in range(60, 80):
    test_features.append(test_inputs[i-60:i, 0])

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

Making Predictions

We can now use the trained model to create the predictions

The predictions are then inversely transformed to the original scale for meaningful interpretation

predictions = model.predict(test_features) predictions = scaler.inverse_transform(predictions)

plt.figure(figsize=(10, 6))
plt.plot(test_prices, color='blue', label='Actual Stock Price')
plt.plot(predictions, color='red', label='Predicted Stock Price')
plt.title('Stock Price Prediction with SimpleRNN')
plt.xlabel('Time')
plt.ylabel('Stock Price')
plt.legend()
plt.show()

Comentarios

Entradas populares de este blog

Supervised Classification | hyperparameter optimization and voting ensemble

Convolutional Neural Network - Microplastic image classification PLASTISCAN