FRENESDE

Writing a Strategy

A strategy is a Python class that inherits from bt.Strategy. You write the class and pass it to cerebro.addstrategy(): Cerebro creates the object.
In __init__ you declare the indicators once, for example self.sma = bt.ind.SMA(self.data.close, period=20). Backtrader computes them over the whole series.
In next() you write each bar’s decision: if not self.position and self.data.close[0] > self.sma[0]: self.buy().
Settings go into params: params = (('period', 20),), then self.p.period. That way you can test 20, 50 or 100 without rewriting the class.

Examples

Key terms

bt.Strategy
The base class every strategy inherits from
__init__
Method run once, where indicators are declared
next()
Method called at each bar to decide
params
The strategy’s adjustable settings
Take the mission on Doji Academy

← Back to the index