This project uses a Long Short-Term Memory (LSTM) neural network to forecast the future stock prices of a publicly traded company. It fetches historical stock data, preprocesses it, builds and trains an LSTM model, and then visualizes the predicted prices against the historical data.
The script is designed to predict the closing price of a stock for the next 30 days. It uses the past 60 days of closing prices as input to predict the price for the next day. This process is repeated iteratively to generate a 30-day forecast. The default ticker is set to AAPL (Apple Inc.), but it can be easily changed to any other stock ticker available on Yahoo Finance.
- Data Fetching: Fetches historical stock data from 2015 to the current date using the
yfinancelibrary. - Data Preprocessing: Scales the closing prices to a range between 0 and 1 for better model performance using
scikit-learn'sMinMaxScaler. - LSTM Model: Builds a stacked LSTM model with
Dropoutlayers to prevent overfitting, using the Keras API from TensorFlow. - Time-Series Forecasting: Creates training data in sequences of 60 days to predict the 61st day.
- Future Prediction: Iteratively predicts the stock price for a specified number of future days (default is 30).
- Visualization: Plots two graphs using
matplotlib:- The complete historical closing price of the stock.
- A combined view of the historical price and the 30-day forecasted price.
- Fetch Data: The script downloads the historical daily stock data for the specified
ticker. - Scale Data: The 'Close' prices are isolated and scaled down to a [0, 1] range. This normalization helps the LSTM network learn more effectively.
- Create Sequences: The data is transformed into sequences. For each training sample, 60 consecutive days of prices (
x_train) are used to predict the price on the 61st day (y_train). - Build and Train Model: A sequential Keras model is constructed with two LSTM layers and two Dropout layers, followed by a Dense output layer. The model is compiled with the
adamoptimizer andmean_squared_errorloss function and then trained on the sequenced data. - Predict the Future:
- The last 60 days from the historical data are used as the initial input for the forecast.
- The model predicts the price for the next day.
- This predicted price is then added to the end of the input sequence, and the oldest price is removed.
- This new sequence is used to predict the subsequent day's price. The process repeats for 30 days.
- Inverse Transform & Visualize: The predicted prices, which are in the scaled format, are transformed back to their original dollar values. Finally, the forecast is plotted on a graph alongside the historical data for comparison.
- Python 3
- NumPy: For numerical operations and array manipulation.
- Pandas: For data handling and manipulation.
- yfinance: To fetch financial market data from Yahoo Finance.
- Matplotlib: For data visualization and plotting.
- Scikit-learn: For data preprocessing (
MinMaxScaler). - TensorFlow / Keras: For building and training the LSTM neural network.
Follow these instructions to get a copy of the project up and running on your local machine.
You need to have Python 3 and pip installed on your system.
-
Clone the repository:
git clone [https://github.com/PriyanshAg-1/Stock-Analysis.git](https://github.com/PriyanshAg-1/Stock-Analysis.git) cd Stock-Analysis -
Create a virtual environment (optional but recommended):
python -m venv venv source venv/bin/activate # On Windows, use `venv\Scripts\activate`
-
Install the required libraries: A
requirements.txtfile is recommended for listing dependencies. You can create one with the following content:numpy pandas yfinance matplotlib scikit-learn tensorflowThen, install them all at once:
pip install -r requirements.txt
-
Run the script:
python main.py
-
Change the Stock Ticker: To analyze a different stock, simply change the
tickervariable at the top of the script:ticker = 'GOOGL' # For Alphabet Inc. (Google) # ticker = 'MSFT' # For Microsoft Corp.
The script will then print the latest real-time price, the forecasted prices for the next 30 days to the console, and display the two plots.
This project is for educational and informational purposes only. The predictions generated by the LSTM model are not financial advice. Stock market prices are highly volatile and influenced by numerous factors, and past performance is not indicative of future results. Do not use this project as the basis for any real investment decisions.