A machine learning model can produce a prediction for each bar, for example the probability that the next close will be higher. You compute these predictions in advance, with pandas and scikit-learn, then pass them to Backtrader.
To read that column, you extend the pandas feed: class PandasPred(bt.feeds.PandasData): with lines = ('prediction',) and params = (('prediction', -1),). The -1 asks it to find the column by name; in next() you read self.data.prediction[0]. The model does not trade: the strategy decides.
Predictions must be out of sample: produced by a model that has never seen those bars. Split along time (train on the past, predict what follows), ideally walk-forward; scikit-learn’s TimeSeriesSplit respects that order, unlike a random shuffle.
Watch out for information leaks: a feature normalised with the mean of the whole series, or a prediction for bar t that uses the close of t+1, makes the backtest superb and false. A prediction made at the close of t should only drive an order executed at t+1.
Examples
SIGMA-X (fictional market) : The straight line is the direction the model tries to anticipate. The model gives a probability per bar, for example 0.62; the strategy only buys if it exceeds a threshold set in advance, and keeps its usual risk rules.
Winter 2012–2013: Google Flu Trends gets it wrong : Google Flu Trends estimated flu activity in the US from online searches. In the winter of 2012–2013, it overestimated the peak by about two times compared with official figures, according to an article in the journal Nature. A model that shines on the past can fail when conditions change: markets are no exception.
Key terms
Out of sample
Data the model did not see during training
Walk-forward
Train on a past window, test on the next one, then move forward
Information leak
Future data slipped by mistake into training or features