FRENESDE

Custom indicator

A custom indicator is a class that inherits from bt.Indicator. It declares its output lines, for example lines = ('ecart',): each line holds one value per bar, like a feed’s close.
Parameters are declared in params = (('period', 20),) and read with self.p.period. You can then create EcartSMA(period=50) without touching the class code.
The calculation goes in __init__, using line operations: self.lines.ecart = self.data.close - bt.ind.SMA(self.data.close, period=self.p.period). Backtrader then computes the whole line, bar after bar, with no loop to write.
Backtrader works out the minimum period by itself: until the SMA 20 has 20 bars, the indicator has no value and the strategy waits. In the strategy you write self.ecart = EcartSMA(), then in next() you read self.ecart[0] (current bar) or self.ecart[-1] (previous bar).

Examples

Key terms

Custom indicator
Class inheriting from bt.Indicator that computes its own lines
Line
Series of values, one per bar
Parameter (param)
Setting chosen at creation, read with self.p
Minimum period
Number of bars needed before the first value
Take the mission on Doji Academy

← Back to the index