book
Checkout our new book! Hands on AI Trading with Python, QuantConnect, and AWS Learn More arrow

Requesting Data

Individual Contracts

Introduction

The add_option_contract method enables you to add an individual Option contract to your algorithm. To check which contracts are currently available to add to your algorithm, use the option_chain method. If you want to subscribe to a set of contracts instead of individual contracts one-by-one, see Universes.

Create Subscriptions

Before you can subscribe to an Option contract, you must configure the underlying Equity and get the contract Symbol.

Select Language:
class BasicOptionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2024, 1, 1)
        self._underlying = self.add_equity('SPY', data_normalization_mode=DataNormalizationMode.RAW).symbol
        self._contract_symbol = None

    def on_data(self, data):
        if self._contract_symbol:
            return
        chain = self.option_chain(self._underlying, flatten=True).data_frame
        expiry = chain.expiry.min()
        self._contract_symbol = chain[
            (chain.expiry == expiry) &
            (chain.right == OptionRight.CALL) &
            (chain.delta < 0.7) &
            (chain.delta > 0.3)
        ].sort_values('openinterest').index[-1]
        self.add_option_contract(self._contract_symbol)

Configure the Underlying Equity

If you want to subscribe to the underlying Equity in the initialize method, set the Equity data normalization to DataNormalizationMode.RAW.

Select Language:
self._underlying = self.add_equity("SPY", data_normalization_mode=DataNormalizationMode.RAW).symbol

If your algorithm has a dynamic universe of Equities, before you add the Equity universe in the initialize method, set the universe data normalization mode to DataNormalizationMode.RAW.

Select Language:
self.universe_settings.data_normalization_mode = DataNormalizationMode.RAW

Get Contract Symbols

To subscribe to an Option contract, you need the contract Symbol. The preferred method to getting Option contract Symbol objects is to use the option_chain method. This method returns an OptionChain object, which represent an entire chain of Option contracts for a single underlying security. You can even format the chain data into a DataFrame where each row in the DataFrame represents a single contract. With the chain, sort and filter the data to find the specific contract(s) you want to trade.

Select Language:
# Get the contracts available to trade (in DataFrame format).
chain = self.option_chain(self._underlying, flatten=True).data_frame

# Select a contract.
expiry = chain.expiry.min()
self._contract_symbol = chain[
    # Select call contracts with the closest expiry.
    (chain.expiry == expiry) & 
    (chain.right == OptionRight.CALL) &
    # Select contracts with a 0.3-0.7 delta.
    (chain.delta > 0.3) &
    (chain.delta < 0.7)
    # Select the contract with the largest open interest.
].sort_values('openinterest').index[-1]

Subscribe to Contracts

To create an Equity Option contract subscription, pass the contract Symbol to the add_option_contract method. Save a reference to the contract symbol so you can easily access the Option contract in the OptionChain that LEAN passes to the on_data method. This method returns an Option object. To override the default pricing model of the Option, set a pricing model.

Select Language:
option = self.add_option_contract(self._contract_symbol)
option.price_model = OptionPriceModels.binomial_cox_ross_rubinstein()

The add_option_contract method creates a subscription for a single Option contract and adds it to your user-defined universe. To create a dynamic universe of Option contracts, add an Equity Options universe or an Options Universe Selection model.

Warm Up Contract Prices

If you subscribe to an Option contract with add_option_contract, you'll need to wait until the next Slice to receive data and trade the contract. To trade the contract in the same time step you subscribe to the contract, set the current price of the contract in a security initializer.

Select Language:
seeder = FuncSecuritySeeder(self.get_last_known_prices)
self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, seeder))

Supported Assets

To view the supported assets in the US Equities dataset, see the Data Explorer.

Resolutions

The following table shows the available resolutions and data formats for Equity Option contract subscriptions:

ResolutionTradeBarQuoteBarTrade TickQuote Tick
TICK

SECOND

MINUTEgreen checkgreen check
HOURgreen checkgreen check
DAILYgreen checkgreen check

The default resolution for Option contract subscriptions is Resolution.MINUTE. To change the resolution, pass a resolution argument to the add_option_contract method.

Select Language:
self.add_option_contract(self._contract_symbol, Resolution.MINUTE)

To create custom resolution periods, see Consolidating Data.

Supported Markets

LEAN groups all of the US Equity exchanges under Market.USA. You don't need to pass a market argument to the add_option_contract method because the contract symbol already contains the market.

Fill Forward

Fill forward means if there is no data point for the current slice, LEAN uses the previous data point. Fill forward is the default data setting. If you disable fill forward, you may get stale fills or you may see trade volume as zero.

To disable fill forward for a security, set the fill_forward argument to false when you create the security subscription.

Select Language:
self.add_option_contract(self._contract_symbol, fill_forward=False)

Margin and Leverage

LEAN models buying power and margin calls to ensure your algorithm stays within the margin requirements. Options are already leveraged products, so you can't change their leverage.

Extended Market Hours

By default, your security subscriptions only cover regular trading hours. To subscribe to pre and post-market trading hours for a specific asset, enable the extended_market_hours argument when you create the security subscription.

Select Language:
self.add_option_contract(self._contract_symbol, extended_market_hours=True)

You only receive extended market hours data if you create the subscription with minute, second, or tick resolution. If you create the subscription with daily or hourly resolution, the bars only reflect the regular trading hours.

To view the schedule of regular and extended market hours, see Market Hours.

Data Normalization

The data normalization mode doesn't affect the data that LEAN passes to on_data or the data from history request. By default, LEAN doesn't adjust Equity Options data for splits and dividends of their underlying. If you change the data normalization mode, it won't change the outcome.

If you hold an Option contract when a corporate action occurs for the underlying Equity, LEAN automatically closes your position.

Remove Subscriptions

To remove a contract subscription that you created with add_option_contract, call the remove_option_contract method. This method is an alias for remove_security.

Select Language:
self.remove_option_contract(self._contract_symbol)

The remove_option_contract method cancels your open orders for the contract and liquidates your holdings.

Properties

The add_option_contract method returns an Option object, which have the following properties:

Helper Methods

The Option object provides methods you can use for basic calculations. These methods require the underlying price. To get the Option object and the Security object for its underlying in any function, use the Option symbol to access the value in the securities object.

Select Language:
option = self.securities[self._contract_symbol]
underlying = self.securities[self._contract_symbol.underlying]
underlying_price = underlying.price

To get the Option payoff, call the get_pay_off method.

Select Language:
pay_off = option.get_pay_off(underlying_price)

To get the Option intrinsic value, call the get_intrinsic_value method.

Select Language:
intrinsic_value = option.get_intrinsic_value(underlying_price)

To get the Option out-of-the-money amount, call the out_of_the_money_amount method.

Select Language:
otm_amount = option.out_of_the_money_amount(underlying_price)

To check whether the Option can be automatic exercised, call the is_auto_exercised method.

Select Language:
is_auto_exercised = option.is_auto_exercised(underlying_price)

Exceptions and Edge Cases

The following sections explain exceptions and edge cases with subscribing to individual Option contracts.

Manually Creating Option Symbol Objects

To subscribe to an Option contract, you need the contract Symbol. You can get the contract Symbol from the create_option or option_chain methods. If you use the create_option method, you need to provide the details of an existing contract.

Select Language:
self._contract_symbol = Symbol.create_option(self._underlying, Market.USA,
    OptionStyle.AMERICAN, OptionRight.CALL, 365, datetime(2022, 6, 17))

Default Underlying Subscription Settings

If you subscribe to an Equity Option contract but don't have a subscription to the underlying Equity, LEAN automatically subscribes to the underlying Equity with the following settings:

SettingValue
Fill forwardSame as the Option contract
Leverage0
Extended Market HoursSame as the Option contract
Data NormalizationDataNormalizationMode.RAW

In this case, you still need the Equity Symbol to subscribe to Equity Option contracts. If you don't have access to it, create it.

Select Language:
self._underlying = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)

Overriding the Initial Implied Volatility Guess

To override the initial guess of implied volatility, set and warm up the underlying volatility model.

Examples

The following examples demonstrate some common practices for requesting individual Equity Option contract data.

Example 1: Covered Call

A cover call consists of a short call and with a lot of the underlying equity. Although it capped the maximum profit if the underlying skyrocketted, it also provide extra credit received while speculating the underlying will rise.

Select Language:
class EquityOptionExampleAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2018, 1, 1)
        self.set_end_date(2019, 1, 1)
        self._chain = pd.DataFrame()
        # Seed the security price to ensure the retrieval of the ATM calls at the initial filtering.
        self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices)))
        # Set the data normalization mode as raw for option strike-price comparability.
        self.aapl = self.add_equity("AAPL", data_normalization_mode=DataNormalizationMode.RAW).symbol
        
        # Filter an updated option list at market open everyday by a scheduled event.
        self.schedule.on(
            self.date_rules.every_day(self.aapl),
            self.time_rules.at(9, 0),
            self.refresh_option_list
        )
    
    def refresh_option_list(self) -> None:
        # Get all tradable option contracts for AAPL at the current time for filtering.
        chain = self.option_chain(self.aapl, flatten=True).data_frame
        if chain.empty:
            return
        # Select the calls expires within 30 days and within $5 strike from ATM as leg of the covered call.
        # $5 buffer is given on selecting the ATM call due to price movement.
        expiry_threshold = self.time + timedelta(30)
        self._chain = chain[
            (chain.expiry < expiry_threshold) &
            (chain.right == OptionRight.CALL) &
            (abs(chain.strike - chain.underlyinglastprice) <= 5)
        ]
        for symbol in self._chain.index:
            self.add_option_contract(symbol)
    
    def on_data(self, slice: Slice) -> None:
        if not self.portfolio.invested and self.aapl in slice.bars and not self._chain.empty:
            # To form a covered call, get the contract closest to ATM and expiry.
            self._chain['abs_moneyness'] = abs(self._chain.strike - self._chain.underlyinglastprice)
            expiry = self._chain.expiry.min()
            contract = self._chain[self._chain.expiry == expiry].sort_values('abs_moneyness').index[0]
                
            # Covered call involves shorting 1 ATM call and ordering 1 lot of underlying.
            self.market_order(contract, -1)
            self.market_order(self.aapl, self.securities[contract].symbol_properties.contract_multiplier)
    
    def on_order_event(self, order_event: OrderEvent) -> None:
        # Close AAPL position if the short call is not exercised (OTM).
        # If it is exercised, the underlying will be used to settle the contract automatically.
        if order_event.ticket.order_type == OrderType.OPTION_EXERCISE \
        and not order_event.is_in_the_money:
            self.market_order(self.aapl, -self.securities[order_event.symbol].symbol_properties.contract_multiplier)

Example 2: 0-DTE Bull Put Spread

0DTE options often trades with high volume and volatility, providing arbitration opportunities and higher profit margin on spread type trading. In this example, we make use of 0-DTE SPY options to trade bull put spread option strategy.

Select Language:
class EquityOptionExampleAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.options = []
        # Seed the underlying security price to ensure accurate filtering for puts of $5 above/below current market price.
        self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices)))
        # Set the data normalization mode as raw for option strike-price comparability.
        self.spy = self.add_equity("SPY", data_normalization_mode=DataNormalizationMode.RAW).symbol
        
        # Filter an updated option list at market open everyday by a scheduled event.
        self.schedule.on(
            self.date_rules.every_day(self.spy),
            self.time_rules.at(9, 0),
            self.refresh_option_list
        )
    
        # Use a scheduled event to close all positions before market close.
        self.schedule.on(
            self.date_rules.every_day(self.spy),
            self.time_rules.before_market_close(self.spy, 1),
            self.exit_position
        )
    
    def refresh_option_list(self) -> None:
        # Get all tradable option contracts for SPY at the current time for filtering.
        contract_symbols = self.option_chain(self.spy)
        # Select the 0-DTE puts by setting expiry within 1 day.
        filtered_symbols = [symbol for symbol in contract_symbols
            if symbol.id.date < self.time + timedelta(1) and symbol.id.option_right == OptionRight.PUT]
        # Ensure at least 2 contracts available to form a put spread.
        if len(filtered_symbols) < 2:
            self.options = []
            return
            
        # To form a put spread, select and subscribe to put contracts $5 above and below from the current underlying price.
        itm_put = sorted(filtered_symbols, key=lambda symbol: abs(symbol.id.strike_price - self.securities[self.spy].price - 5))[0]
        otm_put = sorted(filtered_symbols, key=lambda symbol: abs(symbol.id.strike_price - self.securities[self.spy].price + 5))[0]
        self.options = [self.add_option_contract(itm_put).symbol, self.add_option_contract(otm_put).symbol]
    
    def on_data(self, slice: Slice) -> None:
        # To avoid over-trading, limit the position opening to before 3pm.
        # To ensure the put spread formed correctly, make sure at least 2 contracts selected.
        if not self.portfolio.invested and self.time.hour < 15 and len(self.options) == 2:
            # A bull put spread involves buying a lower-strike put and selling a high-strike put
            sorted_by_strike = sorted(self.options, key=lambda x: x.id.strike_price)
            self.market_order(sorted_by_strike[-1], -1)
            self.market_order(sorted_by_strike[0], 1)
    
    def exit_position(self) -> None:
        # Exit all positions before market close to avoid option assignment and overnight risk.
        self.liquidate()

Example 3: Select Option Contracts by Greeks

The following algorithm creates a weekly Scheduled Event that adds a universe of contracts with a Delta >= 0.99. This universe is useful for creating a hedge replicate portfolio for arbitrage.

Select Language:
class EquityOptionExampleAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2019, 1, 1)
        self.set_end_date(2019, 6, 1)
        # Add the underlying asset with raw data to enable Option strike-price comparability.
        self._underlying = self.add_equity("SPY", data_normalization_mode=DataNormalizationMode.RAW).symbol    
        # Add a Scheduled Event to select the Option contracts to trade each week.
        self.schedule.on(
            self.date_rules.week_start(self._underlying),
            self.time_rules.at(7, 30),
            self._add_contracts
        )
    
    def _add_contracts(self) -> None:
        self._universe = []
        # Get all the tradable Option contracts for SPY at the current time.
        chain = self.option_chain(self._underlying, flatten=True).data_frame
        if not chain.empty:
            # Add the contracts that have the nearest expiry after 7 days and a delta >= 0.99.
            expiry_threshold = self.time + timedelta(7)
            expiry = chain[chain.expiry >= expiry_threshold].expiry.min()
            self._universe = [
                self.add_option_contract(symbol) 
                for symbol in chain[(chain.expiry == expiry) & (chain.delta >= 0.99)].index
            ]
        # Plot the number of contracts in the universe.
        self.plot('Universe', 'Size', len(self._universe))

Example 4: Wheel Strategy

The Wheel strategy is a popular trading strategy for Options that enables traders to build a steady flow of income from Equity assets they want to hold for the long term.

Select Language:
class EquityOptionExampleAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2021, 1, 1)
        self.set_end_date(2022, 1, 1)
        self.set_cash(1000000000)
        
        # Set the data normalization mode as raw for option strike-price comparability.
        self.spy = self.add_equity("SPY", data_normalization_mode=DataNormalizationMode.RAW).symbol
        # Set OTM threshold for wheel strategy profit margin.
        self.otm_threshold = 0.05
    
    def on_data(self, slice: Slice) -> None:
        # To use the latest underlying price to filter the option contract, ensure the SPY in the bar data.
        # Open short put contract position only when the last wheel is completed.
        if not self.portfolio.invested and self.spy in slice.bars:
            # Initiate the wheel by shorting a least-OTM put contract that the strike is below the threshold.
            symbol = self.get_target_contract(OptionRight.PUT, slice.bars[self.spy].price * (1 - self.otm_threshold))
            self.set_holdings(symbol, -0.2)
        # Open short call contract position only when the put is assigned (portfolio with the underlying) to close the wheel and underlying position by the call assignment.
        elif self.portfolio[self.spy].invested and self.spy in slice.bars:
            # Short the corresponding number of a least-OTM call contract that the strike is above the threshold.
            symbol = self.get_target_contract(OptionRight.CALL, slice.bars[self.spy].price * (1 + self.otm_threshold))
            self.market_order(symbol, self.portfolio[self.spy].quantity / self.securities[self.spy].symbol_properties.contract_multipliers)
        
    def get_target_contract(self, right: OptionRight, target_price: float) -> Symbol:
        # Get all tradable option contracts for SPY at the current time for filtering.
        contract_symbols = self.option_chain(self.spy)
        if not contract_symbols:
            return
        # Filter for the least-OTM contract that is off by the threshold to form the wheel.
        # Expiry is set to be at least 30 days to earn the time decay, which is highest in the last month.
        expiry = min(x.id.date for x in contract_symbols)
        filtered = [x for x in contract_symbols \
            if x.id.date == expiry \
            and x.id.option_right == right \
            and (x.id.strike_price >= target_price if right == OptionRight.CALL else x.id.strike_price <= target_price)]
        sorted_by_strikes = sorted(filtered, key=lambda x: x.id.strike_price)
        selected = sorted_by_strikes[0] if right == OptionRight.CALL else sorted_by_strikes[-1]
        # Request the selected contract data for trading.
        return self.add_option_contract(selected).symbol

For more details, refer to the Wheel Strategy research post .

Example 5: Scan and Update Option Chain Every 5 Minutes

The following example shows how to update the Option chain every five minutes. The OptionChainManager class implements the selection logic and manages the contract subscriptions.

Select Language:
class OptionChainFullExample(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2023, 1, 2)
        self.set_end_date(2023, 1, 30)
        self.set_cash(100000)

        self.universe_settings.asynchronous = True
        self.universe_settings.minimum_time_in_universe = timedelta(minutes=0)        
        # Seed the security price to ensure the underlying price data is ready at the initial filtering
        self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices)))
        # Set the data normalization mode as raw for option strike-price comparability
        spy = self.add_equity("SPY", data_normalization_mode=DataNormalizationMode.RAW).symbol
        # Set up a OptionChainManager to filter the contracts based on latest data by request
        self._chain_manager = {
            Symbol.create_canonical_option(spy): OptionChainManager(-10, 10, 0, 7)
        }
        # Daily population of the available contracts to ensure the contracts are tradable
        self._populate_option_chain()
        self.schedule.on(
            self.date_rules.every_day(spy), self.time_rules.after_market_open(spy, 1), self._populate_option_chain
        )
        # Filter for contract in every 5 minutes interval through scheduled event
        self.schedule.on(self.date_rules.every_day(spy), self.time_rules.every(timedelta(minutes=5)), self._filter)

    def _populate_option_chain(self):
        # The contract list is updated daily, so we can get it and apply
        # the expiration filter as soon as the market opens.
        for symbol, manager in self._chain_manager.items():
            manager.set_chain(self.option_chain(symbol), self.time)
        self._filter()

    def _filter(self):
        for symbol, manager in self._chain_manager.items():
            manager.select(self, symbol)

    def on_data(self, slice: Slice) -> None:
        # Iterate the saved symbol and chain manager to obtain only the contract wanted
        for symbol, _ in self._chain_manager.items():
            chain = slice.option_chains.get(symbol)
            if not chain: 
                continue
            expiry = min([x.expiry for x in chain])
            contracts = [
                x for x in chain 
                if x.expiry == expiry and x.right == OptionRight.CALL and self.securities[x.symbol].is_tradable
            ]
            if not contracts: 
                continue
            atm_call = sorted(contracts, key=lambda x: abs(chain.underlying.price-x.strike))[0]

            if not self.portfolio[atm_call.symbol].invested:
                self.market_order(atm_call.symbol, 1)


class OptionChainManager:
    _chain = []
    _symbols = set([])
    
    def __init__(self, min_strike, max_strike, min_expiry, max_expiry):
        self._min_strike = min_strike
        self._max_strike = max_strike
        self._min_expiry = min_expiry
        self._max_expiry = max_expiry
    
    def set_chain(self, chain: OptionChain, time: datetime) -> None:
        # Expiry criteria will not affect intra-day universe filtering, so it is done in a daily basis in higher level
        self._chain = [x for x in chain if self._min_expiry <= (x.expiry - time).days <= self._max_expiry]
    
    def select(self, algorithm: QCAlgorithm, symbol: Symbol) -> None:
        if not self._chain:
            return
        if symbol.is_canonical():
            symbol = symbol.underlying

        # Select by strike range from ATM
        strikes = sorted(set(x.strike for x in self._chain))
        spot = algorithm.securities[symbol].price
        atm = sorted(strikes, key=lambda x: abs(spot-x))[0]
        index = strikes.index(atm)
        min_strike = strikes[max(0, index + self._min_strike)]
        max_strike = strikes[min(len(strikes) - 1, index + self._max_strike)]
        symbols = set(x.symbol for x in self._chain if min_strike <= x.strike <= max_strike)
        
        # Also remove data subscription on the contracts being filtered out to release computation resources
        for symbol in self._symbols - symbols:
            if algorithm.remove_option_contract(symbol):
                self._symbols.remove(symbol)
        # Request data subscription on the newly selected contracts for trading
        for symbol in symbols - self._symbols:
            self._symbols.add(symbol)
            algorithm.add_option_contract(symbol)

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: