← Back to Main Portfolio

Stock Price Prediction with LSTM

This project demonstrates the use of a Long Short-Term Memory (LSTM) neural network, a type of Recurrent Neural Network (RNN), to forecast future stock prices based on historical data. The model is built with TensorFlow and Keras and trained on historical stock data fetched from Yahoo Finance.

Project Overview

The script follows a standard machine learning workflow for time series forecasting:

  1. Data Acquisition: Fetches historical stock data (e.g., for Apple Inc. - AAPL) from Yahoo Finance using the yfinance library.
  2. Data Preprocessing: Scales the 'Close' price data using MinMaxScaler from Scikit-learn. This normalization is crucial for neural network performance.
  3. Sequence Creation: Transforms the time series data into sequences of a fixed length (e.g., 60 days) to be used as input features for the LSTM model. The next day's price is the target label.
  4. Model Architecture: Defines and builds a sequential LSTM model using Keras, consisting of multiple LSTM layers with Dropout to prevent overfitting, and a final Dense layer for the output prediction.
  5. Model Training: Compiles the model with an Adam optimizer and Mean Squared Error loss function, then trains it on the prepared training dataset.
  6. Prediction & Evaluation: Makes predictions on the test dataset and calculates the Root Mean Squared Error (RMSE) to evaluate the model's performance.
  7. Visualization: Plots the original stock prices against the model's predictions to visually assess the forecast accuracy.

Technologies Used

How to Run

1. Navigate to the project directory:

cd stock-price-prediction-lstm

2. Install dependencies from the requirements file:

pip install -r requirements.txt

3. Run the Python script (ensure your script name matches):

python stock_predictor.py

The script will fetch the latest data, train the model, and output its evaluation metric.

Sample Output

The script will print the model's performance to the console:


Fetching data for AAPL from 2012-01-01 to 2024-01-01...
Data fetched successfully.
Starting model training...
Epoch 1/25
...
Epoch 25/25
Model training complete.
Calculating model performance...

Root Mean Squared Error (RMSE): 4.52
        

Additionally, the script will generate and save a plot (e.g., prediction_vs_actual.png) that visually compares the actual stock prices with the prices predicted by the LSTM model.