backtrader.analyzers.annualreturn module

Annual Return Analyzer Module - Annual return calculation.

This module provides the AnnualReturn analyzer for calculating year-by-year returns of a strategy.

Classes:

AnnualReturn: Analyzer that calculates annual returns.

Example

>>> cerebro = bt.Cerebro()
>>> cerebro.addanalyzer(bt.analyzers.AnnualReturn, _name='annret')
>>> results = cerebro.run()
>>> print(results[0].analyzers.annret.get_analysis())
class backtrader.analyzers.annualreturn.AnnualReturn[source]

Bases: Analyzer

This analyzer calculates the AnnualReturns by looking at the beginning and end of the year

Params:

  • (None)

Member Attributes:

  • rets: list of calculated annual returns

  • ret: dictionary (key: year) of annual returns

get_analysis:

  • Returns a dictionary of annual returns (key: year)

__init__()[source]

Initialize the AnnualReturn analyzer.

Initializes cache lists for storing dates and values during backtesting.

next()[source]

Cache current date and account value on each bar.

Stores the current datetime and portfolio value for later annual return calculation.

stop()[source]

Calculate annual returns from cached data.

Iterates through cached date-value pairs to calculate returns for each calendar year. Stores results in self.rets (list) and self.ret (dictionary keyed by year).

get_analysis()[source]

Return the annual return analysis results.

Returns:

Dictionary mapping years to their annual returns.

Return type:

OrderedDict

class backtrader.analyzers.annualreturn.MyAnnualReturn[source]

Bases: Analyzer

This analyzer calculates the AnnualReturns by looking at the beginning and end of the year

Params:

  • (None)

Member Attributes:

  • rets: list of calculated annual returns

  • ret: dictionary (key: year) of annual returns

get_analysis:

  • Returns a dictionary of annual returns (key: year)

stop()[source]

Calculate annual returns using pandas.

Uses pandas DataFrame operations to group data by year and calculate annual returns based on beginning and ending values for each year.

Note

This method requires pandas to be installed.

get_analysis()[source]

Return the annual return analysis results.

Returns:

Dictionary mapping years to their annual returns.

Return type:

OrderedDict