backtrader.analyzers.leverage module

Leverage Analyzer Module - Gross leverage calculation.

This module provides the GrossLeverage analyzer for calculating the gross leverage (ratio of used capital to portfolio value).

Classes:

GrossLeverage: Analyzer that calculates gross leverage.

Example

>>> cerebro = bt.Cerebro()
>>> cerebro.addanalyzer(bt.analyzers.GrossLeverage, _name='lev')
>>> results = cerebro.run()
>>> print(results[0].analyzers.lev.get_analysis())
class backtrader.analyzers.leverage.GrossLeverage[source]

Bases: Analyzer

This analyzer calculates the Gross Leverage of the current strategy on a timeframe basis

Params:

  • 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

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

Initialize the GrossLeverage 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 based on parameters or broker settings.

notify_fund(cash, value, fundvalue, shares)[source]

Update cash and value from fund notification.

Parameters:
  • cash – Current cash amount.

  • value – Current portfolio value.

  • fundvalue – Current fund value.

  • shares – Number of fund shares.

next()[source]

Calculate and record the gross leverage for the current bar.

Gross leverage is calculated as (value - cash) / value. Returns 0.0 if 100% in cash, 1.0 if fully invested without shorting.