Hello Everyone.
Is there an example on how to set the Leverage within the Framework?
I've tried to set it within the AlphaModel, but nothing changes if I set different leveages. Maybe I have to modify the Portfolio contstruction or the Execution Model to make the changes in Leverage effective? Or Is something that can be passed through the insights?
Best Regards!
Alessio Magri
Hello Everyone, I found a viable answer in modifying the Portfolio construction model.Â
from decimal import Decimal class EqualLeveragePortfolioConstructionModel(EqualWeightingPortfolioConstructionModel): def __init__(self, rebalance = Resolution.Daily, leverage = 1): super().__init__(rebalance) self.leverage = abs(leverage) self.symbols = [] self.result = dict() def DetermineTargetPercent(self, activeInsights): #2. Search for the active insights in this sector. Save the variable self.insights self.insights = [insight for insight in activeInsights if insight.Symbol in self.symbols] #3. For each insight in self.insights, assign each insight an allocation. # The allocation is calculated by multiplying the insight direction by the self.percent for insight in self.insights: self.result[insight] = insight.Direction * self.percent return self.result def OnSecuritiesChanged(self, algorithm, changes): for security in changes.AddedSecurities: self.symbols.append(security.Symbol) for security in changes.RemovedSecurities: symbol = security.Symbol if symbol in self.symbols: self.symbols.remove(symbol) if algorithm.Portfolio.CashBook.TotalValueInAccountCurrency <= 25000 and self.leverage > 2: self.leverage = 2 elif algorithm.Portfolio.CashBook.TotalValueInAccountCurrency > 25000 and self.leverage > 4: self.leverage = 4 if self.leverage > 2: #PDT Margin Model for Short Trading... if any algorithm.Securities[symbol].MarginModel = PatternDayTradingMarginModel() #1. Set the self.percent (BuyingPower) before by dividing one by the length of self.symbols self.percent = Decimal(format(self.leverage / len(self.symbols), ".2f")) super().OnSecuritiesChanged(algorithm, changes)
Do you think it's a good way to manage leverage or maybe there are better ways? I noticed that the maximum leverage is 2 (more than 2 it can't fill the orders because they are over the margin allowed). Is it something that is fixed with the brokerage model (like interactive brokers) or there are ways to get a leverage higher than 2?
Best regards
Alessio Magri
Found a good answer by Jing Wu here:Â
https://www.quantconnect.com/forum/discussion/500/update-margin-calls-and-portfolio-modelingÂ
Derek Melchin
Hi Alessio,
The cleanest way to implement leverage in the Framework is to inherit from InsightWeightingPortfolioConstructionModel and override CreateTargets
class MyPCM(InsightWeightingPortfolioConstructionModel): def CreateTargets(self, algorithm, insights): targets = super().CreateTargets(algorithm, insights) return [PortfolioTarget(x.Symbol, x.Quantity*algorithm.Securities[x.Symbol].Leverage) for x in targets]
Now we control the amount of leverage used for each symbol by setting a security initializer in Initialize with
self.SetSecurityInitializer(self.CustomSecurityInitializer)
and we define the CustomSecurityInitializer as
def CustomSecurityInitializer(self, security): security.SetLeverage(3.5)
See the attached backtest for reference. Learn more about security initializers in the documentation.
Best,
Derek Melchin
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.
Alessio Magri
Thank You Derek!
This is really a cleaner version!
Alessio Magri
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.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!