How to track and control your algorithm leverage

In the Quantopian Open, leverage is constrained to 3x for eligible entries. You can track and control your algorithm leverage using the context.account.leverage variable.

But quantconnect how to do it ?

Update Backtest

On the quantopian transfer post, Alexandre Catarino shared a way:

account_leverage = self.Portfolio.TotalAbsoluteHoldingsCost / self.Portfolio.TotalPortfolioValue

I chart it it once a day with my minute algos(you don't want to spam the charts they have limits, see docs):

# in Initialize
self.splotName = 'Strategy Info'
sPlot = Chart(self.splotName)
sPlot.AddSeries(Series('RAM',  SeriesType.Line, 0))

# periodicaly in algo
self.Plot(self.splotName,'RAM', OS.ApplicationMemoryUsed/1024.)

Settiing leverage depends, you may want to review the docs on a couple topics there. You can set leverage for self.UniverseSettings.Leverage if using AddUniverse, and or set the pattern day trade model for 2 overnight 4 iintrday using security.MarginModel   =  PatternDayTradingMarginModel(), or manually set each asset;s leverage when using AddEquity.

Cash and Broker Models

AddEquity and use of manual leverage setting


I noticed in my charts that the above leverage calc will not account for current value of positions, but rather just their average cost as the names suggest. Meaning that your unrealized profits will be left out of your leverage calc, which may not be desired.

self.account_leverage = self.Portfolio.TotalHoldingsValue / self.Portfolio.TotalPortfolioValue

Update Backtest


The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


This discussion is closed