backtrader.analyzers.timereturn module¶
TimeReturn Analyzer Module - Time-based returns calculation.
This module provides the TimeReturn analyzer for calculating returns over specified time periods.
- Classes:
TimeReturn: Analyzer that calculates returns by timeframe.
Example
>>> cerebro = bt.Cerebro()
>>> cerebro.addanalyzer(bt.analyzers.TimeReturn, timeframe=bt.TimeFrame.Years)
- class backtrader.analyzers.timereturn.TimeReturn[source]¶
Bases:
TimeFrameAnalyzerBaseThis analyzer calculates the Returns by looking at the beginning and end of the timeframe
Params:
timeframe(default:None) IfNonethetimeframeof the first data in the system will be usedPass
TimeFrame.NoTimeFrameto consider the entire dataset with no time constraintscompression(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
data(default:None)Reference asset to track instead of the portfolio value.
- Note:: this data must have been added to a
cerebroinstance with addata,resampledataorreplaydata
- Note:: this data must have been added to a
firstopen(default:True)When tracking the returns of data the following is done when crossing a timeframe boundary, for example,
Years:Last
closethe previous year is used as the reference price to see the return in the current year
The problem is the first calculation, because the data has** no previous** closing price.As such, and when this parameter is True, the opening price will be used for the first calculation.
This requires the data feed to have an
openprice (forclosethe standard [0] notations will be used without a reference to a field price)Else the initial close will be used. # When calculating returns for the first period, whether to use the first opening price. If parameter is False, the first closing price will be used
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_fundmodein the broker documentationSet it to
TrueorFalsefor a specific behavior
- - Get_analysis
Returns a dictionary with returns as values and the datetime points for each return as keys
- params = (('data', None), ('firstopen', True), ('fund', None))¶
- __init__(*args, **kwargs)[source]¶
Initialize the TimeReturn analyzer.
- Parameters:
*args – Positional arguments.
**kwargs – Keyword arguments for analyzer parameters.
- start()[source]¶
Initialize the analyzer at the start of the backtest.
Sets the fund mode and initializes the starting value for return calculations.
- notify_fund(cash, value, fundvalue, shares)[source]¶
Update current value based on fund notification.
- Parameters:
cash – Current cash amount.
value – Current portfolio value.
fundvalue – Current fund value.
shares – Number of fund shares.