List of Topics:
Location Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Build a GRU-Based Model for Stock Price Prediction Using Yahoo Finance Data

Building a GRU-Based Model for Stock Price Prediction Using Yahoo Finance Data

Condition for Building a GRU-Based Model for Stock Price Prediction Using Yahoo Finance Data

  • Description:
    This code implements a binary image classification model using MobileNetV2 for classifying cat and dog images. It utilizes transfer learning by freezing the pre-trained layers of MobileNetV2 and adding custom dense layers for classification. The model is trained on the processed images, evaluated with performance metrics, and visualized with a confusion matrix.
Step-by-Step Process
  • Import Libraries:
    Import essential libraries like numpy, tensorflow, PIL, and sklearn for image processing and model building.
  • Load and Inspect Images:
    Load cat and dog images from directories, and visualize samples for inspection.
  • Preprocess Data:
    Resize images to 224x224 pixels, normalize pixel values, and encode labels.
  • Build and Train Model:
    Use MobileNetV2 as the base model, freeze pre-trained layers, and add custom dense layers for classification.
  • Evaluate and Visualize:
    Evaluate the model using test data, calculate performance metrics, and plot a confusion matrix.
Sample Source Code
  • # Import Necessary Libraries
    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    from sklearn.preprocessing import StandardScaler
    from sklearn.model_selection import train_test_split
    import warnings
    warnings.filterwarnings("ignore")
    from tensorflow.keras.layers import Input, GRU, Dense
    from tensorflow.keras.models import Model
    from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
    import numpy as np

    df = pd.read_excel("/home/soft12/Downloads/sample_dataset/Website/Dataset/yahoo_data.xlsx")

    # Check Nan values
    print("Check Nan values\n")
    print(df.isna().sum())

    # If Nan values present
    df = df.dropna()

    # Check Null Values
    print("Check Null Values\n")
    print(df.isnull().sum())

    # Check dtypes of features
    print(df.dtypes)

    # Convert the date column to a datetime object
    df['Date'] = pd.to_datetime(df['Date'])

    # Split into day, month, and year
    df['day'] = df['Date'].dt.day
    df['month'] = df['Date'].dt.month
    df['year'] = df['Date'].dt.year

    df = df.drop('Date',axis=1)

    df['Target'] = (df['Adj Close**'].shift(-1) > df['Adj Close**']).astype(int)

    # Compute the correlation matrix
    correlation_matrix = df.corr()

    # Display the correlation matrix
    print(correlation_matrix)

    # Plot the heatmap
    plt.figure(figsize=(10, 8))
    sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt='.2f', linewidths=0.5)
    plt.title('Correlation Heatmap')
    plt.show()

    x = df.drop('Target',axis=1)
    y = df['Target']

    # Scaling the input data
    scaler = StandardScaler()
    x = scaler.fit_transform(x)

    # Split the train_test_data
    X_train, X_test, y_train, y_test = train_test_split(x,y,test_size=.2,random_state=42)

    # Reshape the Data for LSTM model
    X_train_reshaped = X_train.reshape(X_train.shape[0],1,X_train.shape[1])
    X_test_reshaped = X_test.reshape(X_test.shape[0],1,X_test.shape[1])

    def GRU_model(input_shape):

    inputs = Input(shape=(input_shape))

    # GRU layers
    gru_layer1 = GRU(64, return_sequences=True)(inputs)
    gru_layer2 = GRU(32, return_sequences=False)(gru_layer1)

    output_layer = Dense(1, activation='linear')(gru_layer2)

    # Build the model
    gru_model = Model(inputs=inputs, outputs=output_layer)

    # Compile the model with Adam optimizer and mean squared error loss function
    gru_model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mean_absolute_error'])

    return gru_model

    model = GRU_model((X_train_reshaped.shape[1],X_train_reshaped.shape[2]))

    # Summary of Model
    model.summary()

    model.fit(X_train_reshaped,y_train,batch_size=36,epochs=10,validation_data=(X_test_reshaped,y_test))

    y_pred = model.predict(X_test_reshaped)

    y_test = np.array(y_test)
    y_pred = np.array(y_pred)

    # Calculate MAE, MSE, RMSE, R2, and MAPE
    mae = mean_absolute_error(y_test, y_pred)
    mse = mean_squared_error(y_test, y_pred)
    rmse = np.sqrt(mse)
    r2 = r2_score(y_test, y_pred)

    # Print the metrics
    print("___Performance_Metrics___\n")
    print("Mean Absolute Error (MAE): ", mae)
    print("Mean Squared Error (MSE): ", mse)
    print("Root Mean Squared Error (RMSE): ", rmse)
    print("R-squared (R²): ", r2)
Screenshots
  • GRU-Based Model Screenshot