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
ALPHA-X (fictional market) : The green and red dots mark entries and exits. A custom analyzer can count these trades, measure their average length or the time spent in a position: figures no chart gives at a glance.
1966: William F. Sharpe and his ratio : In 1966, economist William F. Sharpe proposed a ratio comparing the return earned above a risk-free investment with the volatility endured. He received the Nobel Prize in economics in 1990, together with Harry Markowitz and Merton Miller. Backtrader provides a ready-made version: bt.analyzers.SharpeRatio.
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