MLStrategy - alex-ruperto/Stock-Predictor GitHub Wiki

MLStrategy Overview

The MLStrategy is a trading strategy that integrates machine learning models into the backtrader framework. Instead of relying solely on traditional technical indicators to make buy or sell decisions, this strategy uses a trained machine learning model to predict the future movement of stock prices.

Key Components

Technical Indicators

The strategy still uses traditional technical indicators as features for the machine learning model. These include:

  • Simple Moving Averages (SMA) with two different periods.
  • Relative Strength Index (RSI).
  • Moving Average Convergence Divergence (MACD) with its signal line.
  • Bollinger Bands
  • Stochastic Oscillator

Machine Learning Model

The strategy uses a Long-Short Term Memory neural network model from pytorch as its predictive model. This model is trained on historical data to predict whether the stock price will go up or down the next day.

Training the Model

Before the backtest begins, the historical data is preprocessed to calculate the technical indicators and the target variable (whether the stock price goes up or down the next day). The data is then split into training and test sets, and the model is trained on the training set.

Making Predictions

During the backtest, for each new data point, the strategy extracts the current values of the technical indicators and feeds them into the trained model. The model then predicts whether the stock price will go up or down the next day.

Trading Logic

Based on the model's prediction:

  • If the model predicts the stock will go up, the strategy places a buy order.
  • If the model predicts the stock will go down and there's an open position, the strategy places a sell order.

Integration with backtrader

Data Feed

The strategy uses yfinance to fetch historical stock data, which is then preprocessed and fed into backtrader as a data feed.

Strategy Initialization

During the initialization phase, the strategy sets up the technical indicators using backtrader's built-in indicators.

Next Method

The core trading logic resides in the next method. This method is called for each new data point. Here, the strategy extracts the current values of the technical indicators, makes a prediction using the trained model, and then decides whether to buy, sell, or hold.

Visualization

After the backtest is complete, the strategy's performance, along with the technical indicators and buy/sell signals, can be visualized using plotly.


This description provides a high-level overview of the MLStrategy and its integration with backtrader. It highlights the key components and the flow of the strategy from data fetching to visualization.

board-adorable-pickle