Hi guys,
building on the helpful comment on leverage from Rahul Chowdhury, please find here an option for (a) using leverage on security level together with (b) a margin type brokerage model.
According to the documentation on key concepts of universe selection, the SetSecurityInitializer method overwrites the default security initializer including the selected brokerage model, and we can use our brokerage model if we extend upon the default security initializer instead of overwriting it.
Any comments welcome ;)
Best
Frank
# 1 - In Initialize of the QCAlgorithm:
# Specify a margin type brokerage model and change the free cash % in our portfolio
self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin)
self.Settings.FreePortfolioValuePercentage = 0.05
# Set leverage on a security level
# Instead of configuring global universe settings, you can individually
# configure the settings of each security in the universe with a security
# initializer.
# If you call the SetSecurityInitializer method, it overwrites the
# default security initializer. To extend upon the default security
# initializer instead of overwriting it, create a custom
# BrokerageModelSecurityInitializer.
# In some cases, you may want to trade a security in the same time loop
# that you create the security subscription. To avoid errors, use a
# security initializer to set the market price of each security to the
# last known price.
# https://www.quantconnect.com/docs/v2/writing-algorithms/algorithm-framework/universe-selection/key-concepts?ref=v1
self.SetSecurityInitializer(CustomSecurityInitializer(
self.BrokerageModel,
FuncSecuritySeeder(self.GetLastKnownPrices),
self.max_security_leverage,
))
# 2 - In main.py as a separate class:
class CustomSecurityInitializer(BrokerageModelSecurityInitializer):
'''Extends the default security initializer.
Args:
brokerage_model: The brokerage model we have defined
security_seeder: A security initializer
max_security_leverage: The maximum leverage beeing set on security level
'''
def __init__(self,
brokerage_model,
security_seeder,
max_security_leverage=1.0):
# Our child class inherits the Parent class and initializes the Parent class object
super().__init__(brokerage_model, security_seeder)
self.max_security_leverage = max_security_leverage
def Initialize(self, security):
# First, the superclass definition is called which sets the reality
# models of each security using the default reality models of the
# brokerage model.
super().Initialize(security)
# Next, some of the reality models can be overwritten.
security.SetLeverage(self.max_security_leverage)