diff --git a/03 Writing Algorithms/24 Reality Modeling/02 Trade Fills/01 Key Concepts/02 Set Models.php b/03 Writing Algorithms/24 Reality Modeling/02 Trade Fills/01 Key Concepts/02 Set Models.php index eaa2f2b57a..7a31eb57bb 100644 --- a/03 Writing Algorithms/24 Reality Modeling/02 Trade Fills/01 Key Concepts/02 Set Models.php +++ b/03 Writing Algorithms/24 Reality Modeling/02 Trade Fills/01 Key Concepts/02 Set Models.php @@ -1,11 +1,17 @@
The brokerage model of your algorithm automatically sets the fill model for each security, but you can override it. To manually set the fill model of a security, call the SetFillModel
set_fill_model
method on the Security object.
// In Initialize -var security = AddEquity("SPY"); -security.SetFillModel(new ImmediateFillModel());-
# In Initialize -security = self.add_equity("SPY") -security.set_fill_model(ImmediateFillModel())+
public override void Initialize() +{ + var security = AddEquity("SPY"); + // Set the fill model for the requested security to backtest with the most realistic scenario + // ImmediateFillModel provide no delay from network issue or brokerage rules + security.SetFillModel(new ImmediateFillModel()); +}+
def initialize(self) -> None: + security = self.add_equity("SPY") + # Set the fill model for the requested security to backtest with the most realistic scenario + # ImmediateFillModel provide no delay from network issue or brokerage rules + security.set_fill_model(ImmediateFillModel())
You can also set the fill model in a security initializer. If your algorithm has a dynamic universe, use the security initializer technique. In order to initialize single security subscriptions with the security initializer, call SetSecurityInitializer
set_security_initializer
before you create the subscriptions.
diff --git a/03 Writing Algorithms/24 Reality Modeling/02 Trade Fills/01 Key Concepts/04 Model Structure.html b/03 Writing Algorithms/24 Reality Modeling/02 Trade Fills/01 Key Concepts/04 Model Structure.html index d5036cc03b..1e46880933 100644 --- a/03 Writing Algorithms/24 Reality Modeling/02 Trade Fills/01 Key Concepts/04 Model Structure.html +++ b/03 Writing Algorithms/24 Reality Modeling/02 Trade Fills/01 Key Concepts/04 Model Structure.html @@ -1,9 +1,16 @@
Fill Models should extend the FillModel
class. To implement your own fill model, override the methods in the FillModel
class you wish to change.
The class has a dedicated method for each order type. Most of the methods receive a Security
and Order
object and return an OrderEvent
object that contains information about the order status, fill quantity, and errors.
// In the Initialize method, set the custom fill model -security.SetFillModel(new MyFillModel()); - +public class CustomFillModelExampleAlgorithm : QCAlgorithm +{ + public override void Initialize() + { + // In the Initialize method, set the custom fill model for an added security to use the custom model + var security = AddEquity("SPY"); + security.SetFillModel(new MyFillModel()); + } +} + // Define the custom fill model outside of the algorithm public class MyFillModel : FillModel { @@ -52,8 +59,11 @@ } }-# In the Initialize method, set the custom fill model -security.set_fill_model(MyFillModel()) +class CustomFillModelExampleAlgorithm(QCAlgorithm): + def initialize(self) -> None: + # In the Initialize method, set the custom fill model for an added security to use the custom model + security = self.add_equity("SPY") + security.set_fill_model(MyFillModel()) # Define the custom fill model outside of the algorithm class MyFillModel(FillModel): diff --git a/03 Writing Algorithms/24 Reality Modeling/03 Slippage/01 Key Concepts/03 Set Models.php b/03 Writing Algorithms/24 Reality Modeling/03 Slippage/01 Key Concepts/03 Set Models.php index 2d3de0a016..bf3d4a489a 100644 --- a/03 Writing Algorithms/24 Reality Modeling/03 Slippage/01 Key Concepts/03 Set Models.php +++ b/03 Writing Algorithms/24 Reality Modeling/03 Slippage/01 Key Concepts/03 Set Models.php @@ -1,12 +1,20 @@The brokerage model of your algorithm automatically sets the slippage model for each security, but you can override it. To manually set the slippage model of a security, call the
SetSlippageModel
set_slippage_model
method on theSecurity
object.-// In Initialize -var security = AddEquity("SPY"); -security.SetSlippageModel(new VolumeShareSlippageModel());-# In Initialize -security = self.add_equity("SPY") -security.set_slippage_model(VolumeShareSlippageModel())+public override void Initialize() +{ + var security = AddEquity("SPY"); + // Set the slippage model for the requested security to backtest with the most realistic scenario + // VolumeShareSlippageModel has slippage size affected by the volume of the order compared to the actual filled volume of the bar + // It is only valid for the security with a volume property, while being more accurate with denser resolution + security.SetSlippageModel(new VolumeShareSlippageModel()); +}+def initialize(self) -> None: + security = self.add_equity("SPY") + # Set the slippage model for the requested security to backtest with the most realistic scenario + # VolumeShareSlippageModel has slippage size affected by the volume of the order compared to the actual filled volume of the bar + # It is only valid for the security with a volume property, while being more accurate with denser resolution + security.set_slippage_model(VolumeShareSlippageModel())You can also set the slippage model in a security initializer. If your algorithm has a dynamic universe, use the security initializer technique. In order to initialize single security subscriptions with the security initializer, call
diff --git a/03 Writing Algorithms/24 Reality Modeling/03 Slippage/01 Key Concepts/05 Model Structure.html b/03 Writing Algorithms/24 Reality Modeling/03 Slippage/01 Key Concepts/05 Model Structure.html index 4166befd72..963350b9d8 100644 --- a/03 Writing Algorithms/24 Reality Modeling/03 Slippage/01 Key Concepts/05 Model Structure.html +++ b/03 Writing Algorithms/24 Reality Modeling/03 Slippage/01 Key Concepts/05 Model Structure.html @@ -1,8 +1,15 @@SetSecurityInitializer
set_security_initializer
before you create the subscriptions.Slippage models should implement the
ISlippageModel
interface. Extensions of theISlippageModel
interface must implement theGetSlippageApproximation
get_slippage_approximation
method, which calculates the slippage quantity.-diff --git a/03 Writing Algorithms/24 Reality Modeling/04 Transaction Fees/01 Key Concepts/04 Model Structure.html b/03 Writing Algorithms/24 Reality Modeling/04 Transaction Fees/01 Key Concepts/04 Model Structure.html index 1dc72abec5..02e0f4f208 100644 --- a/03 Writing Algorithms/24 Reality Modeling/04 Transaction Fees/01 Key Concepts/04 Model Structure.html +++ b/03 Writing Algorithms/24 Reality Modeling/04 Transaction Fees/01 Key Concepts/04 Model Structure.html @@ -1,8 +1,15 @@// In the Initialize method, set the slippage model -security.SetSlippageModel(new MySlippageModel()); +public class CustomSlippageModelExampleAlgorithm : QCAlgorithm +{ + public override void Initialize() + { + // In the Initialize method, set the custom slippage model for an added security to use the custom model + var security = AddEquity("SPY"); + security.SetSlippageModel(new MySlippageModel()); + } +} // Define the custom slippage model public class MySlippageModel : ISlippageModel @@ -13,8 +20,11 @@ } }-# In the Initialize method, set the slippage model -security.set_slippage_model(MySlippageModel()) +class CustomSlippageModelExampleAlgorithm(QCAlgorithm): + def initialize(self) -> None: + # In the Initialize method, set the custom slippage model for an added security to use the custom model + security = self.add_equity("SPY") + security.set_slippage_model(MySlippageModel()) # Define the custom slippage model class MySlippageModel: diff --git a/03 Writing Algorithms/24 Reality Modeling/04 Transaction Fees/01 Key Concepts/02 Set Models.php b/03 Writing Algorithms/24 Reality Modeling/04 Transaction Fees/01 Key Concepts/02 Set Models.php index 6802cc2510..474a45e8a0 100644 --- a/03 Writing Algorithms/24 Reality Modeling/04 Transaction Fees/01 Key Concepts/02 Set Models.php +++ b/03 Writing Algorithms/24 Reality Modeling/04 Transaction Fees/01 Key Concepts/02 Set Models.php @@ -5,10 +5,14 @@public override Initialize() { var security = AddEquity("SPY"); + // Set the fee model for the requested security to backtest with the most realistic scenario + // Constant fee model of 0 dollar is accurate for the commission-free brokerage security.SetFeeModel(new ConstantFeeModel(0)); }def initialize(self): security = self.add_equity("SPY") + # Set the fee model for the requested security to backtest with the most realistic scenario + # Constant fee model of 0 dollar is accurate for the commission-free brokerage security.set_fee_model(ConstantFeeModel(0))Fee models should extend the
FeeModel
class. Extensions of theFeeModel
class must implement theGetOrderFee
get_order_fee
method, which receivesOrderFeeParameters
and returns anOrderFee
that represents a cash amount in a currency.-// In the Initialize method, set the fee model -security.SetFeeModel(new MyFeeModel()); +public class CustomFeeModelExampleAlgorithm : QCAlgorithm +{ + public override void Initialize() + { + // In the Initialize method, set the custom fee model for an added security to use the custom model + var security = AddEquity("SPY"); + security.SetFeeModel(new MyFeeModel()); + } +} // Define the custom fee model public class MyFeeModel : FeeModel @@ -12,8 +19,11 @@ return new OrderFee(new CashAmount(0.5m, "USD")); } }-# In the Initialize method, set the fee model -security.set_fee_model(MyFeeModel()) +class CustomFeeModelExampleAlgorithm(QCAlgorithm): + def initialize(self) -> None: + # In the Initialize method, set the custom fee model for an added security to use the custom model + security = self.add_equity("SPY") + security.set_fee_model(MyFeeModel()) # Define the custom fee model class MyFeeModel(FeeModel): diff --git a/03 Writing Algorithms/24 Reality Modeling/05 Brokerages/01 Key Concepts/02 Set Models.html b/03 Writing Algorithms/24 Reality Modeling/05 Brokerages/01 Key Concepts/02 Set Models.html index a968b3d33d..fa2fc16d99 100644 --- a/03 Writing Algorithms/24 Reality Modeling/05 Brokerages/01 Key Concepts/02 Set Models.html +++ b/03 Writing Algorithms/24 Reality Modeling/05 Brokerages/01 Key Concepts/02 Set Models.html @@ -1,11 +1,16 @@To set a brokerage model, in the
Initialize
initialize
method, call theSetBrokerageModel
set_brokerage_model
method with aBrokerageName
and anAccountType
. If you set a brokerage model, it overrides any security level models you manually set in your algorithm.-SetBrokerageModel(BrokerageName.OandaBrokerage); // Defaults to margin account -SetBrokerageModel(BrokerageName.Bitfinex, AccountType.Margin); // Overrides the default account type --self.set_brokerage_model(BrokerageName.OANDA_BROKERAGE) # Defaults to margin account -self.set_brokerage_model(BrokerageName.BITFINEX, AccountType.MARGIN) # Overrides the default account type +public override void Initialize() +{ + // Set the brokerage model to backtest with the most realistic scenario to handle the order validity, margin rate and transaction fee + SetBrokerageModel(BrokerageName.OandaBrokerage); // Defaults to margin account + SetBrokerageModel(BrokerageName.Bitfinex, AccountType.Margin); // Overrides the default account type, which is AccountType.Cash +}+def initialize(self) -> None: + # Set the brokerage model to backtest with the most realistic scenario to handle the order validity, margin rate and transaction fee + self.set_brokerage_model(BrokerageName.OANDA_BROKERAGE) # Defaults to margin account + self.set_brokerage_model(BrokerageName.BITFINEX, AccountType.MARGIN) # Overrides the default account type, which is AccountType.CashIn live trading, LEAN doesn't ignore your
diff --git a/03 Writing Algorithms/24 Reality Modeling/05 Brokerages/01 Key Concepts/06 Model Structure.html b/03 Writing Algorithms/24 Reality Modeling/05 Brokerages/01 Key Concepts/06 Model Structure.html index bfec57403c..1db7e3c98b 100644 --- a/03 Writing Algorithms/24 Reality Modeling/05 Brokerages/01 Key Concepts/06 Model Structure.html +++ b/03 Writing Algorithms/24 Reality Modeling/05 Brokerages/01 Key Concepts/06 Model Structure.html @@ -1,8 +1,14 @@SetBrokerageModel
set_brokerage_model
method calls. LEAN uses some of the brokerage model rules to catch invalid orders before they reach your real brokerage.Brokerage models should extend the
DefaultBrokerageModel
class. Extensions of theDefaultBrokerageModel
class should implement the following methods:-// In the Initialize method, set the custom brokerage model -SetBrokerageModel(new MyBrokerageModel()); +public class CustomBrokerageModelExampleAlgorithm : QCAlgorithm +{ + public override void Initialize() + { + // In the Initialize method, set the custom brokerage model + SetBrokerageModel(new MyBrokerageModel()); + } +} // Define the custom brokerage model outside of the algorithm class MyBrokerageModel : DefaultBrokerageModel @@ -88,8 +94,10 @@ } }-# In the Initialize method, set the custom brokerage model -self.set_brokerage_model(MyBrokerageModel()) +class CustomBrokerageModelExampleAlgorithm(QCAlgorithm): + def initialize(self) -> None: + # In the Initialize method, set the custom brokerage model + self.set_brokerage_model(MyBrokerageModel()) # Define the custom brokerage model outside of the algorithm class MyBrokerageModel(DefaultBrokerageModel): diff --git a/03 Writing Algorithms/24 Reality Modeling/06 Brokerage Message Handler/02 Set Models.html b/03 Writing Algorithms/24 Reality Modeling/06 Brokerage Message Handler/02 Set Models.html index 89a8d65e89..1bc70ebdb1 100644 --- a/03 Writing Algorithms/24 Reality Modeling/06 Brokerage Message Handler/02 Set Models.html +++ b/03 Writing Algorithms/24 Reality Modeling/06 Brokerage Message Handler/02 Set Models.html @@ -1,6 +1,14 @@To set a brokerage message handler, in the
Initialize
initialize
method, call theSetBrokerageMessageHandler
set_brokerage_message_handler
method.-diff --git a/03 Writing Algorithms/24 Reality Modeling/06 Brokerage Message Handler/06 Model Structure.html b/03 Writing Algorithms/24 Reality Modeling/06 Brokerage Message Handler/06 Model Structure.html index c4c217db58..e4925382d4 100644 --- a/03 Writing Algorithms/24 Reality Modeling/06 Brokerage Message Handler/06 Model Structure.html +++ b/03 Writing Algorithms/24 Reality Modeling/06 Brokerage Message Handler/06 Model Structure.html @@ -8,8 +8,14 @@SetBrokerageMessageHandler(new MyBrokerageMessageHandler(this));-self.set_brokerage_message_handler(MyBrokerageMessageHandler(self))+public override void Initialize() +{ + // Set a custom brokerage message handler for the algorithm in Initialize method + // It handles different type of returned message from the broker, helping you filter or abstract for the ones you care about + SetBrokerageMessageHandler(new MyBrokerageMessageHandler(this)); +}+def initialize(self) -> None: + # Set a custom brokerage message handler for the algorithm in Initialize method + # It handles different type of returned message from the broker, helping you filter or abstract for the ones you care about + self.set_brokerage_message_handler(MyBrokerageMessageHandler(self))The
HandleOrder
handle_order
method defines whether the transaction handler should process a new order you placed directly through the brokerage's website or third-party software.-// In the Initialize method, set the brokerage message handler -SetBrokerageMessageHandler(new MyBrokerageMessageHandler(this)); +public class CustomBrokerageMessageHandlerExampleAlgorithm : QCAlgorithm +{ + public override void Initialize() + { + // In the Initialize method, set the brokerage message handler + SetBrokerageMessageHandler(new MyBrokerageMessageHandler(this)); + } +} // Define the custom brokerage message handler public class MyBrokerageMessageHandler : DefaultBrokerageMessageHandler @@ -31,8 +37,10 @@ return false; } }-# In the Initialize method, set the brokerage message handler -self.set_brokerage_message_handler(MyBrokerageMessageHandler(self)) +class CustomBrokerageMessageHandlerExampleAlgorithm(QCAlgorithm): + def initialize(self) -> None: + # In the Initialize method, set the brokerage message handler + self.set_brokerage_message_handler(MyBrokerageMessageHandler(self)) # Define the custom brokerage message handler class MyBrokerageMessageHandler(DefaultBrokerageMessageHandler): diff --git a/03 Writing Algorithms/24 Reality Modeling/07 Buying Power/06 Set Models.php b/03 Writing Algorithms/24 Reality Modeling/07 Buying Power/06 Set Models.php index b72827d968..75141e4e31 100644 --- a/03 Writing Algorithms/24 Reality Modeling/07 Buying Power/06 Set Models.php +++ b/03 Writing Algorithms/24 Reality Modeling/07 Buying Power/06 Set Models.php @@ -1,12 +1,16 @@The brokerage model of your algorithm automatically sets the buying power model for each security, but you can override it. To manually set the buying power model of a security, call the
SetBuyingPowerModel
set_buying_power_model
method on theSecurity
object.-// In Initialize -var security = AddEquity("SPY"); -security.SetBuyingPowerModel(new SecurityMarginModel(3m));-# In Initialize -security = self.add_equity("SPY") -security.set_buying_power_model(SecurityMarginModel(3))+public override void Initialize() +{ + var security = AddEquity("SPY"); + // Use 3x leverage on the selected security, which mimic the actual buying power of your broker + security.SetBuyingPowerModel(new SecurityMarginModel(3m)); +}+def initialize(self) -> None: + security = self.add_equity("SPY") + # Use 3x leverage on the selected security, which mimic the actual buying power of your broker + security.set_buying_power_model(SecurityMarginModel(3))You can also set the buying power model in a security initializer. If your algorithm has a universe, use the security initializer technique. In order to initialize single security subscriptions with the security initializer, call
diff --git a/03 Writing Algorithms/24 Reality Modeling/07 Buying Power/09 Model Structure.html b/03 Writing Algorithms/24 Reality Modeling/07 Buying Power/09 Model Structure.html index 287c372684..0cc81c7a3f 100644 --- a/03 Writing Algorithms/24 Reality Modeling/07 Buying Power/09 Model Structure.html +++ b/03 Writing Algorithms/24 Reality Modeling/07 Buying Power/09 Model Structure.html @@ -2,8 +2,15 @@ Extensions of theSetSecurityInitializer
set_security_initializer
before you create the subscriptions.BuyingPowerModel
class should implement the following methods:-// In the Initialize method, set the buying power model -security.SetBuyingPowerModel(new MyBuyingPowerModel()); +public class CustomBuyingPowerModelExampleAlgorithm : QCAlgorithm +{ + public override void Initialize() + { + var security = AddEquity("SPY"); + // Set the custom buying power model of the selected security to mimic its actual buying power in your used broker + security.SetBuyingPowerModel(new MyBuyingPowerModel()); + } +} // Define the custom buying power model class MyBuyingPowerModel : BuyingPowerModel @@ -77,8 +84,11 @@ return base.GetBuyingPower(parameters); } }-# In the Initialize method, set the buying power model -security.set_buying_power_model(MyBuyingPowerModel()) +class CustomBuyingPowerModelExampleAlgorithm(QCAlgorithm): + def initialize(self) -> None: + security = self.add_equity("SPY") + # Set the custom buying power model of the selected security to mimic its actual buying power in your used broker + security.set_buying_power_model(MyBuyingPowerModel()) # Define the custom buying power model class MyBuyingPowerModel(BuyingPowerModel): diff --git a/03 Writing Algorithms/24 Reality Modeling/07 Buying Power/11 Set Asset Leverage.php b/03 Writing Algorithms/24 Reality Modeling/07 Buying Power/11 Set Asset Leverage.php index 9dc4fe914c..ebed2ba861 100644 --- a/03 Writing Algorithms/24 Reality Modeling/07 Buying Power/11 Set Asset Leverage.php +++ b/03 Writing Algorithms/24 Reality Modeling/07 Buying Power/11 Set Asset Leverage.php @@ -2,10 +2,14 @@To set the leverage when you create a security subscription, pass in a
leverage
argument.-// In Initialize -AddEquity("SPY", leverage: 3);-# In Initialize -self.add_equity("SPY", leverage=3)+public override void Initialize() +{ + // Set the leverage to 3x manually subjected to specific need + AddEquity("SPY", leverage: 3); +}+def initialize(self) -> None: + # Set the leverage to 3x manually subjected to specific need + self.add_equity("SPY", leverage=3)You can also set the asset leverage in a security initializer. In order to set the leverage of securities in the security initializer, call
@@ -23,10 +27,16 @@SetSecurityInitializer
set_security_initializer
before you create security subscriptions and before you callSetBrokerageModel
set_brokerage_model
. If you pass in aleverage
argument when you create the security subscription, theleverage
argument takes precedence over theSetLeverage
set_leverage
call in the security initializer.To set the leverage for all securities in a universe, set the
UniverseSettings.Leverage
universe_settings.leverage
property.-// In Initialize -UniverseSettings.Leverage = 3;-# In Initialize -self.universe_settings.leverage = 3+public override void Initialize() +{ + // Set the leverage to 3x to all securities, it should only be used for a very narrow spectrum of security universe with the same leverage + // E.g. US Equities universe composed of only primary stocks in NYSE exchange + UniverseSettings.Leverage = 3; +}+def initialize(self) ->None: + # Set the leverage to 3x to all securities, it should only be used for a very narrow spectrum of security universe with the same leverage + # E.g. US Equities universe composed of only primary stocks in NYSE exchange + self.universe_settings.leverage = 3In live trading, LEAN doesn't ignore the leverage you set. However, if you set a different leverage from what your brokerage provides, it creates a mismatch between the buying power in your algorithm and the buying power the brokerage gives you. In this case, orders can pass the validations in LEAN but your brokerage may reject them.
diff --git a/03 Writing Algorithms/24 Reality Modeling/07 Buying Power/13 Get Initial Margin Requirements.html b/03 Writing Algorithms/24 Reality Modeling/07 Buying Power/13 Get Initial Margin Requirements.html index 577f189c05..0fba1e428d 100644 --- a/03 Writing Algorithms/24 Reality Modeling/07 Buying Power/13 Get Initial Margin Requirements.html +++ b/03 Writing Algorithms/24 Reality Modeling/07 Buying Power/13 Get Initial Margin Requirements.html @@ -6,14 +6,21 @@Check Requirements of Regular Orders
@@ -43,44 +51,78 @@
- Create an
InitialMarginParameters
object with the security and quantity you want to trade.-var parameter = new InitialMarginParameters(security, quantity);-parameter = InitialMarginParameters(security, quantity)+public override void OnData(Slice slice) +{ + var security = Securities["SPY"]; + var quantity = 100m; + var parameter = new InitialMarginParameters(security, quantity);+def on_data(self, slice: Slice) -> None: + security = self.securities["SPY"] + quantity = 100 + parameter = InitialMarginParameters(security, quantity)- Call the
GetInitialMarginRequirement
get_initial_margin_requirement
method of the security's buying power model with theInitialMarginParameters
.-var initialMargin = security.BuyingPowerModel.GetInitialMarginRequirement(parameter);-initial_margin = security.buying_power_model.get_initial_margin_requirement(parameter)+var initialMargin = security.BuyingPowerModel.GetInitialMarginRequirement(parameter);+initial_margin = security.buying_power_model.get_initial_margin_requirement(parameter)The
@@ -21,18 +28,19 @@GetInitialMarginRequirement
get_initial_margin_requirement
method returns anInitialMargin
object, which have the following properties:Check Requirements of Regular Orders
- Compare the margin you have remaining against the initial margin requirement of the order.
-if (Portfolio.MarginRemaining >= initialMargin.Value) -{ - MarketOrder(security.Symbol, quantity); -} -else -{ - Debug("You don't have sufficient margin for this order."); +if (Portfolio.MarginRemaining >= initialMargin.Value) + { + MarketOrder(security.Symbol, quantity); + } + else + { + Debug("You don't have sufficient margin for this order."); + } }-if self.portfolio.margin_remaining >= initial_margin.value: - self.market_order(security.symbol, quantity) -else: - self.debug("You don't have sufficient margin for this order.")+if self.portfolio.margin_remaining >= initial_margin.value: + self.market_order(security.symbol, quantity) + else: + self.debug("You don't have sufficient margin for this order.")Check Requirements of Option Strategy Orders
Create an OptionStrategy
object with the strategy you want to trade and its buying power model.For example, create a Bull Put Spread strategy.
-var optionStrategy = OptionStrategies.BullPutSpread(_symbol, itmStrike, otmStrike, expiry);-option_strategy = OptionStrategies.bull_put_spread(self._symbol, itm_strike, otm_strike, expiry)+private Symbol _symbol; + +public override void Initialize() +{ + // Subscribe to option data and cache the canonical symbol to obtain the option data + _symbol = AddOption("SPY").Symbol; +} + +public voerride void OnData(Slice slice) +{ + // Trade on updated option chain data + if (!slice.OptionChains.TryGetValue(_symbol, out var chain)) + { + return; + } + + var itmStrike = chain.Max(x => x.Strike); + var otmStrike = chain.Min(x => x.Strike); + var expiry = chain.Min(x => x.Expiry); + + var optionStrategy = OptionStrategies.BullPutSpread(_symbol, itmStrike, otmStrike, expiry);+def initialize(self) -> None: + # Subscribe to option data and cache the canonical symbol to obtain the option data + self._symbol = self.add_option("SPY").symbol + +def on_data(self, slice: Slice) > None: + # Trade on updated option chain data + chain = slice.option_chains.get(self._symbol) + if not chain: + return + + itm_strike = max(x.strike for x in chain) + otm_strike = min(x.strike for x in chain) + expiry = min(x.expiry for x in chain) + + option_strategy = OptionStrategies.bull_put_spread(self._symbol, itm_strike, otm_strike, expiry)Create an OptionStrategyPositionGroupBuyingPowerModel
object of the strategy.-var buyingPowerModel = new OptionStrategyPositionGroupBuyingPowerModel(optionStrategy);-buying_power_model = OptionStrategyPositionGroupBuyingPowerModel(option_strategy)+var buyingPowerModel = new OptionStrategyPositionGroupBuyingPowerModel(optionStrategy);+buying_power_model = OptionStrategyPositionGroupBuyingPowerModel(option_strategy)Create a list of Position
objects from the strategy legs.-var positions = optionStrategy.OptionLegs.Select(leg => -{ - var symbol = QuantConnect.Symbol.CreateOption(_symbol.Underlying, _symbol.ID.Market, _symbol.ID.OptionStyle, leg.Right, leg.Strike, leg.Expiration); - return new Position(symbol, leg.Quantity, 1); -});-def get_symbol(leg): - return Symbol.CreateOption( - self._symbol.underlying, self._symbol.id.market, self._symbol.id.option_style, - leg.right, leg.strike, leg.expiration - ) - -positions = [Position(get_symbol(leg), leg.quantity, 1) for leg in option_strategy.option_legs]+var positions = optionStrategy.OptionLegs.Select(leg => + { + var symbol = QuantConnect.Symbol.CreateOption(_symbol.Underlying, _symbol.ID.Market, _symbol.ID.OptionStyle, leg.Right, leg.Strike, leg.Expiration); + return new Position(symbol, leg.Quantity, 1); + });+def get_symbol(leg): + return Symbol.CreateOption( + self._symbol.underlying, self._symbol.id.market, self._symbol.id.option_style, + leg.right, leg.strike, leg.expiration + ) + + positions = [Position(get_symbol(leg), leg.quantity, 1) for leg in option_strategy.option_legs]Create a PositionGroupInitialMarginParameters
objects with the portfolio and the position group.-var positionGroup = new PositionGroup(buyingPowerModel, 1, positions.ToArray()); -var parameters = new PositionGroupInitialMarginParameters(Portfolio, positionGroup);-position_group = PositionGroup(buying_power_model, 1, positions) -parameters = PositionGroupInitialMarginParameters(self.portfolio, position_group)+var positionGroup = new PositionGroup(buyingPowerModel, 1, positions.ToArray()); + var parameters = new PositionGroupInitialMarginParameters(Portfolio, positionGroup);+position_group = PositionGroup(buying_power_model, 1, positions) + parameters = PositionGroupInitialMarginParameters(self.portfolio, position_group)Call the GetInitialMarginRequirement
get_initial_margin_requirement
method of the strategy's buying power model with thePositionGroupInitialMarginParameters
.-var initialMargin = buyingPowerModel.GetInitialMarginRequirement(parameters);-initial_margin = buying_power_model.get_initial_margin_requirement(parameters)+var initialMargin = buyingPowerModel.GetInitialMarginRequirement(parameters);+initial_margin = buying_power_model.get_initial_margin_requirement(parameters)The
@@ -92,19 +134,20 @@GetInitialMarginRequirement
get_initial_margin_requirement
method returns anInitialMargin
object, which have the following properties:Check Requirements of Option Strategy Orders
For different trade sizes, multiply theinitialMargin.Value
initial_margin.value
by the quantity.-diff --git a/03 Writing Algorithms/24 Reality Modeling/08 Settlement/01 Key Concepts/02 Set Models.php b/03 Writing Algorithms/24 Reality Modeling/08 Settlement/01 Key Concepts/02 Set Models.php index 98bc720f59..b83e706c43 100644 --- a/03 Writing Algorithms/24 Reality Modeling/08 Settlement/01 Key Concepts/02 Set Models.php +++ b/03 Writing Algorithms/24 Reality Modeling/08 Settlement/01 Key Concepts/02 Set Models.php @@ -1,13 +1,17 @@var strategyQuantity = 2; -if (Portfolio.MarginRemaining >= strategyQuantity * initialMargin.Value) -{ - Buy(optionStrategy, quantity); -} -else -{ - Debug("You don't have sufficient margin for this order."); +var strategyQuantity = 2; + if (Portfolio.MarginRemaining >= strategyQuantity * initialMargin.Value) + { + Buy(optionStrategy, quantity); + } + else + { + Debug("You don't have sufficient margin for this order."); + } }-strategy_quantity = 2 -if self.portfolio.margin_remaining >= strategy_quantity * initial_margin.value: - self.buy(option_strategy, strategy_quantity) -else: - self.debug("You don't have sufficient margin for this order.")+strategy_quantity = 2 + if self.portfolio.margin_remaining >= strategy_quantity * initial_margin.value: + self.buy(option_strategy, strategy_quantity) + else: + self.debug("You don't have sufficient margin for this order.")The brokerage model of your algorithm automatically sets the settlement model for each security, but you can override it. To manually set the settlement model of a security, call the
SetSettlementModel
set_settlement_model
method on theSecurity
object.-// In Initialize -var security = AddEquity("SPY"); -// Set a delayed settlement model that settles 7 days after the trade at 8 AM -security.SetSettlementModel(new DelayedSettlementModel(7, TimeSpan.FromHours(8)));-# In Initialize -security = self.add_equity("SPY") -# Set a delayed settlement model that settles 7 days after the trade at 8 AM -security.set_settlement_model(DelayedSettlementModel(7, timedelta(hours=8)))+public override void Initialize() +{ + var security = AddEquity("SPY"); + // Set a delayed settlement model that settles 7 days after the trade at 8 AM + // This can better mimic actual settlement of some brokerage, providing more realistic fund and margin available + security.SetSettlementModel(new DelayedSettlementModel(7, TimeSpan.FromHours(8))); +}+def initialize(self) -> None: + security = self.add_equity("SPY") + # Set a delayed settlement model that settles 7 days after the trade at 8 AM + # This can better mimic actual settlement of some brokerage, providing more realistic fund and margin available + security.set_settlement_model(DelayedSettlementModel(7, timedelta(hours=8)))You can also set the settlement model in a security initializer. If your algorithm has a universe, use the security initializer technique. In order to initialize single security subscriptions with the security initializer, call
diff --git a/03 Writing Algorithms/24 Reality Modeling/08 Settlement/01 Key Concepts/04 Model Structure.html b/03 Writing Algorithms/24 Reality Modeling/08 Settlement/01 Key Concepts/04 Model Structure.html index df8c9c4c1a..44c6959cd6 100644 --- a/03 Writing Algorithms/24 Reality Modeling/08 Settlement/01 Key Concepts/04 Model Structure.html +++ b/03 Writing Algorithms/24 Reality Modeling/08 Settlement/01 Key Concepts/04 Model Structure.html @@ -18,8 +18,15 @@SetSecurityInitializer
set_security_initializer
before you create the subscriptions.-// In the Initialize method, set the custom settlement model -security.SetSettlementModel(new MySettlementModel()); +public class CustomSettlementModelExampleAlgorithm : QCAlgorithm +{ + public override void Initialize() + { + var security = AddEquity("SPY"); + // Set the custom settlement model of the selected security to reflect actual scenario for more realistic margin available + security.SetSettlementModel(new MySettlementModel()); + } +} // Define the custom settlement model outside of the algorithm public class MySettlementModel : ISettlementModel @@ -40,8 +47,11 @@ return new CashAmount(0, "USD"); } }-# In the Initialize method, set the custom settlement model -security.set_settlement_model(MySettlementModel()) +class CustomSettlementModelExampleAlgorithm(QCAlgorithm): + def initialize(self) -> None: + security = self.add_equity("SPY") + # Set the custom settlement model of the selected security to reflect actual scenario for more realistic margin available + security.set_settlement_model(MySettlementModel()) # Define the custom settlement model outside of the algorithm class MySettlementModel: diff --git a/03 Writing Algorithms/24 Reality Modeling/09 Options Models/01 Pricing/03 Set Models.php b/03 Writing Algorithms/24 Reality Modeling/09 Options Models/01 Pricing/03 Set Models.php index 4e86ab3613..bf52e2fd6e 100644 --- a/03 Writing Algorithms/24 Reality Modeling/09 Options Models/01 Pricing/03 Set Models.php +++ b/03 Writing Algorithms/24 Reality Modeling/09 Options Models/01 Pricing/03 Set Models.php @@ -7,12 +7,14 @@ { UniverseSettings.Asynchronous = true; var option = AddOption("SPY"); - option.PriceModel = OptionPriceModels.CrankNicolsonFD(); + // SPY options are American Options, in which IV and greeks more accurately calculated using Binomial model + option.PriceModel = OptionPriceModels.BinomialCoxRossRubinstein(); }def initialize(self): self.universe_settings.asynchronous = True option = self.add_option("SPY") - option.price_model = OptionPriceModels.crank_nicolson_fd()+ # SPY options are American Options, in which IV and greeks more accurately calculated using Binomial model + option.price_model = OptionPriceModels.binomial_cox_ross_rubinstein()Otherwise, set the price model in a security initializer.
@@ -20,10 +22,10 @@ To set the volatility model of the underlying security of an Option, set theVolatilityModel
property of theSecurity
object. The volatility model can have a different resolution than the underlying asset subscription.-@@ -14,7 +18,7 @@ $overwriteCodePy = "if security.Type == SecurityType.EQUITY: - security.VolatilityModel = StandardDeviationOfReturnsVolatilityModel(30)"; + security.volatility_model = StandardDeviationOfReturnsVolatilityModel(30)"; $overwriteCodeC = "if (security.Type == SecurityType.Equity) { security.VolatilityModel = new StandardDeviationOfReturnsVolatilityModel(30); diff --git a/03 Writing Algorithms/24 Reality Modeling/09 Options Models/02 Volatility/01 Key Concepts/06 Model Structure.html b/03 Writing Algorithms/24 Reality Modeling/09 Options Models/02 Volatility/01 Key Concepts/06 Model Structure.html index 65a2fb02e8..fbb393623b 100644 --- a/03 Writing Algorithms/24 Reality Modeling/09 Options Models/02 Volatility/01 Key Concepts/06 Model Structure.html +++ b/03 Writing Algorithms/24 Reality Modeling/09 Options Models/02 Volatility/01 Key Concepts/06 Model Structure.html @@ -1,8 +1,15 @@// In Initialize -var underlyingSecurity= AddEquity("SPY"); -underlyingSecurity.VolatilityModel = new StandardDeviationOfReturnsVolatilityModel(30);-# In Initialize -underlying_security = self.add_equity("SPY") -underlying_security.volatility_model = StandardDeviationOfReturnsVolatilityModel(30)+public override void Initialize() +{ + var underlyingSecurity = AddEquity("SPY"); + // Usually, the historical and implied volatility is calculated using 30-day standard deviation of return + underlyingSecurity.VolatilityModel = new StandardDeviationOfReturnsVolatilityModel(30); +}+def initialize(self) -> None: + underlying_security = self.add_equity("SPY") + # Usually, the historical and implied volatility is calculated using 30-day standard deviation of return + underlying_security.volatility_model = StandardDeviationOfReturnsVolatilityModel(30)Volatility models should extend the
BaseVolatilityModel
class. Extensions of theBaseVolatilityModel
class must haveUpdate
update
andGetHistoryRequirements
get_history_requirements
methods and aVolatility
volatility
property. TheUpdate
update
method receivesSecurity
andBaseData
objects and then updates theVolatility
volatility
. TheGetHistoryRequirements
get_history_requirements
method receivesSecurity
andDateTime
datetime
objects and then returns a list ofHistoryRequest
objects that represent the history requests to warm up the model. Volatility models receive data at each time step in the algorithm to update their state.-// In the Initialize method, set the custom volatility model of the underlying security -underlyingSecurity.VolatilityModel = new MyVolatilityModel(); +public class CustomVolatilityModelExampleAlgorithm : QCAlgorithm +{ + public override void Initialize() + { + var underlyingSecurity = AddIndex("VIX"); + // Apply custom volatility model for specific underlyings, often they are synthetic products or with different market calendar + underlyingSecurity.VolatilityModel = new MyVolatilityModel(); + } +} // Define the custom volatility model outside of the algorithm public class MyVolatilityModel : BaseVolatilityModel @@ -35,8 +42,11 @@ return base.GetHistoryRequirements(security, utcTime, resolution, barCount); } }-# In the Initialize method, set the custom volatility model of the underlying security -underlying_security.volatility_model = MyVolatilityModel() +class CustomVolatilityModelExampleAlgorithm(QCAlgorithm): + def initialize(self) -> None: + underlying_security = self.add_index("VIX") + # Apply custom volatility model for specific underlyings, often they are synthetic products or with different market calendar + underlying_security.volatility_model = MyVolatilityModel() # Define the custom volatility model outside of the algorithm class MyVolatilityModel(BaseVolatilityModel): diff --git a/03 Writing Algorithms/24 Reality Modeling/09 Options Models/02 Volatility/01 Key Concepts/07 Warm Up Models.php b/03 Writing Algorithms/24 Reality Modeling/09 Options Models/02 Volatility/01 Key Concepts/07 Warm Up Models.php index 2404ab146f..16e17bc621 100644 --- a/03 Writing Algorithms/24 Reality Modeling/09 Options Models/02 Volatility/01 Key Concepts/07 Warm Up Models.php +++ b/03 Writing Algorithms/24 Reality Modeling/09 Options Models/02 Volatility/01 Key Concepts/07 Warm Up Models.php @@ -1,17 +1,25 @@To use your volatility model as the inital guess for the implied volatility, warm up the volatility model of the underlying security. If you subscribe to all the Options in the
Initialize
initialize
method, set a warm-up period to warm up their volatility models. The warm-up period should provide the volatility models with enough data to compute their values.-// In Initialize -SetWarmUp(30, Resolution.Daily); +public override void Initialize() +{ + // For default 30-day SD of return as volatility, you need 30+1 trading day to warm up + SetWarmUp(31, Resolution.Daily); +} -// In OnData -if (IsWarmingUp) return;-# In Initialize -self.set_warm_up(30, Resolution.DAILY) +public override void OnData(Slice slice) +{ + // Only take the warmed-up volatility value into account for accuracy issue + if (IsWarmingUp) return; +}+def initialize(self) -> None: + # For default 30-day SD of return as volatility, you need 30+1 trading day to warm up + self.set_warm_up(30, Resolution.DAILY) -# In OnData -if self.is_warming_up: - return+def on_data(self, slice: Slice) -> None: + # Only take the warmed-up volatility value into account for accuracy issue + if self.is_warming_up: + returnIf you have a dynamic universe of underlying assets and add Option contracts to your algorithm with the
diff --git a/03 Writing Algorithms/24 Reality Modeling/09 Options Models/03 Exercise/05 Model Structure.html b/03 Writing Algorithms/24 Reality Modeling/09 Options Models/03 Exercise/05 Model Structure.html index 8c16594e3f..e3fb045347 100644 --- a/03 Writing Algorithms/24 Reality Modeling/09 Options Models/03 Exercise/05 Model Structure.html +++ b/03 Writing Algorithms/24 Reality Modeling/09 Options Models/03 Exercise/05 Model Structure.html @@ -4,8 +4,15 @@AddOptionContract
add_option_contract
,AddIndexOptionContract
add_index_option_contract
, orAddFutureOptionContract
add_future_option_contract
methods, warm up the volatility model when the underlying asset enters your universe. We recommend you do this inside a security initializer.using QuantConnect.Orders.OptionExercise; -// In the security initializer, set the custom Option exercise model -(security as Option).SetOptionExerciseModel(new MyOptionExerciseModel()); +public class CustomOptionExerciseModelExampleAlgorithm : QCAlgorithm +{ + public override void Initialize() + { + var security = AddOption("SPY"); + // Set custom option exercise model for mimicking specific Brokerage most realistic actions + (security as Option).SetOptionExerciseModel(new MyOptionExerciseModel()); + } +} // Define the custom Option exercise model outside of the algorithm public class MyOptionExerciseModel : IOptionExerciseModel @@ -28,8 +35,11 @@ ) { IsAssignment = isAssignment }; } }-# In the security initializer, set the custom Option exercise model -security.set_option_exercise_model(MyOptionExerciseModel()) +class CustomOptionExerciseModelExampleAlgorithm(QCAlgorithm): + def initialize(self) -> None: + security = self.add_option("SPY") + # Set custom option exercise model for mimicking specific Brokerage most realistic actions + security.set_option_exercise_model(MyOptionExerciseModel()) # Define the custom Option exercise model outside of the algorithm class MyOptionExerciseModel(DefaultExerciseModel): diff --git a/03 Writing Algorithms/24 Reality Modeling/09 Options Models/04 Assignment/05 Model Structure.html b/03 Writing Algorithms/24 Reality Modeling/09 Options Models/04 Assignment/05 Model Structure.html index 45726a9c95..c41cf979e9 100644 --- a/03 Writing Algorithms/24 Reality Modeling/09 Options Models/04 Assignment/05 Model Structure.html +++ b/03 Writing Algorithms/24 Reality Modeling/09 Options Models/04 Assignment/05 Model Structure.html @@ -2,8 +2,15 @@Option assignment models should extend the
NullOptionAssignmentModel
class. Extensions of theNullOptionAssignmentModel
class must implement theGetAssignment
get_assignment
method, which automatically fires at the top of each hour and returns the Option assignments to generate.-// In the security initializer, set the custom Option assignment model -(security as Option).SetOptionAssignmentModel(new MyOptionAssignmentModel()); +public class CustomOptionAssignmentModelExampleAlgorithm : QCAlgorithm +{ + public override void Initialize() + { + var security = AddOption("SPY"); + // Set custom option assignment model for mimicking specific Brokerage most realistic actions + (security as Option).SetOptionAssignmentModel(new MyOptionAssignmentModel()); + } +} // Define the custom Option assignment model outside of the algorithm public class MyOptionAssignmentModel : IOptionAssignmentModel @@ -20,8 +27,11 @@ return OptionAssignmentResult.Null; } }-# In the security initializer, set the custom Option assignment model -security.set_option_assignment_model(MyOptionAssignmentModel()) +class CustomOptionAssignmentModelExampleAlgorithm(QCAlgorithm): + def initialize(self) -> None: + security = self.add_option("SPY") + # Set custom option assignment model for mimicking specific Brokerage most realistic actions + security.set_option_assignment_model(MyOptionAssignmentModel()) # Define the custom Option assignment model outside of the algorithm class MyOptionAssignmentModel(NullOptionAssignmentModel): diff --git a/03 Writing Algorithms/24 Reality Modeling/10 Risk Free Interest Rate/01 Key Concepts/02 Set Models.html b/03 Writing Algorithms/24 Reality Modeling/10 Risk Free Interest Rate/01 Key Concepts/02 Set Models.html index 6736ccc95a..6c9eb39b3e 100644 --- a/03 Writing Algorithms/24 Reality Modeling/10 Risk Free Interest Rate/01 Key Concepts/02 Set Models.html +++ b/03 Writing Algorithms/24 Reality Modeling/10 Risk Free Interest Rate/01 Key Concepts/02 Set Models.html @@ -1,10 +1,16 @@To set the risk free interest rate model, in the Initialize method, call the
SetRiskFreeInterestRateModel
set_risk_free_interest_rate_model
method.-// In Initialize -SetRiskFreeInterestRateModel(new ConstantRiskFreeRateInterestRateModel(0.02m));-# In Initialize -self.set_risk_free_interest_rate_model(ConstantRiskFreeRateInterestRateModel(0.02))+public overide void Initialize() +{ + // Set the interest rate model for accurate option IV/greeks and result metrics like Sharpe Ratio + // You should set it according to the main currency of your trading Securities + SetRiskFreeInterestRateModel(new ConstantRiskFreeRateInterestRateModel(0.02m)); +}+def initialize(self) -> None: + # Set the interest rate model for accurate option IV/greeks and result metrics like Sharpe Ratio + # You should set it according to the main currency of your trading Securities + self.set_risk_free_interest_rate_model(ConstantRiskFreeRateInterestRateModel(0.02))To view all the pre-built risk free interest rate models, see Supported Models.
diff --git a/03 Writing Algorithms/24 Reality Modeling/10 Risk Free Interest Rate/01 Key Concepts/04 Model Structure.html b/03 Writing Algorithms/24 Reality Modeling/10 Risk Free Interest Rate/01 Key Concepts/04 Model Structure.html index c3b8ad9191..1b29560feb 100644 --- a/03 Writing Algorithms/24 Reality Modeling/10 Risk Free Interest Rate/01 Key Concepts/04 Model Structure.html +++ b/03 Writing Algorithms/24 Reality Modeling/10 Risk Free Interest Rate/01 Key Concepts/04 Model Structure.html @@ -1,8 +1,15 @@Risk free interest rate models must extend the
IRiskFreeInterestRateModel
interface. Extensions of theIRiskFreeInterestRateModel
interface must implement aGetInterestRate
get_interest_rate
method. TheGetInterestRate
get_interest_rate
method returns the risk free interest rate for a given date.-// In the Initialize method, set the risk free interest rate model -SetRiskFreeInterestRateModel(new MyRiskFreeInterestRateModel()); +public class CustomRiskFreeInterestRateModelExampleAlgorithm : QCAlgorithm +{ + public override void Initialize() + { + // Set the interest rate model for accurate option IV/greeks and result metrics like Sharpe Ratio + // You should set it according to the main currency of your trading Securities + SetRiskFreeInterestRateModel(new MyRiskFreeInterestRateModel()); + } +} // Define the custom risk free interest rate model public class MyRiskFreeInterestRateModel : IRiskFreeInterestRateModel @@ -12,8 +19,11 @@ return 0.02m; } }-# In the Initialize method, set the risk free interest rate model -self.set_risk_free_interest_rate_model(MyRiskFreeInterestRateModel()) +class CustomRiskFreeInterestRateModelExampleAlgorithm(QCAlgorithm): + def initialize(self) -> None: + # Set the interest rate model for accurate option IV/greeks and result metrics like Sharpe Ratio + # You should set it according to the main currency of your trading Securities + self.set_risk_free_interest_rate_model(MyRiskFreeInterestRateModel()) # Define the custom risk free interest rate model class MyRiskFreeInterestRateModel: diff --git a/03 Writing Algorithms/24 Reality Modeling/10 Risk Free Interest Rate/01 Key Concepts/06 Get Interest Rate.html b/03 Writing Algorithms/24 Reality Modeling/10 Risk Free Interest Rate/01 Key Concepts/06 Get Interest Rate.html index 85b575e689..da95839901 100644 --- a/03 Writing Algorithms/24 Reality Modeling/10 Risk Free Interest Rate/01 Key Concepts/06 Get Interest Rate.html +++ b/03 Writing Algorithms/24 Reality Modeling/10 Risk Free Interest Rate/01 Key Concepts/06 Get Interest Rate.html @@ -1,8 +1,12 @@To get the risk free interest rate for a specific time, call the
GetInterestRate
get_interest_rate
method with the time.-@@ -13,11 +17,15 @@var riskFreeInterestRate = RiskFreeInterestRateModel.GetInterestRate(Time);-risk_free_interest_rate = self.risk_free_interest_rate_model.get_interest_rate(self.time)+public override void OnData(Slice slice) +{ + var riskFreeInterestRate = RiskFreeInterestRateModel.GetInterestRate(slice.Time); +}+def on_data(self, slice: Slice) -> None: + risk_free_interest_rate = self.risk_free_interest_rate_model.get_interest_rate(slice.time)-@@ -28,11 +36,15 @@var avgRiskFreeInterestRate = RiskFreeInterestRateModel.GetRiskFreeRate(Time.AddDays(-30), Time);-avg_risk_free_interest_rate = RiskFreeInterestRateModelExtensions.get_risk_free_rate( - self.risk_free_interest_rate_model, - self.time-timedelta(7), self.time -)+public override void OnData(Slice slice) +{ + var avgRiskFreeInterestRate = RiskFreeInterestRateModel.GetRiskFreeRate(Time.AddDays(-30), Time); +}+def on_data(self, slice: Slice) -> None: + avg_risk_free_interest_rate = RiskFreeInterestRateModelExtensions.get_risk_free_rate( + self.risk_free_interest_rate_model, + self.time-timedelta(7), self.time + )-diff --git a/03 Writing Algorithms/24 Reality Modeling/11 Dividend Yield/01 Key Concepts/02 Set Models.html b/03 Writing Algorithms/24 Reality Modeling/11 Dividend Yield/01 Key Concepts/02 Set Models.html index d8fecbc935..00cbaca056 100644 --- a/03 Writing Algorithms/24 Reality Modeling/11 Dividend Yield/01 Key Concepts/02 Set Models.html +++ b/03 Writing Algorithms/24 Reality Modeling/11 Dividend Yield/01 Key Concepts/02 Set Models.html @@ -1,12 +1,19 @@var avgRiskFreeInterestRate = RiskFreeInterestRateModel.GetAverageRiskFreeRate( - new [] {Time, Time.AddDays(-180), Time.AddDays(-365)} -);-avg_risk_free_interest_rate = RiskFreeInterestRateModelExtensions.get_average_risk_free_rate( - self.risk_free_interest_rate_model, - [self.time, self.time-timedelta(180), self.time-timedelta(365)] -)+public override void OnData(Slice slice) +{ + var avgRiskFreeInterestRate = RiskFreeInterestRateModel.GetAverageRiskFreeRate( + new [] {Time, Time.AddDays(-180), Time.AddDays(-365)} + ); +}+def on_data(self, slice: Slice) -> None: + avg_risk_free_interest_rate = RiskFreeInterestRateModelExtensions.get_average_risk_free_rate( + self.risk_free_interest_rate_model, + [self.time, self.time-timedelta(180), self.time-timedelta(365)] + )To set the dividend yield model for an Option indicator, pass a
DividendYieldProvider
as thedividendYieldModel
dividend_yield_model
parameter.-// Before creating the indicator, create the set dividend yield model -var dividendYieldModel = new DividendYieldProvider(symbol.Underlying); -_iv = new ImpliedVolatility(symbol, RiskFreeInterestRateModel, dividendYieldModel, OptionPricingModelType.BlackScholes);-# Before creating the indicator, create the set dividend yield model -dividend_yield_model = DividendYieldProvider(symbol.underlying) -self.iv = ImpliedVolatility(symbol, self.risk_free_interest_rate_model, dividend_yield_model, OptionPricingModelType.BLACK_SCHOLES)++public override void Initialize() +{ + // Before creating the indicator, create the set dividend yield model, such that it will use it in default + // Using DividendYieldProvider will calculate the continuous dividend yield using all dividend payoffs in 1 year + var dividendYieldModel = new DividendYieldProvider(symbol.Underlying); + _iv = new ImpliedVolatility(symbol, RiskFreeInterestRateModel, dividendYieldModel, OptionPricingModelType.BlackScholes); +}+def initialize(self) -> None: + # Before creating the indicator, create the set dividend yield model + # Using DividendYieldProvider will calculate the continuous dividend yield using all dividend payoffs in 1 year + dividend_yield_model = DividendYieldProvider(symbol.underlying) + self.iv = ImpliedVolatility(symbol, self.risk_free_interest_rate_model, dividend_yield_model, OptionPricingModelType.BLACK_SCHOLES)To view all the pre-built dividend yield models, see Supported Models.
diff --git a/03 Writing Algorithms/24 Reality Modeling/11 Dividend Yield/01 Key Concepts/04 Model Structure.html b/03 Writing Algorithms/24 Reality Modeling/11 Dividend Yield/01 Key Concepts/04 Model Structure.html index 9133e91a78..6be01bea61 100644 --- a/03 Writing Algorithms/24 Reality Modeling/11 Dividend Yield/01 Key Concepts/04 Model Structure.html +++ b/03 Writing Algorithms/24 Reality Modeling/11 Dividend Yield/01 Key Concepts/04 Model Structure.html @@ -1,9 +1,16 @@Dividend yield models must extend the
IDividendYieldModel
interface. Extensions of theIDividendYieldModel
interface must implement aGetDividendYield
get_dividend_yield
method. TheGetDividendYield
get_dividend_yield
method returns the dividend yield for a given date.-// Before creating the indicator, create the dividend yield model -var dividendYieldModel = new MyDividendYieldModel(); -_iv = new ImpliedVolatility(symbol, RiskFreeInterestRateModel, dividendYieldModel, OptionPricingModelType.BlackScholes); +public class CustomDividendYieldModelExampleAlgorithm : QCAlgorithm +{ + public override void Initialize() + { + var symbol = AddEquity("SPY").Symbol; + // Before creating the indicator, create the dividend yield model + var dividendYieldModel = new MyDividendYieldModel(); + _iv = new ImpliedVolatility(symbol, RiskFreeInterestRateModel, dividendYieldModel, OptionPricingModelType.BlackScholes); + } +} // Define the custom dividend yield model public class MyDividendYieldModel : IDividendYieldModel @@ -13,9 +20,12 @@ return 0.02m; } }-# Before creating the indicator, create the dividend yield model -dividend_yield_model = MyDividendYieldModel() -self.iv = ImpliedVolatility(symbol, self.risk_free_interest_rate_model, dividend_yield_model, OptionPricingModelType.BLACK_SCHOLES) +class CustomDividendYieldModelExampleAlgorithm(QCAlgorithm): + def initialize(self) -> None: + symbol = self.add_equity("SPY").symbol + # Before creating the indicator, create the dividend yield model + dividend_yield_model = MyDividendYieldModel() + self.iv = ImpliedVolatility(symbol, self.risk_free_interest_rate_model, dividend_yield_model, OptionPricingModelType.BLACK_SCHOLES) # Define the custom dividend yield model class MyDividendYieldModel: diff --git a/03 Writing Algorithms/24 Reality Modeling/12 Margin Interest Rate/01 Key Concepts/02 Set Models.php b/03 Writing Algorithms/24 Reality Modeling/12 Margin Interest Rate/01 Key Concepts/02 Set Models.php index 71dc411609..6e98329e21 100644 --- a/03 Writing Algorithms/24 Reality Modeling/12 Margin Interest Rate/01 Key Concepts/02 Set Models.php +++ b/03 Writing Algorithms/24 Reality Modeling/12 Margin Interest Rate/01 Key Concepts/02 Set Models.php @@ -1,11 +1,15 @@The brokerage model of your algorithm automatically sets the margin interest rate model for each security, but you can override it. To manually set the margin interest rate model of a security, assign a model to the
MarginInterestRateModel
property of the Security object.-// In Initialize -var security = AddEquity("SPY"); -security.MarginInterestRateModel = MarginInterestRateModel.Null;-# In Initialize -security = self.add_equity("SPY") -security.set_margin_interest_rate_model(MarginInterestRateModel.NULL)+public override void Initialize() +{ + var security = AddEquity("SPY"); + // Null margin interest rate model is non-realistic, you should set it according to your broker information + security.MarginInterestRateModel = MarginInterestRateModel.Null; +}+def initialize(self) -> None: + security = self.add_equity("SPY") + # Null margin interest rate model is non-realistic, you should set it according to your broker information + security.set_margin_interest_rate_model(MarginInterestRateModel.NULL)You can also set the margin interest rate model in a security initializer. If your algorithm has a dynamic universe, use the security initializer technique. In order to initialize single security subscriptions with the security initializer, call
SetSecurityInitializer
set_security_initializer
before you create the subscriptions.diff --git a/03 Writing Algorithms/24 Reality Modeling/12 Margin Interest Rate/01 Key Concepts/04 Model Structure.html b/03 Writing Algorithms/24 Reality Modeling/12 Margin Interest Rate/01 Key Concepts/04 Model Structure.html index 9213dd96d0..54eae23c49 100644 --- a/03 Writing Algorithms/24 Reality Modeling/12 Margin Interest Rate/01 Key Concepts/04 Model Structure.html +++ b/03 Writing Algorithms/24 Reality Modeling/12 Margin Interest Rate/01 Key Concepts/04 Model Structure.html @@ -1,8 +1,15 @@
Margin interest rate models should implement the
IMarginInterestRateModel
interface. Extensions of theIMarginInterestRateModel
interface must implement theApplyMarginInterestRate
apply_margin_interest_rate
method, which applies margin interest payments to the portfolio.-// In the Initialize method, set the margin interest rate model -security.SetMarginInterestRateModel(new MyMarginInterestRateModel()); +public class CustomMarginInterestRateModelExampleAlgorithm : QCAlgorithm +{ + public override void Initialize() + { + var security = AddEquity("SPY"); + // You should set it according to your broker information for the least actual-expected discrepancies + security.SetMarginInterestRateModel(new MyMarginInterestRateModel()); + } +} // Define the custom margin interest rate model public class MyMarginInterestRateModel : IMarginInterestRateModel @@ -14,8 +21,11 @@ positionValue.Cash.AddAmount(-1); } }-# In the Initialize method, set the margin interest rate model -security.set_margin_interest_rate_model(MyMarginInterestRateModel()) +class CustomMarginInterestRateModelExampleAlgorithm(QCAlgorithm): + def initialize(self) -> None: + security = self.add_equity("SPY") + # You should set it according to your broker information for the least actual-expected discrepancies + security.set_margin_interest_rate_model(MyMarginInterestRateModel()) # Define the custom margin interest rate model class MyMarginInterestRateModel: diff --git a/03 Writing Algorithms/24 Reality Modeling/13 Margin Calls/02 Set Models.html b/03 Writing Algorithms/24 Reality Modeling/13 Margin Calls/02 Set Models.html index abb1a6fdd9..a2d403e57a 100644 --- a/03 Writing Algorithms/24 Reality Modeling/13 Margin Calls/02 Set Models.html +++ b/03 Writing Algorithms/24 Reality Modeling/13 Margin Calls/02 Set Models.html @@ -1,10 +1,14 @@ To set the margin call model, call theSetMarginCallModel
set_margin_call_model
method of thePortfolio
portfolio
object.-diff --git a/03 Writing Algorithms/24 Reality Modeling/13 Margin Calls/06 Model Structure.html b/03 Writing Algorithms/24 Reality Modeling/13 Margin Calls/06 Model Structure.html index 9226685aa6..59708d1894 100644 --- a/03 Writing Algorithms/24 Reality Modeling/13 Margin Calls/06 Model Structure.html +++ b/03 Writing Algorithms/24 Reality Modeling/13 Margin Calls/06 Model Structure.html @@ -5,8 +5,14 @@// In Initialize -Portfolio.SetMarginCallModel(new DefaultMarginCallModel(Portfolio, DefaultOrderProperties)); +public override void Initialize() +{ + // Set margin call model for the whole portfolio, better with reference to your broker information + Portfolio.SetMarginCallModel(new DefaultMarginCallModel(Portfolio, DefaultOrderProperties)); +}-# In Initialize -self.portfolio.set_margin_call_model(DefaultMarginCallModel(self.portfolio, self.default_order_properties)) +def initialize(self) -> None: + # Set margin call model for the whole portfolio, better with reference to your broker information + self.portfolio.set_margin_call_model(DefaultMarginCallModel(self.portfolio, self.default_order_properties))The
ExecuteMarginCall
execute_margin_call
method receives the list ofSubmitOrderRequest
objects from theGetMarginCallOrders
get_margin_call_orders
method, executes some of them, and returns a list ofOrderTicket
objects.-// In the Initialize method, set the margin call model -Portfolio.SetMarginCallModel(new MyMarginCallModel(Portfolio, DefaultOrderProperties)); +public class CustomMarginCallModelExampleAlgorithm : QCAlgorithm +{ + public override void Initialize() + { + // Set margin call model for the whole portfolio, better with reference to your broker information + Portfolio.SetMarginCallModel(new MyMarginCallModel(Portfolio, DefaultOrderProperties)); + } +} // Define the custom margin call model public class MyMarginCallModel : DefaultMarginCallModel @@ -24,13 +30,15 @@ return base.ExecuteMarginCall(generatedMarginCallOrders); } - public List<SubmitOrderRequest>-GetMarginCallOrders(out bool issueMarginCallWarning) + public List<SubmitOrderRequest> GetMarginCallOrders(out bool issueMarginCallWarning) { return base.GetMarginCallOrders(out issueMarginCallWarning); } -} # In the Initialize method, set the margin call model -self.portfolio.set_margin_call_model(MyMarginCallModel(self.portfolio, self.default_order_properties)) +}+class CustomMarginCallModelExampleAlgorithm(QCAlgorithm): + def initialize(self) -> None: + # Set margin call model for the whole portfolio, better with reference to your broker information + self.portfolio.set_margin_call_model(MyMarginCallModel(self.portfolio, self.default_order_properties)) # Define the custom margin call model class MyMarginCallModel(DefaultMarginCallModel): diff --git a/03 Writing Algorithms/24 Reality Modeling/13 Margin Calls/07 Disable Margin Calls.html b/03 Writing Algorithms/24 Reality Modeling/13 Margin Calls/07 Disable Margin Calls.html index 776b11aa02..576eae70ab 100644 --- a/03 Writing Algorithms/24 Reality Modeling/13 Margin Calls/07 Disable Margin Calls.html +++ b/03 Writing Algorithms/24 Reality Modeling/13 Margin Calls/07 Disable Margin Calls.html @@ -1,8 +1,11 @@To disable margin calls, set the margin call model to the
NullMarginCallModel
.-diff --git a/03 Writing Algorithms/24 Reality Modeling/14 Short Availability/01 Key Concepts/02 Set Providers.php b/03 Writing Algorithms/24 Reality Modeling/14 Short Availability/01 Key Concepts/02 Set Providers.php index 048678de66..7886a57093 100644 --- a/03 Writing Algorithms/24 Reality Modeling/14 Short Availability/01 Key Concepts/02 Set Providers.php +++ b/03 Writing Algorithms/24 Reality Modeling/14 Short Availability/01 Key Concepts/02 Set Providers.php @@ -2,29 +2,37 @@Portfolio.MarginCallModel = MarginCallModel.Null; --self.portfolio.margin_call_model = MarginCallModel.NULL +public override void Initialize() +{ + Portfolio.MarginCallModel = MarginCallModel.Null; +}+def initialize(self) -> None: + self.portfolio.margin_call_model = MarginCallModel.NULL-// In Initialize -var security = AddEquity("SPY"); -security.SetShortableProvider(new LocalDiskShortableProvider("axos"));-# In Initialize -security = self.add_equity("SPY") -security.set_shortable_provider(LocalDiskShortableProvider("axos"))+public override void Initialize() +{ + var security = AddEquity("SPY"); + // Get shortable stocks and quantity from local disk + security.SetShortableProvider(new LocalDiskShortableProvider("axos")); +}+def initialize(self) -> None: + security = self.add_equity("SPY") + # Get shortable stocks and quantity from local disk + security.set_shortable_provider(LocalDiskShortableProvider("axos"))You can also set the shortable provider in a security initializer. If your algorithm has a universe, use the security initializer technique. In order to initialize single security subscriptions with the security initializer, call
SetSecurityInitializer
set_security_initializer
before you create the subscriptions.-// In Initialize -SetSecurityInitializer(CustomSecurityInitializer); -AddEquity("SPY"); +public override void Initialize() +{ + // Set the security initializer before requesting data to apply to all requested securities afterwards + SetSecurityInitializer(CustomSecurityInitializer); + AddEquity("SPY"); +} private void CustomSecurityInitializer(Security security) { security.SetShortableProvider(new LocalDiskShortableProvider("axos")); }-# In Initialize -self.set_security_initializer(self.custom_security_initializer) -self.add_equity("SPY") +def initialize(self) -> None: + # Set the security initializer before requesting data to apply to all requested securities afterwards + self.set_security_initializer(self.custom_security_initializer) + self.add_equity("SPY") def custom_security_initializer(self, security: Security) -> None: security.set_shortable_provider(LocalDiskShortableProvider("axos")) diff --git a/03 Writing Algorithms/24 Reality Modeling/14 Short Availability/01 Key Concepts/04 Provider Structure.html b/03 Writing Algorithms/24 Reality Modeling/14 Short Availability/01 Key Concepts/04 Provider Structure.html index 71ece48f96..1cfa7d7e83 100644 --- a/03 Writing Algorithms/24 Reality Modeling/14 Short Availability/01 Key Concepts/04 Provider Structure.html +++ b/03 Writing Algorithms/24 Reality Modeling/14 Short Availability/01 Key Concepts/04 Provider Structure.html @@ -8,8 +8,15 @@-// In the Initialize method, set the shortable provider -security.SetShortableProvider(new MyShortableProvider()); +public class CustomShortableProviderExampleAlgorithm : QCAlgorithm +{ + public override void Initialize() + { + var security = AddEquity("SPY"); + // Provide the selected security with your broker's shortable information + security.SetShortableProvider(new MyShortableProvider()); + } +} // Define the custom shortable provider class MyShortableProvider : IShortableProvider @@ -29,8 +36,11 @@ return 10000; } }-# In the Initialize method, set the shortable provider -security.set_shortable_provider(MyShortableProvider()) +class CustomShortableProviderExampleAlgorithm(QCAlgorithm): + def initialize(self) -> None: + security = self.add_equity("SPY") + # Provide the selected security with your broker's shortable information + security.set_shortable_provider(MyShortableProvider()) # Define the custom shortable provider class MyShortableProvider(NullShortableProvider): diff --git a/Resources/order-types/stale-fills.html b/Resources/order-types/stale-fills.html index 204c859bdd..e7890bc898 100644 --- a/Resources/order-types/stale-fills.html +++ b/Resources/order-types/stale-fills.html @@ -1,6 +1,12 @@Stale fills occur when you fill an order with price data that is timestamped an hour or more into the past. Stale fills usually only occur if you trade illiquid assets or if your algorithm uses daily data but you trade intraday with Scheduled Events. If your order is filled with stale data, the fill price may not be realistic. The pre-built fill models can only fill market orders with stale data. To adjust the length of time that needs to pass before an order is considered stale, set the
StalePriceTimeSpan
stale_price_time_span
setting.-diff --git a/Resources/reality-modeling/brokerage-model-security-init.php b/Resources/reality-modeling/brokerage-model-security-init.php index b01ca9423e..a32d02e615 100644 --- a/Resources/reality-modeling/brokerage-model-security-init.php +++ b/Resources/reality-modeling/brokerage-model-security-init.php @@ -28,15 +28,21 @@ } ?>Settings.StalePriceTimeSpan = TimeSpan.FromMinutes(10);-self.settings.stale_price_time_span = timedelta(minutes=10)+public override void Initialize() +{ + // Filling over 10 minutes after order submitted is considered stale, in which the filling slippage and condition might be out of expectation. + Settings.StalePriceTimeSpan = TimeSpan.FromMinutes(10); +}+def initialize(self) -> None: + # Filling over 10 minutes after order submitted is considered stale, in which the filling slippage and condition might be out of expectation. + self.settings.stale_price_time_span = timedelta(minutes=10)-diff --git a/Resources/reality-modeling/disable-buying-power.php b/Resources/reality-modeling/disable-buying-power.php index d5e9156af3..2c3c038ebd 100644 --- a/Resources/reality-modeling/disable-buying-power.php +++ b/Resources/reality-modeling/disable-buying-power.php @@ -13,14 +13,20 @@// In the Initialize method, set the security initializer to seed initial the prices and models of assets. -SetSecurityInitializer(new MySecurityInitializer(BrokerageModel, new FuncSecuritySeeder(GetLastKnownPrices)=$extraArgsC?>)); ++public class BrokerageModelExampleAlgorithm : QCAlgorithm +{ + public override void Initialize() + { + // In the Initialize method, set the security initializer to seed initial the prices and models of assets. + SetSecurityInitializer(new MySecurityInitializer(BrokerageModel, new FuncSecuritySeeder(GetLastKnownPrices)=$extraArgsC?>)); + } +} -class MySecurityInitializer : BrokerageModelSecurityInitializer +public class MySecurityInitializer : BrokerageModelSecurityInitializer { =$classMemberC?>public MySecurityInitializer(IBrokerageModel brokerageModel, ISecuritySeeder securitySeeder=$extraParamsC?>) : base(brokerageModel, securitySeeder) =$contructorBodyC ?> - public override void Initialize(Security security) { // First, call the superclass definition. @@ -44,20 +50,19 @@ class MySecurityInitializer : BrokerageModelSecurityInitializer base.Initialize(security); // Next, overwrite =$comment?> - =$overwriteCodeC?> - } }-# In the Initialize method, set the security initializer to seed initial the prices and models of assets. -self.set_security_initializer(MySecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices)=$extraArgsPy?>)) +class BrokerageModelExampleAlgorithm(QCAlgorithm): + def initialize(self) -> None: + # In the Initialize method, set the security initializer to seed initial the prices and models of assets. + self.set_security_initializer(MySecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices)=$extraArgsPy?>)) # Outside of the algorithm class class MySecurityInitializer(BrokerageModelSecurityInitializer): def __init__(self, brokerage_model: IBrokerageModel, security_seeder: ISecuritySeeder=$extraParamsPy?>) -> None: super().__init__(brokerage_model, security_seeder)=$contructorBodyPy?> - def initialize(self, security: Security) -> None: # First, call the superclass definition. @@ -65,6 +70,5 @@ class MySecurityInitializer(BrokerageModelSecurityInitializer): super().initialize(security) # Next, overwrite =$comment?> - =$overwriteCodePy?>To disable the validations of the default buying power model, use the
NullBuyingPowerModel
. To set theNullBuyingPowerModel
for a security subscription, call theSetBuyingPowerModel
set_buying_power_model
method with theBuyingPowerModel.NullNULL
argument.-var equity = AddEquity("SPY"); -equity.SetBuyingPowerModel(BuyingPowerModel.Null); -// Alias: -// equity.SetMarginModel(SecurityMarginModel.Null);-equity = self.add_equity("SPY") -equity.set_buying_power_model(BuyingPowerModel.NULL) -# Alias: -# equity.set_margin_model(SecurityMarginModel.NULL)+public override void Initialize() +{ + var equity = AddEquity("SPY"); + // To disable any buying power of the selected security + equity.SetBuyingPowerModel(BuyingPowerModel.Null); + // Alias: + // equity.SetMarginModel(SecurityMarginModel.Null); +}+def initialize(self) -> None: + equity = self.add_equity("SPY") + # To disable any buying power of the selected security + equity.set_buying_power_model(BuyingPowerModel.NULL) + # Alias: + # equity.set_margin_model(SecurityMarginModel.NULL)