FRENESDE

Custom analyzers

A custom analyzer inherits from bt.Analyzer. It computes a statistic over the whole backtest, whereas an observer records one value per bar for the chart.
Three methods set its rhythm: start() initialises the counters once at the start, next() updates them at each bar, stop() does the final calculation. The result is returned by get_analysis().
The analyzer sees the strategy through self.strategy: if self.strategy.position: lets you count the bars spent in a position. It also receives each trade through notify_trade(trade), for example to add up trade.pnlcomm (profit after commissions) when trade.isclosed is true.
You add it with cerebro.addanalyzer(PctTemps, _name='temps'), then read strat.analyzers.temps.get_analysis() after strat = cerebro.run()[0]. Backtrader already ships built-in analyzers: SharpeRatio, DrawDown, TradeAnalyzer, SQN…

Examples

Key terms

Analyzer
Component that computes a statistic over the whole backtest
get_analysis
Method that returns the analyzer’s result
_name
Name given to the analyzer to find it after the run
pnlcomm
Profit or loss of a trade after commissions
Take the mission on Doji Academy

← Back to the index