Index Options
Handling Data
Introduction
LEAN passes the data you request to the OnDataon_data method so you can make trading decisions. The default OnDataon_data method accepts a Slice object, but you can define additional OnDataon_data methods that accept different data types. For example, if you define an OnDataon_data method that accepts a TradeBar argument, it only receives TradeBar objects. The Slice object that the OnDataon_data method receives groups all the data together at a single moment in time. To access the Slice outside of the OnDataon_data method, use the CurrentSlicecurrent_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 Symbolsymbol, but we recommend you use the Symbolsymbol.
To view the resolutions that are available for Index 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 Barsbars property of the Slice with the contract Symbolsymbol. 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 Symbolsymbol. To avoid issues, check if the Slice contains data for your contract before you index the Slice with the contract Symbolsymbol.
public override void OnData(Slice slice)
{
// Check if the symbol is contained in TradeBars object
if (slice.Bars.ContainsKey(_contractSymbol))
{
// Obtain the mapped TradeBar of the symbol
var tradeBar = slice.Bars[_contractSymbol];
}
}
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.
public override void OnData(Slice slice)
{
// Iterate all received Symbol-TradeBar key-value pairs
foreach (var kvp in slice.Bars)
{
var symbol = kvp.Key;
var tradeBar = kvp.Value;
var closePrice = tradeBar.Close;
}
} 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 Openopen, Highhigh, Lowlow, and Closeclose 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 Openopen, Highhigh, Lowlow, and Closeclose properties of the QuoteBar copy the values of either the Bidbid or Askask instead of taking their mean.
To get the QuoteBar objects in the Slice, index the QuoteBars property of the Slice with the contract Symbolsymbol. 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 Symbolsymbol. To avoid issues, check if the Slice contains data for your contract before you index the Slice with the contract Symbolsymbol.
public override void OnData(Slice slice)
{
// Check if the symbol is contained in QuoteBars object
if (slice.QuoteBars.ContainsKey(_contractSymbol))
{
// Obtain the mapped QuoteBar of the symbol
var quoteBar = slice.QuoteBars[_contractSymbol];
}
}
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.
public override void OnData(Slice slice)
{
// Iterate all received Symbol-QuoteBar key-value pairs
foreach (var kvp in slice.QuoteBars)
{
var symbol = kvp.Key;
var quoteBar = kvp.Value;
var askPrice = quoteBar.Ask.Close;
}
} 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 OptionChainsoption_chains property of the Slice with the canonical Symbol.
public override void OnData(Slice slice)
{
// Try to get the OptionChain using the canonical symbol
if (slice.OptionChains.TryGetValue(_contractSymbol.Canonical, out var chain))
{
// Get all contracts if the OptionChain contains any member
var contracts = chain.Contracts;
}
} 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 OptionChainsoption_chains property to get each OptionChain.
public override void OnData(Slice slice)
{
// Iterate all received Canonical Symbol-OptionChain key-value pairs
foreach (var kvp in slice.OptionChains)
{
var canonicalSymbol = kvp.Key;
var chain = kvp.Value;
var contracts = chain.Contracts;
}
} 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
Filter Chains
OptionChain objects provide the same filter methods as Option universe selection, with the same names and the same behavior.
Each method returns a new OptionChain and leaves the source chain unchanged, so you can chain the calls together.
// Select the call contracts that expire in 20-40 days and are within 3 strikes of the underlying price. var contracts = chain.CallsOnly().Expiration(20, 40).Strikes(-3, 3);
# Select the call contracts that expire in 20-40 days and are within 3 strikes of the underlying price. contracts = chain.calls_only().expiration(20, 40).strikes(-3, 3)
The contract property filters, the Greeks and implied volatility filters, and the Option strategy filters are all available. The strategy filters select the legs of the strategy, or return an empty chain when no set of contracts matches the criteria.
// Select the four legs of an Iron Condor that expires in at least 30 days. var legs = chain.IronCondor(30, 5, 10);
# Select the four legs of an Iron Condor that expires in at least 30 days. legs = chain.iron_condor(30, 5, 10)
To filter the chain with your own predicate, use LINQ's Where method.
To filter the chain with your own predicate, call the where method.
var liquidContracts = chain.Where(contract => contract.OpenInterest > 100);
liquid_contracts = chain.where(lambda contract: contract.open_interest > 100)
The StandardsOnlystandards_only and WeeklysOnlyweeklys_only methods of a chain apply to the contracts the chain already holds, so you can combine them with the expiration filters in any order.
In universe selection, these two filters always run last.
Select Contracts
To get a single contract from the chain, call the Selectselect method.
It returns the contract that best matches the criteria you provide, or nullNone when the chain holds no match.
// Get the put contract at 85% of the underlying price, from the expiration closest to 30 days out. var contract = chain.Select(OptionRight.Put, targetDte: 30, moneyness: -0.15m);
# Get the put contract at 85% of the underlying price, from the expiration closest to 30 days out. contract = chain.select(OptionRight.PUT, target_dte=30, moneyness=-0.15)
These methods take a target number of days to expiration and return the closest expiration within the optional minDtemin_dte and maxDtemax_dte window.
The Option strategy filters instead take a minimum number of days to expiration and return the first expiration at or after it.
The following table describes the contract selection methods of the OptionChain class:
Select(OptionRight? right, int? targetDte, int? minDte, int? maxDte, decimal moneyness)select(right: OptionRight = None, target_dte: int = None, min_dte: int = None, max_dte: int = None, moneyness: float = 0) Selects the contract with the strike closest to |
Pick(OptionRight? right, int? targetDte, int? minDte, int? maxDte, decimal moneyness)pick(right: OptionRight = None, target_dte: int = None, min_dte: int = None, max_dte: int = None, moneyness: float = 0) A synonym of the |
SelectByStrikeDistance(decimal strikeFromAtm, OptionRight? right, int? targetDte, int? minDte, int? maxDte)select_by_strike_distance(strike_from_atm: float, right: OptionRight = None, target_dte: int = None, min_dte: int = None, max_dte: int = None) Selects the contract with the strike closest to a signed distance from the underlying price, in price units. This is how the Option strategy filters express their strikes. |
SelectByDelta(decimal targetDelta, OptionRight? right, int? targetDte, int? minDte, int? maxDte)select_by_delta(target_delta: float, right: OptionRight = None, target_dte: int = None, min_dte: int = None, max_dte: int = None) Selects the contract with the absolute delta closest to the absolute target, so a 30 delta put is 0.3 or -0.3. Contracts without Greeks are ignored. |
AtTheMoney(OptionRight? right)at_the_money(right: OptionRight = None) Selects the contract with the strike closest to the underlying price. Ties go to the lower strike, then to the nearest expiration. |
ClosestExpiry(int? targetDte, int? minDte, int? maxDte)closest_expiry(target_dte: int = None, min_dte: int = None, max_dte: int = None) Returns the expiration date closest to the target number of days out, or |
At(DateTime expiry)at(expiry: datetime) Returns a new chain with the contracts of the given expiration date. The time of day is ignored. |
The expiration methods compose with the chain filters, so you can narrow a single expiration down further.
var expiry = chain.ClosestExpiry(targetDte: 45, minDte: 30, maxDte: 60); var contracts = chain.At(expiry.Value).PutsOnly().Strikes(-2, 0);
expiry = chain.closest_expiry(target_dte=45, min_dte=30, max_dte=60) contracts = chain.at(expiry).puts_only().strikes(-2, 0)
OptionChain objects also expose read-only views of their contracts: Callscalls and Putsputs, sorted by expiration and then strike; Expiriesexpiries, the distinct expiration dates in ascending order; and StrikePricesstrike_prices, the distinct strikes in ascending order.
StrikePricesstrike_prices is a StrikeList object, which adds the ClosestToclosest_to, FirstAbovefirst_above, and FirstBelowfirst_below methods.
Each one takes a reference price and returns nullNone when no strike matches.
var strike = chain.StrikePrices.FirstAbove(chain.Underlying.Price);
strike = chain.strike_prices.first_above(chain.underlying.price)
Properties
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 Contractscontracts property of the OptionChain.
public override void OnData(Slice slice)
{
// Try to get the OptionChain using the canonical symbol
if (slice.OptionChains.TryGetValue(_contractSymbol.Canonical, out var chain))
{
// Get individual contract data
if (chain.Contracts.TryGetValue(_contractSymbol, out var contract))
{
var price = contract.Price;
}
}
} 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 Greeksgreeks and implied_volatility members.
public override void OnData(Slice slice)
{
// Try to get the OptionChain using the canonical symbol
if (slice.OptionChains.TryGetValue(_contractSymbol.Canonical, out var chain))
{
// Get individual contract data
if (chain.Contracts.TryGetValue(_contractSymbol, out var contract))
{
// Get greeks data of the selected contract
var delta = contract.Greeks.Delta;
var iv = contract.ImpliedVolatility;
}
}
} 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 Greeksgreeks property, the Greeks aren't calculated. However, if you invoke the Greeks.Deltagreeks.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 OpenInterestopen_interest property of the Option or OptionContractoption_contract.
public override void OnData(Slice slice)
{
// Try to get the OptionChains using the canonical symbol
if (slice.OptionChains.TryGetValue(_contractSymbol.Canonical, out var chain))
{
// Get individual contract data
if (chain.Contracts.TryGetValue(_contractSymbol, out var contract))
{
// Get the open interest of the selected contracts
var openInterest = contract.OpenInterest;
}
}
}
public void OnData(OptionChains optionChains)
{
// Try to get the OptionChains using the canonical symbol
if (optionChains.TryGetValue(_contractSymbol.Canonical, out var chain))
{
// Get individual contract data
if (chain.Contracts.TryGetValue(_contractSymbol, out var contract))
{
// Get the open interest of the selected contracts
var openInterest = contract.OpenInterest;
}
}
}
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
The following examples demonstrate some common practices for handling Index Options.
Example 1: Supply-Demand Pressure Of Individual Contract
This example shows how to handle QuoteBar data for the SPXW Index Option contracts to trade based on the supply-demand pressure, while filter individual option contracts and request data using OptionChainself.option_chain method for the contracts that expire that day.
public class IndexOptionHandlingDataAlgorithm : QCAlgorithm
{
private Option _spxw;
private List<Symbol> _contracts = new();
public override void Initialize()
{
SetStartDate(2024, 9, 1);
SetEndDate(2024, 12, 31);
SetCash(100000000);
// Subscribe to underlying data for ATM calculation using the updated underlying price.
// Set data normalization mode to raw is required to ensure the strike price and underlying price are comparable.
_spxw = AddIndexOption("SPX", "SPXW");
_spxw.SetFilter((x) => x.Expiration(0, 3).Strikes(-5, 5));
// Update the tradable contracts daily before the market opens since the option contract list provider populates them daily.
Schedule.On(
DateRules.EveryDay(_spxw.Symbol),
TimeRules.At(9, 0),
UpdateContracts
);
}
private void UpdateContracts()
{
// Get all contracts that expire today, and subscribe to data for trading needs.
// We do not need to liquidate or handle settlement since all contracts are cash-settled after market close.
// We only get the strike contracts within $10 of the underlying for higher liquidity and less slippage.
_contracts = OptionChain(_spxw.Symbol)
.Where(x => x.Expiry <= Time.AddDays(1) && Math.Abs(x.UnderlyingLastPrice - x.Strike) < 10)
.Select(x => x.Symbol)
.ToList();
}
public override void OnData(Slice slice)
{
// Only focus on a filtered list of option contracts to trade and select the ATM call.
var contract = _contracts.Where(x => x.ID.OptionRight == OptionRight.Call)
.MinBy(x => Math.Abs(Securities[x.Underlying].Price - x.ID.StrikePrice));
if (contract == null)
{
return;
}
// Trade based on the updated data.
if (slice.QuoteBars.TryGetValue(contract, out var quote) && !Portfolio.Invested)
{
if (quote.Bid != null && quote.Ask != null)
{
// If the last trading price is close to the asking price, the selling pressure is higher, so we are short.
var diff = quote.Ask.Close - 2 * quote.Close + quote.Bid.Close;
if (diff < 0)
{
SetHoldings(contract, -0.05m);
}
else
{
SetHoldings(contract, 0.05m);
}
}
}
}
} class IndexOptionHandlingDataAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_start_date(2024, 9, 1)
self.set_end_date(2024, 12, 31)
self.set_cash(100000000)
self.contracts = []
# Subscribe to underlying data for ATM calculation using the updated underlying price.
# Set data normalization mode to raw is required to ensure the strike and underlying prices are comparable.
self.spxw = self.add_index_option("SPX", "SPXW")
self.spxw.set_filter(lambda x: x.expiration(0, 3).strikes(-5, 5))
# Update the tradable contracts daily before the market opens since the option contract list provider populates them daily.
self.schedule.on(
self.date_rules.every_day(self.spxw.symbol),
self.time_rules.at(9, 0),
self.update_contracts
)
def update_contracts(self) -> None:
# Get all contracts that expire today, and subscribe to data for trading needs.
# We do not need to liquidate or handle settlement since all contracts are cash-settled after market close.
# We only get the strike contracts within $10 of the underlying for higher liquidity and less slippage.
contracts = self.option_chain(self.spxw.symbol)
self.contracts = [x.symbol for x in contracts
if x.expiry < self.time + timedelta(1) and\
abs(x.underlying_last_price - x.strike) < 10]
def on_data(self, slice: Slice) -> None:
# Only focus on a filtered list of option contracts to trade and select the ATM call.
calls = [x for x in self.contracts if x.id.option_right == OptionRight.CALL]
if not calls:
return
contract = sorted(
calls,
key=lambda x: abs(self.securities[x.underlying].price - x.id.strike_price)
)[0]
# Trade based on the updated data.
quote = slice.quote_bars.get(contract)
if quote and quote.bid is not None and quote.ask is not None and not self.portfolio.invested:
# if the last trading price is close to the ask price, the sell pressure is higher, so we short.
diff = quote.ask.close - 2 * quote.close + quote.bid.close
if diff < 0:
self.set_holdings(contract, -0.05)
else:
self.set_holdings(contract, 0.05)
Example 2: Supply-Demand Pressure Of Universe
This example shows how to handle QuoteBar data for shortlisted Index Option contracts to calculate mid-price using bid close and ask close data, while request data through universe selection function using SetFilterset_filter method for the contracts that expire within the current week. Using mid-price, we can examine the market fair value of the Option and compare it with the model theoretical price.
public class IndexOptionHandlingDataAlgorithm : QCAlgorithm
{
private Symbol _symbol;
public override void Initialize()
{
SetStartDate(2024, 9, 1);
SetEndDate(2024, 9, 15);
SetCash(100000000);
// Subscribe to SPXW option data.
var option = AddIndexOption("SPX", "SPXW");
_symbol = option.Symbol;
// We wish only to trade the contracts expiring within the same week since they have the highest volume.
option.SetFilter(u => u.Contracts(x => x.Where(s => s.ID.Date <= Expiry.EndOfWeek(Time))));
}
public override void OnData(Slice slice)
{
// Only want to obtain the option chain of the selected symbol.
if (slice.OptionChains.TryGetValue(_symbol, out var chain))
{
// Select the ATM call to trade.
var contract = chain.Where(x => x.Right == OptionRight.Call)
.MinBy(x => Math.Abs(x.UnderlyingLastPrice - x.Strike));
// If the last trading price is close to the asking price, the selling pressure is higher, so we are short.
var diff = contract.AskPrice - 2m * contract.LastPrice + contract.BidPrice;
if (diff < 0)
{
SetHoldings(contract, 0.05m);
}
else
{
SetHoldings(contract, -0.05m);
}
}
}
} class IndexOptionHandlingDataAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_start_date(2024, 9, 1)
self.set_end_date(2024, 9, 15)
self.set_cash(100000000)
# Subscribe to SPXW option data.
option = self.add_index_option("SPX", "SPXW")
self._symbol = option.symbol
# We wish only to trade the contracts expiring within the same week since they have the highest volume.
option.set_filter(lambda u: u.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
# Select the ATM call to trade.
contract = sorted(
[x for x in chain if x.right == OptionRight.CALL],
key=lambda x: abs(x.underlying_last_price - x.strike)
)[0]
# If the last trading price is close to the asking price, the selling pressure is higher, so we are short.
diff = contract.ask_price - 2 * contract.last_price + contract.bid_price
if diff < 0:
self.set_holdings(contract, -0.05)
else:
self.set_holdings(contract, 0.05)
Example 3: Get Instant Delta
The option Greeks change rapidly, so we need to obtain the instant Greeks to calculate the hedge size for arbitration or replication portfolio accurately. You can call the Greeks property from the OptionChain data to access various Greeks. In this example, we will demonstrate how to obtain a contract with a Delta closest to 0.4 among all call contracts expiring the same week.
public class IndexOptionHandlingDataAlgorithm : QCAlgorithm
{
private Symbol _symbol;
public override void Initialize()
{
SetStartDate(2024, 9, 1);
SetEndDate(2024, 12, 31);
// Subscribe to SPXW option data.
var option = AddIndexOption("SPX", "SPXW");
_symbol = option.Symbol;
// We wish only to trade the contracts expiring within the same week since they have the highest volume.
// 0.4 Delta will only appear in call contracts.
option.SetFilter(u => u.Delta(0.2m, 0.6m).Contracts((x) => x.Where(s => s.ID.Date <= Expiry.EndOfWeek(Time))));
}
public override void OnData(Slice slice)
{
// Only want to obtain the option chain of the selected symbol.
if (slice.OptionChains.TryGetValue(_symbol, out var chain) && !Portfolio.Invested)
{
// Get the contract with Delta closest to 0.4 to trade.
// The arbitrary delta criterion might be set due to hedging need or risk adjustment.
var selected = chain.OrderBy(x => Math.Abs(x.Greeks.Delta - 0.4m)).First();
// Hold a naked call on the selected contract to speculate an uprise of the SPX index with leverage.
MarketOrder(selected.Symbol, 1);
}
}
} class IndexOptionHandlingDataAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_start_date(2024, 9, 1)
self.set_end_date(2024, 12, 31)
# Subscribe to SPXW option data.
option = self.add_index_option("SPX", "SPXW")
self._symbol = option.symbol
# We wish only to 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.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 or self.portfolio.invested:
return
# Get the contract with Delta closest to 0.4 to trade.
# The arbitrary 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]
# Hold a naked call on the selected contract to speculate an uprise of the SPX index with leverage.
self.market_order(selected.symbol, 1)