backtrader.analyzers.tradeanalyzer module

Trade Analyzer Module - Detailed trade statistics.

This module provides the TradeAnalyzer for calculating comprehensive trade statistics including win/loss ratios, streaks, and PnL metrics.

Classes:

TradeAnalyzer: Analyzer that calculates detailed trade statistics.

示例

>>> cerebro = bt.Cerebro()
>>> cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name='ta')
>>> results = cerebro.run()
>>> print(results[0].analyzers.ta.get_analysis())
class backtrader.analyzers.tradeanalyzer.TradeAnalyzer[源代码]

基类:Analyzer

Provides statistics on closed trades (keeps also the count of open ones)

  • Total Open/Closed Trades

  • Streak Won/Lost Current/Longest

  • ProfitAndLoss Total/Average

  • Won/Lost Count/ Total PNL/ Average PNL / Max PNL

  • Long/Short Count/ Total PNL / Average PNL / Max PNL

    • Won/Lost Count/ Total PNL/ Average PNL / Max PNL

  • Length (bars in the market)

    • Total/Average/Max/Min

    • Won/Lost Total/Average/Max/Min

    • Long/Short Total/Average/Max/Min

      • Won/Lost Total/Average/Max/Min

备注

The analyzer uses an autodict for the fields, which means that if no trades are executed, no statistics will be generated.

In that case, there will be a single field/subfield in the dictionary returned by get_analysis, namely:

  • Dictname['total']['total'] which will have a value of 0 (the field is also reachable with dot notation dictname.total.total

rets = None
create_analysis()[源代码]

Create the analysis result data structure.

Initializes the AutoOrderedDict with a total counter set to zero.

stop()[源代码]

Finalize the analysis when backtest ends.

Closes the results dictionary to prevent further modifications.

notify_trade(trade)[源代码]

Process trade notifications to build detailed statistics.

Updates all trade statistics including win/loss counts, streaks, PnL metrics, and trade duration for both long and short positions.

参数:

trade -- The trade object with status and PnL information.