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

示例

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[源代码]

基类:ParameterizedBase

Analyzer 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 reference

  • self.data, giving access to self.datas[0]

  • self.dataX -> self.datas[X]

  • self.dataX_Y -> self.datas[X].lines[Y]

  • self.dataX_name -> self.datas[X].name

  • self.data_name -> self.datas[0].name

  • self.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 setup

  • start / stop to signal the begin and end of operations

  • prenext / nextstart / next family of methods that follow the calls made to the same methods in the strategy

  • notify_trade / notify_order / notify_cashvalue / notify_fund which 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 next calls, at the end of operations during stop and even with a single method like notify_trade

The important thing is to override get_analysis to 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)[源代码]

Initialize Analyzer with basic functionality.

Note: __new__ removed - _children initialization moved here.

__len__()[源代码]

Support for invoking len on analyzers by actually returning the current length of the strategy the analyzer operates on

notify_cashvalue(cash, value)[源代码]

Notify the analyzer of cash and value changes.

参数:
  • cash -- Current available cash.

  • value -- Current portfolio value.

备注

Override this method to react to cash/value changes.

notify_fund(cash, value, fundvalue, shares)[源代码]

Notify the analyzer of fund-related changes.

参数:
  • cash -- Current available cash.

  • value -- Current portfolio value.

  • fundvalue -- Current fund value.

  • shares -- Number of fund shares.

备注

Override this method to react to fund changes.

notify_order(order)[源代码]

Notify the analyzer of an order status change.

参数:

order -- The order that was updated.

备注

Override this method to track order status.

notify_trade(trade)[源代码]

Notify the analyzer of a trade status change.

参数:

trade -- The trade that was updated.

备注

Override this method to track trade status.

next()[源代码]

Called on each bar after minimum period is reached.

备注

Override this method to implement per-bar analysis logic.

prenext()[源代码]

Called on each bar before minimum period is reached.

By default calls next(). Override if different behavior is needed.

nextstart()[源代码]

Called once when minimum period is first reached.

By default calls next(). Override if different behavior is needed.

start()[源代码]

Called at the start of the backtest.

备注

Override this method to initialize analyzer state.

stop()[源代码]

Called at the end of the backtest.

备注

Override this method to perform final calculations.

create_analysis()[源代码]

Create the analysis results container.

Creates the rets OrderedDict that will hold analysis results. Override this method to customize the results structure.

get_analysis()[源代码]

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 rets created by the default create_analysis method

# Return dict-like result analysis, specific format depends on implementation

print(*args, **kwargs)[源代码]

Prints the results returned by get_analysis via a standard print call

pprint(*args, **kwargs)[源代码]

Prints the results returned by get_analysis via a pretty print call

class backtrader.analyzer.TimeFrameAnalyzerBase[源代码]

基类:Analyzer

Base 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).

on_dt_over()[源代码]

Override to handle timeframe changes.

params = (('timeframe', None), ('compression', None), ('_doprenext', True))
__init__(*args, **kwargs)[源代码]

Initialize with functionality previously in MetaTimeFrameAnalyzerBase

on_dt_over()[源代码]

Called when the timeframe period changes.

This method is called when the datetime crosses into a new period of the configured timeframe (e.g., new week, new month).

备注

Override this method to implement period-based analysis logic.