Predicting Stock Prices using GMDH Algorithm: A Practical Approach with Working Code

Predicting Stock Prices using GMDH Algorithm: A Practical Approach with Working Code

Want to learn how to predict stock prices (Day High and Day Low) with just a few lines of code?

Let me walk you through the process!

Firstly the codes:

import pandas as p
import numpy as np
import yfinance as yf
from sklearn.model_selection import train_test_split
from gmdhpy.gmdh import Regressor

# Define the list of tickers (You can put all the tickers (stocks) here all at once)
tickers = ['^NSEI', '^NSEBANK', 'Ticker 3', 'Ticker 4', 'Ticker 5']

# Create an empty dictionary to store the predicted prices for each stock
all_predicted_prices = {}

# Loop through each ticker
for ticker in tickers:
    # Downloading stock data from Yahoo Finance
    try:
        df = yf.download(ticker, start='2010-01-01', end=pd.Timestamp.today() - pd.Timedelta(days=1))
    except:
        print(f"Could not download data for {ticker}. Moving on to next ticker.")
        continue

    # Removing unnecessary columns
    df.drop(['Adj Close', 'Volume'], axis=1, inplace=True)

    # Splitting the data into                 
    try:
        X_train, X_test, y_train_open, y_test_open = train_test_split(df.drop(['Open'], axis=1), df['Open'], test_size=0.2, shuffle=False)
        _, _, y_train_close, y_test_close = train_test_split(df.drop(['Close'], axis=1), df['Close'], test_size=0.2, shuffle=False)
        _, _, y_train_high, y_test_high = train_test_split(df.drop(['High'], axis=1), df['High'], test_size=0.2, shuffle=False)
        _, _, y_train_low, y_test_low = train_test_split(df.drop(['Low'], axis=1), df['Low'], test_size=0.2, shuffle=False)
    except ValueError:
        print(f"No data available for {ticker}. Moving on to next ticker.")
        continue

    # Training the model using the GMDH method for Open price prediction
    model_open = Regressor()
    model_open.fit(X_train.values, y_train_open.values)

    # Training the model using the GMDH method for Close price prediction
    model_close = Regressor()
    model_close.fit(X_train.values, y_train_close.values)

    # Training the model using the GMDH method for High price prediction
    model_high = Regressor()
    model_high.fit(X_train.values, y_train_high.values)

    # Training the model using the GMDH method for Low price prediction
    model_low = Regressor()
    model_low.fit(X_train.values, y_train_low.values)

    # Predicting the prices using the trained models
    predicted_prices = {
        'Open': model_open.predict(X_test[-1:].values)[0],
        'Close': model_close.predict(X_test[-1:].values)[0],
        'High': model_high.predict(X_test[-1:].values)[0],
        'Low': model_low.predict(X_test[-1:].values)[0]
    }

    # Add the predicted prices for this stock to the all_predicted_prices dictionary
    all_predicted_prices[ticker] = predicted_prices

# Displaying the predicted prices for all stocks
prediction_date = pd.Timestamp.today().date()
print(f"The predicted prices for all stocks on {prediction_date} are:")
for ticker, predicted_prices in all_predicted_prices.items():
    print(f"\n{ticker}:")
    print(f"Prediction date: {prediction_date}")
    print(f"Low: {predicted_prices['Low']:.2f}")
    print(f"High: {predicted_prices['High']:.2f}"        

Step 1: Let's start by importing the necessary libraries. We'll be using Pandas, Numpy, Yfinance, Scikit-learn, and GMDHpy. With these libraries, we'll be able to download and clean data, train models, and make predictions.

Note: With this code, you won't have to worry about downloading and cleaning data. It's all done for you!

Step 2: Next, we need to define the list of stocks that we want to predict. Once we have our list, we create an empty dictionary to store the predicted prices for each stock.

Note: You can add as many stocks as you want to this list! It can be 5, 10, or even 100. The code will do the prediction for all of them at once.

Step 3: Now, let's loop through each stock in our list and download the stock data from Yahoo Finance. We'll remove unnecessary columns, split the data into training and testing sets, and train the GMDH models using the training data.

Once our models are trained, we'll use them to predict the prices and add the predicted prices for each stock to our dictionary.

Step 4: Finally, we'll display the predicted prices for all stocks in a formatted manner. We'll show the prediction date, low price, and high price for each stock.

With these predicted prices, you can make informed decisions about buying or selling stocks. You can use the high and low prices to determine whether a stock is in an uptrend or downtrend. If it breaks the level of high or low and sustains there for 3-5 minutes, then it may be going to break even further.

Now the output:

No alt text provided for this image

How will I use it: If the price breaks the Day low predicted level, then its a weak trend and will slide further down. Similarly if the price breaks the day high level, then its a strong uptrend and possibility of breaking more upside is there.

Facing Issue with GMDH installation in python. It could be daunting sometimes and took a while for me to figure out. Hence created a simple article to help you in each steps:

https://www.garudax.id/pulse/diy-install-gmdh-libraries-python-step-by-step-guide-akhil-sharma/

Disclaimer: Remember, these predictions are based on historical data and do not guarantee future performance.

#stockmarket #datascience #machinelearning #GMDHalgorithm #prediction #stockprice #financialanalysis #investing #dataanalysis #Pythonprogramming #coding #opensource #yfinance #pandas #numpy #sklearn

To view or add a comment, sign in

Explore content categories