backtrader.analyzer module¶
Analyzer Module - Strategy performance analysis framework.
This module provides the base classes for analyzers that calculate and report performance metrics for trading strategies. Analyzers can track trades, returns, drawdowns, Sharpe ratios, and other statistics.
- Key Classes:
Analyzer: Base class for all analyzers. TimeFrameAnalyzerBase: Base for time-frame aware analyzers.
- Analyzers receive notifications from the strategy during backtesting:
notify_trade: Called when a trade is completed
notify_order: Called when an order status changes
notify_cashvalue: Called when cash/value changes
notify_fund: Called when fund data changes
Example
Creating a custom analyzer: >>> class MyAnalyzer(Analyzer): … def __init__(self): … super().__init__() … self.trades = 0 … … def notify_trade(self, trade): … if trade.isclosed: … self.trades += 1 … … def get_analysis(self): … return {‘trade_count’: self.trades}
- class backtrader.analyzer.Analyzer[source]¶
Bases:
ParameterizedBaseAnalyzer base class. All analyzers are subclass of this one
An Analyzer instance operates in the frame of a strategy and provides an analysis for that strategy.
# Analyzer class, all analyzers are base classes of this class. An analyzer operates within the strategy framework and provides analysis of strategy execution
Automagically set member attributes:
self.strategy(giving access to the strategy and anything accessible from it)# Access to strategy instance
self.datas[x]giving access to the array of data feeds present in the the system, which could also be accessed via the strategy referenceself.data, giving access toself.datas[0]self.dataX->self.datas[X]self.dataX_Y->self.datas[X].lines[Y]self.dataX_name->self.datas[X].nameself.data_name->self.datas[0].nameself.data_Y->self.datas[0].lines[Y]
# Methods to access data
This is not a Lines object, but the methods and operation follow the same design
__init__during instantiation and initial setupstart/stopto signal the begin and end of operationsprenext/nextstart/nextfamily of methods that follow the calls made to the same methods in the strategynotify_trade/notify_order/notify_cashvalue/notify_fundwhich receive the same notifications as the equivalent methods of the strategy
The mode of operation is open and no pattern is preferred. As such the analysis can be generated with the
nextcalls, at the end of operations duringstopand even with a single method likenotify_tradeThe important thing is to override
get_analysisto return a dict-like object containing the results of the analysis (the actual format is implementation dependent)# Below are not line objects, but methods and operation design are similar to strategy. The most important thing is to override get_analysis, # to return a dict-like object to store analysis results
- csv = True¶
- __init__(*args, **kwargs)[source]¶
Initialize Analyzer with basic functionality.
Note: __new__ removed - _children initialization moved here.
- __len__()[source]¶
Support for invoking
lenon analyzers by actually returning the current length of the strategy the analyzer operates on
- notify_cashvalue(cash, value)[source]¶
Notify the analyzer of cash and value changes.
- Parameters:
cash – Current available cash.
value – Current portfolio value.
Note
Override this method to react to cash/value changes.
- notify_fund(cash, value, fundvalue, shares)[source]¶
Notify the analyzer of fund-related changes.
- Parameters:
cash – Current available cash.
value – Current portfolio value.
fundvalue – Current fund value.
shares – Number of fund shares.
Note
Override this method to react to fund changes.
- notify_order(order)[source]¶
Notify the analyzer of an order status change.
- Parameters:
order – The order that was updated.
Note
Override this method to track order status.
- notify_trade(trade)[source]¶
Notify the analyzer of a trade status change.
- Parameters:
trade – The trade that was updated.
Note
Override this method to track trade status.
- next()[source]¶
Called on each bar after minimum period is reached.
Note
Override this method to implement per-bar analysis logic.
- prenext()[source]¶
Called on each bar before minimum period is reached.
By default calls next(). Override if different behavior is needed.
- nextstart()[source]¶
Called once when minimum period is first reached.
By default calls next(). Override if different behavior is needed.
- start()[source]¶
Called at the start of the backtest.
Note
Override this method to initialize analyzer state.
- stop()[source]¶
Called at the end of the backtest.
Note
Override this method to perform final calculations.
- create_analysis()[source]¶
Create the analysis results container.
Creates the rets OrderedDict that will hold analysis results. Override this method to customize the results structure.
- get_analysis()[source]¶
Returns a dict-like object with the results of the analysis
The keys and format of analysis results in the dictionary is implementation dependent.
It is not even enforced that the result is a dict-like object, just the convention
The default implementation returns the default OrderedDict
retscreated by the defaultcreate_analysismethod# Return dict-like result analysis, specific format depends on implementation
- class backtrader.analyzer.TimeFrameAnalyzerBase[source]¶
Bases:
AnalyzerBase class for time-frame aware analyzers.
This analyzer base operates on a specific timeframe (daily, weekly, monthly, etc.) and calls on_dt_over() when the timeframe changes.
- Params:
timeframe: TimeFrame to use (None = use data’s timeframe). compression: Compression factor (None = use data’s compression). _doprenext: Whether to call prenext (default: True).
- params = (('timeframe', None), ('compression', None), ('_doprenext', True))¶