backtrader.analyzers.returns module

Returns Analyzer Module - Return statistics calculation.

This module provides the Returns analyzer for calculating total, average, compound, and annualized returns using a logarithmic approach.

Classes:

Returns: Analyzer that calculates return statistics.

Example

>>> cerebro = bt.Cerebro()
>>> cerebro.addanalyzer(bt.analyzers.Returns, _name='ret')
>>> results = cerebro.run()
>>> print(results[0].analyzers.ret.get_analysis())
class backtrader.analyzers.returns.Returns[source]

Bases: TimeFrameAnalyzerBase

Total, Average, Compound and Annualized Returns calculated using a logarithmic approach

See:

Params:

  • timeframe (default: None)

    If None the timeframe of the first data in the system will be used

    Pass TimeFrame.NoTimeFrame to consider the entire dataset with no time constraints

  • compression (default: None)

    Only used for sub-day timeframes to, for example, work on an hourly timeframe by specifying “TimeFrame.Minutes” and 60 as compression

    If None, then the compression of the first data in the system will be used

  • tann (default: None)

    Number of periods to use for the annualization (normalization)

    namely:

    • days: 252

    • weeks: 52

    • months: 12

    • years: 1

  • fund (default: None)

    If None, the actual mode of the broker (fundmode - True/False) will be autodetected to decide if the returns are based on the total net asset value or on the fund value. See set_fundmode in the broker documentation

    Set it to True or False for a specific behavior

- get_analysis

Returns a dictionary with returns as values and the datetime points for each return as keys

The returned dict the following keys:

  • rtot: Total compound return

  • ravg: Average return for the entire period (timeframe specific)

  • rnorm: Annualized/Normalized return

  • rnorm100: Annualized/Normalized return expressed in 100%

params = (('tann', None), ('fund', None))
__init__(*args, **kwargs)[source]

Initialize the Returns analyzer.

Parameters:
  • *args – Positional arguments.

  • **kwargs – Keyword arguments for analyzer parameters.

start()[source]

Initialize the analyzer at the start of the backtest.

Records the initial portfolio value and sets the fund mode.

stop()[source]

Calculate and store return statistics at the end of the backtest.

Calculates:
  • rtot: Total compound return

  • ravg: Average return for the period

  • rnorm: Annualized return

  • rnorm100: Annualized return in percentage form

on_dt_over()[source]

Called when a datetime period is over.

Increments the subperiod counter.