Problem Description
Solution
To find out the margin requirement for a specific security in QuantConnect, you access the buying_power_model property of the Security object.
The buying_power_model provides methods to calculate:
- Initial Margin: The cash required to open a new position.
- Maintenance Margin: The equity required to keep an existing position open.
Implementation Details
To calculate the Initial Margin, you must create an InitialMarginParameters object, which requires the security and the quantity you intend to trade.
To calculate the Maintenance Margin, you simply pass the security object to the model (assuming you already hold a position).
Code Example
The following algorithm demonstrates how to log the margin requirements for a specific trade (e.g., buying 10 shares of SPY) and check the maintenance margin for current holdings.
from AlgorithmImports import *
class MarginRequirementAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2023, 1, 1)
self.set_end_date(2023, 1, 5)
self.set_cash(100000)
# Add a security
self.spy = self.add_equity("SPY", Resolution.MINUTE).symbol
def on_data(self, slice: Slice):
if not self.portfolio.invested:
# 1. Calculate Initial Margin Requirement (To Open a Trade)
# -------------------------------------------------------
quantity_to_buy = 10
security = self.securities[self.spy]
# Create the parameters object: (Security, Quantity)
# This asks: "How much margin do I need to buy 10 shares?"
margin_params = InitialMarginParameters(security, quantity_to_buy)
# Get the requirement
initial_margin = security.buying_power_model.get_initial_margin_requirement(margin_params)
self.log(f"Price: {security.price}")
self.log(f"Initial Margin required for {quantity_to_buy} shares: ${initial_margin.value}")
# Place the trade
self.market_order(self.spy, quantity_to_buy)
else:
# 2. Calculate Maintenance Margin (To Hold Current Position)
# ----------------------------------------------------------
security = self.securities[self.spy]
# This asks: "How much equity do I need to maintain my current position?"
maintenance_margin = security.buying_power_model.get_maintenance_margin(security)
self.log(f"Current Maintenance Margin for holdings: ${maintenance_margin}")
self.log(f"Total Margin Used: ${self.portfolio.total_margin_used}")
Key Components Explained
-
self.securities[symbol].buying_power_model:
This is the model responsible for setting leverage and margin rules. By default, Equities useSecurityMarginModel(typically 50% initial margin for overnight, 25% for intraday), and Futures useFutureMarginModel(based on SPAN). -
InitialMarginParameters(security, quantity):
This helper object packages the request. You must specify the quantity because margin often scales linearly, but in some complex models (like options or tiered margin), the size of the trade matters. -
get_initial_margin_requirement(parameters):
Returns aBuyingPowerobject. You access the actual monetary value using.value. -
get_maintenance_margin(security):
Calculates the minimum equity needed to avoid a margin call for the current holdings of that security.
Q&A
Q: How does QuantConnect determine the margin model for a security?
A: LEAN automatically assigns a default margin model based on the asset class (e.g., SecurityMarginModel for Equities, PatternDayTradingMarginModel for PDT accounts, or FutureMarginModel for Futures). You can override this in initialize using self.securities[symbol].set_buying_power_model().
Q: Can I check if I have enough margin before placing an order?
A: Yes. Instead of manually calculating the margin, you can use self.portfolio.get_buying_power(symbol, direction). This returns the maximum buying power available for that specific symbol, allowing you to calculate the maximum quantity you can afford.
Q: What happens if the maintenance margin requirement exceeds my portfolio equity?
A: The on_margin_call_warning event is triggered when margin remaining drops below 5%. If the situation persists, the on_margin_call event is triggered, and LEAN will liquidate positions to restore the required margin level.
Q: Does the margin requirement include leverage?
A: Yes. The buying_power_model accounts for the leverage set on the security. For example, if leverage is set to 2.0, the get_initial_margin_requirement will return roughly 50% of the trade value.