FRENESDE

Machine learning and Backtrader

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

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
PandasData
Backtrader feed that reads a pandas DataFrame
Take the mission on Doji Academy

← Back to the index