Equity Options
Handling Data
Introduction
LEAN passes the data you request to the on_data
method so you can make trading decisions. The Slice
object that the on_data
method receives groups all the data together at a single moment in time. To access the Slice
outside of the on_data
method, use the current_slice
property of your algorithm.
All the data formats use DataDictionary
objects to group data by Symbol
and provide easy access to information. The plural of the type denotes the collection of objects. For instance, the TradeBars
DataDictionary
is made up of TradeBar
objects. To access individual data points in the dictionary, you can index the dictionary with the contract ticker or symbol
, but we recommend you use the symbol
.
To view the resolutions that are available for Equity Options data, see Resolutions.
Trades
TradeBar
objects are price bars that consolidate individual trades from the exchanges. They contain the open, high, low, close, and volume of trading activity over a period of time.

To get the TradeBar
objects in the Slice
, index the Slice
or index the bars
property of the Slice
with the contract symbol
. If the contract doesn't actively trade or you are in the same time step as when you added the contract subscription, the Slice
may not contain data for your symbol
. To avoid issues, check if the Slice
contains data for your contract before you index the Slice
with the contract symbol
.
def on_data(self, slice: Slice) -> None: # Obtain the mapped TradeBar of the symbol if any trade_bar = slice.bars.get(self._contract_symbol) # None if not found
You can also iterate through the TradeBars
dictionary. The keys of the dictionary are the Symbol
objects and the values are the TradeBar
objects.
def on_data(self, slice: Slice) -> None: # Iterate all received Symbol-TradeBar key-value pairs for symbol, trade_bar in slice.bars.items(): close_price = trade_bar.close
TradeBar
objects have the following properties:
Quotes
QuoteBar
objects are bars that consolidate NBBO quotes from the exchanges. They contain the open, high, low, and close prices of the bid and ask. The open
, high
, low
, and close
properties of the QuoteBar
object are the mean of the respective bid and ask prices. If the bid or ask portion of the QuoteBar
has no data, the open
, high
, low
, and close
properties of the QuoteBar
copy the values of either the bid
or ask
instead of taking their mean.

To get the QuoteBar
objects in the Slice
, index the QuoteBars
property of the Slice
with the contract symbol
. If the contract doesn't actively get quotes or you are in the same time step as when you added the contract subscription, the Slice
may not contain data for your symbol
. To avoid issues, check if the Slice
contains data for your contract before you index the Slice
with the contract symbol
.
def on_data(self, slice: Slice) -> None: # Obtain the mapped QuoteBar of the symbol if any quote_bar = slice.quote_bars.get(self._contract_symbol) # None if not found
You can also iterate through the QuoteBars
dictionary. The keys of the dictionary are the Symbol
objects and the values are the QuoteBar
objects.
def on_data(self, slice: Slice) -> None: # Iterate all received Symbol-QuoteBar key-value pairs for symbol, quote_bar in slice.quote_bars.items(): ask_price = quote_bar.ask.close
QuoteBar
objects let LEAN incorporate spread costs into your simulated trade fills to make backtest results more realistic.
QuoteBar
objects have the following properties:
Option Chains
OptionChain
objects represent an entire chain of Option contracts for a single underlying security.
To get the OptionChain
, index the option_chains
property of the Slice
with the canonical Symbol
.
def on_data(self, slice: Slice) -> None: # Try to get the OptionChain using the canonical symbol (None if no OptionChain return) chain = slice.option_chains.get(self._contract_symbol.Canonical) if chain: # Get all contracts if the OptionChain contains any member contracts = chain.contracts
You can also loop through the option_chains
property to get each OptionChain
.
def on_data(self, slice: Slice) -> None: # Iterate all received Canonical Symbol-OptionChain key-value pairs for canonical_symbol, chain in slice.option_chains.items(): contracts = chain.contracts
OptionChain
objects have the following properties:
Option Contracts
OptionContract
objects represent the data of a single Option contract in the market.
To get the Option contracts in the Slice
, use the contracts
property of the OptionChain
.
def on_data(self, slice: Slice) -> None: # Try to get the OptionChain using the canonical symbol chain = slice.option_chains.get(self._contract_symbol.canonical) if chain: # Get individual contract data contract = chain.contracts.get(self._contract_symbol) if contract: price = contract.price
Greeks and Implied Volatility
To get the Greeks and implied volatility of an Option contract, use the greeks
and implied_volatility
members.
def on_data(self, slice: Slice) -> None: # Try to get the OptionChain using the canonical symbol chain = slice.option_chains.get(self._contract_symbol.canonical) if chain: # Get individual contract data contract = chain.contracts.get(self._contract_symbol) if contract: # Get greeks data of the selected contract delta = contract.greeks.delta iv = contract.implied_volatility
LEAN only calculates Greeks and implied volatility when you request them because they are expensive operations. If you invoke the greeks
property, the Greeks aren't calculated. However, if you invoke the greeks.delta
, LEAN calculates the delta. To avoid unecessary computation in your algorithm, only request the Greeks and implied volatility when you need them. For more information about the Greeks and implied volatility, see Options Pricing.
Open Interest
Open interest is the number of outstanding contracts that haven't been settled. It provides a measure of investor interest and the market liquidity, so it's a popular metric to use for contract selection. Open interest is calculated once per day. To get the latest open interest value, use the open_interest
property of the Option
or option_contract
.
def on_data(self, slice: Slice) -> None: # Try to get the option_chains using the canonical symbol chain = slice.option_chains.get(self._contract_symbol.canonical) if chain: # Get individual contract data contract = chain.contracts.get(self._contract_symbol) if contract: # Get the open interest of the selected contracts open_interest = contract.open_interest
Properties
OptionContract
objects have the following properties:
Examples
Example 1: Get Mid Price For Individual Contracts
This example shows how to handle
QuoteBar
data for shortlisted Equity Option contracts to calculate mid price using bid close and ask close data, while
filter individual option contracts and request data
using
self.option_chain
method for the contracts that expires within the current week. Using mid price, we can examine the market fair value of the Option and compare with model theoretical price.
class EquityOptionHandlingDataAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2021, 1, 1) self.set_end_date(2021, 4, 1) self.contracts = [] # Seed the price with last known price to ensure the underlying price data is available on initial option contract filtering. self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices))) # Subscribe to underlying data for ATM calculation using the update underlying price. # Set data normalization mode to raw is required to ensure strike price and underlying price is comparable. self.spy = self.add_equity("SPY", data_normalization_mode=DataNormalizationMode.RAW).symbol # Update the tradable contracts daily before market open since the option contract list provider populate them daily. self.schedule.on( self.date_rules.every_day(self.spy), self.time_rules.at(9, 0), self.update_contracts ) def update_contracts(self) -> None: # Get all contracts that expiring this week to trade with, subscribe to data for trading need. contracts = self.option_chain(self.spy) self.contracts = [self.add_option_contract(x).symbol for x in contracts if x.id.date < Expiry.end_of_week(self.time)] def on_data(self, slice: Slice) -> None: # Only focus on filtered list of option contracts to trade. for contract in self.contracts: # Mid price can only be calculated when quote bar data is available. quote = slice.quote_bars.get(contract) if quote and quote.bid is not None and quote.ask is not None: # Mid price = average of bid close price and ask close price. mid_price = (quote.bid.close + quote.ask.close) * 0.5
Example 2: Get Mid Price For Universe
This example shows how to handle
QuoteBar
data for shortlisted Equity Option contracts to calculate mid price using bid close and ask close data, while
request data through universe selection function
using
set_filter
method for the contracts that expires within the current week. Using mid price, we can examine the market fair value of the Option and compare with model theoretical price.
class EquityOptionHandlingDataAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2021, 1, 1) self.set_end_date(2021, 4, 1) # Seed the price with last known price to ensure the underlying price data is available on initial option contract filtering. self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices))) # Subscribe to underlying data for ATM calculation using the update underlying price. # Set data normalization mode to raw is required to ensure strike price and underlying price is comparable. spy = self.add_equity("SPY", data_normalization_mode=DataNormalizationMode.RAW).symbol # Subscribe to SPY option data. option = self.add_option(spy) self._symbol = option.symbol # We wish to only trade the contracts expiring within the same week since they have the highest volume. option.set_filter(lambda u: u.include_weeklys().contracts(lambda x: [s for s in x if s.id.date <= Expiry.end_of_week(self.time)])) def on_data(self, slice: Slice) -> None: # Only want to obtain the option chain of the selected symbol. chain = slice.option_chains.get(self._symbol) if not chain: return for contract in chain: # Mid price = average of bid close price and ask close price mid_price = (contract.bid_price + contract.ask_price) * 0.5
Example 3: Get Instant Delta
The option greeks change rapidly, so we need to obtain the instant greeks to accurately calculate the hedge size for arbitration or replication portfolio. You can call the
Greeks
property from the
OptionChain
data to access various greeks. In this example, we will demonstrate how to obtain the contract with delta closest to 0.4 among all call contracts expiring the same week.
class EquityOptionHandlingDataAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2021, 1, 1) self.set_end_date(2021, 4, 1) # Seed the price with last known price to ensure the underlying price data is available on initial option contract filtering. self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices))) # Subscribe to underlying data for ATM calculation using the update underlying price. # Set data normalization mode to raw is required to ensure strike price and underlying price is comparable. spy = self.add_equity("SPY", data_normalization_mode=DataNormalizationMode.RAW).symbol # Subscribe to SPY option data. option = self.add_option(spy) self._symbol = option.symbol # We wish to only trade the contracts expiring within the same week since they have the highest volume. # 0.4 Delta will only appear in call contracts. option.set_filter(lambda u: u.include_weeklys().delta(0.2, 0.6).contracts(lambda x: [s for s in x if s.id.date <= Expiry.end_of_week(self.time)])) def on_data(self, slice: Slice) -> None: # Only want to obtain the option chain of the selected symbol. chain = slice.option_chains.get(self._symbol) if not chain: return # Get the contract with Delta closest to 0.4 to trade. # The arbitary delta criterion might be set due to hedging need or risk adjustment. selected = sorted(chain, key=lambda x: abs(x.greeks.delta - 0.4))[0]