Future 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 Futures Option contract ticker or Symbolsymbol, but we recommend you use the Symbolsymbol.
To view the resolutions that are available for Future 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 Option contract Symbolsymbol. If the Option contract doesn't actively trade or you are in the same time step as when you added the Option contract subscription, the Slice may not contain data for your Symbolsymbol. To avoid issues, check if the Slice contains data for your Option contract before you index the Slice with the Option contract Symbolsymbol.
public override void OnData(Slice slice)
{
// Check if the symbol is contained in TradeBars object
if (slice.Bars.ContainsKey(_optionContractSymbol))
{
// Obtain the mapped TradeBar of the symbol
var tradeBar = slice.Bars[_optionContractSymbol];
}
}
def on_data(self, slice: Slice) -> None:
# Obtain the mapped TradeBar of the symbol if any
trade_bar = slice.bars.get(self._option_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 Option contract Symbolsymbol. If the Option contract doesn't actively get quotes or you are in the same time step as when you added the Option contract subscription, the Slice may not contain data for your Symbolsymbol. To avoid issues, check if the Slice contains data for your Option contract before you index the Slice with the Option contract Symbolsymbol.
public override void OnData(Slice slice)
{
// Check if the symbol is contained in QuoteBars object
if (slice.QuoteBars.ContainsKey(_optionContractSymbol))
{
// Obtain the mapped QuoteBar of the symbol
var quoteBar = slice.QuoteBars[_optionContractSymbol];
}
}
def on_data(self, slice: Slice) -> None:
# Obtain the mapped QuoteBar of the symbol if any
quote_bar = slice.quote_bars.get(self._option_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:
Futures Chains
FuturesChain objects represent an entire chain of contracts for a single underlying Future.
To get the FuturesChain, index the FuturesChainsfutures_chains property of the Slice with the continuous contract Symbol.
public override void OnData(Slice slice)
{
// Try to get the FutureChain using the canonical symbol
if (slice.FuturesChains.TryGetValue(_futureContractSymbol.Canonical, out var chain))
{
// Get all contracts if the FutureChain contains any member
var contracts = chain.Contracts;
}
}
def on_data(self, slice: Slice) -> None:
# Try to get the FutureChain using the canonical symbol (None if no FutureChain return)
chain = slice.futures_chains.get(self._future_contract_symbol.canonical)
if chain:
# Get all contracts if the FutureChain contains any member
contracts = chain.contracts
You can also loop through the FuturesChainsfutures_chains property to get each FuturesChain.
public override void OnData(Slice slice)
{
// Iterate all received Canonical Symbol-FutureChain key-value pairs
foreach (var kvp in slice.FuturesChains)
{
var continuousContractSymbol = kvp.Key;
var chain = kvp.Value;
var contracts = chain.Contracts;
}
}
// Using this overload will only handle any FutureChains object received
public void OnData(FuturesChains futuresChains)
{
// Iterate all received Canonical Symbol-FutureChain key-value pairs
foreach (var kvp in futuresChains)
{
var continuousContractSymbol = kvp.Key;
var chain = kvp.Value;
var contracts = chain.Contracts;
}
} def on_data(self, slice: Slice) -> None:
# Iterate all received Canonical Symbol-FutureChain key-value pairs
for continuous_contract_symbol, chain in slice.futures_chains.items():
contracts = chain.contracts
FuturesChain objects have the following properties:
Futures Contracts
FuturesContract objects represent the data of a single Futures contract in the market.
To get the Futures contracts in the Slice, use the Contractscontracts property of the FuturesChain.
public override void OnData(Slice slice)
{
// Try to get the FutureChain using the canonical symbol
if (slice.FuturesChains.TryGetValue(_futureContractSymbol.Canonical, out var chain))
{
// Get individual contract data
if (chain.Contracts.TryGetValue(_futureContractSymbol, out var contract))
{
var price = contract.LastPrice;
}
}
}
// // Using this overload will only handle any FutureChains object received
public void OnData(FuturesChains futuresChains)
{
// Try to get the FutureChain using the canonical symbol
if (futuresChains.TryGetValue(_futureContractSymbol.Canonical, out var chain))
{
// Get individual contract data
if (chain.Contracts.TryGetValue(_futureContractSymbol, out var contract))
{
var price = contract.LastPrice;
}
}
} def on_data(self, slice: Slice) -> None:
# Try to get the FutureChain using the canonical symbol
chain = slice.future_chains.get(self._future_contract_symbol.canonical)
if chain:
# Get individual contract data (None if not contained)
contract = chain.contracts.get(self._future_contract_symbol)
if contract:
price = contract.last_price
FuturesContract 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(_optionContractSymbol.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._option_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 canonicalFOPSymbol = 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_fop_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 Contractscontracts property of the OptionChain.
public override void OnData(Slice slice)
{
// Try to get the OptionChain using the canonical symbol
if (slice.OptionChains.TryGetValue(_optionContractSymbol.Canonical, out var chain))
{
// Get individual contract data
if (chain.Contracts.TryGetValue(_optionContractSymbol, 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._option_contract_symbol.canonical)
if chain:
# Get individual contract data
contract = chain.contracts.get(self._option_contract_symbol)
if contract:
price = contract.price
You can also iterate through the FuturesChainsfutures_chains first.
public override void OnData(Slice slice)
{
// Iterate all received Canonical Symbol-FuturesChain key-value pairs
foreach (var kvp in slice.FuturesChains)
{
var continuousContractSymbol = kvp.Key;
var futuresChain = kvp.Value;
// Select a Future Contract and create its canonical FOP Symbol
var futuresContract = futuresChain.First();
var canonicalFOPSymbol = QuantConnect.Symbol.CreateCanonicalOption(futuresContract.Symbol);
// Try to get the OptionChain using the canonical FOP symbol
if (slice.OptionChains.TryGetValue(canonicalFOPSymbol, out var optionChain))
{
// Get individual contract data
if (optionChain.Contracts.TryGetValue(_optionContractSymbol, out var optionContract))
{
var price = optionContract.Price;
}
}
}
} def on_data(self, slice: Slice) -> None:
# Iterate all received Canonical Symbol-FuturesChain key-value pairs
for continuous_future_symbol, futures_chain in slice.futures_chains.items():
# Select a Future Contract and create its canonical FOP Symbol
futures_contract = [contract for contract in futures_chain][0]
canonical_fop_symbol = Symbol.create_canonical_option(futures_contract.symbol)
# Try to get the OptionChain using the canonical FOP symbol
option_chain = slice.option_chains.get(canonical_fop_symbol)
if option_chain:
# Get individual contract data
option_contract = option_chain.contracts.get(self._option_contract_symbol)
if option_contract:
price = option_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(_optionContractSymbol.Canonical, out var chain))
{
// Get individual contract data
if (chain.Contracts.TryGetValue(_optionContractSymbol, 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._option_contract_symbol.canonical)
if chain:
# Get individual contract data
contract = chain.contracts.get(self._option_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 Future Option data.
Example 1: Monthly Protective Put
The following algorithm shows how to perform monthly selection on individual ES Future Option contract to implement a protective put option strategy to hedge speculation on S&P500 Future. It is a useful tool to hedge the excessive risk on leverage using Futures to trade.
public class FutureOptionExampleAlgorithm : QCAlgorithm
{
private Future _underlying;
public override void Initialize()
{
SetStartDate(2024, 9, 1);
SetEndDate(2024, 12, 31);
SetCash(1000000000);
// Seed the security price to ensure the underlying price is available at the initial filtering.
SetSecurityInitializer(new BrokerageModelSecurityInitializer(BrokerageModel, new FuncSecuritySeeder(GetLastKnownPrices)));
// Set data normalization mode to raw for fair strike price comparison.
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
// Subscribe the underlying since the updated price is needed for filtering.
_underlying = AddFuture(Futures.Indices.SP500EMini,
dataMappingMode: DataMappingMode.OpenInterest,
dataNormalizationMode: DataNormalizationMode.Raw,
contractDepthOffset: 0);
// Filter the underlying continuous Futures to narrow the FOP spectrum.
_underlying.SetFilter(0, 31);
// Schedule a monthly event on selection of future-future option pair, since the portfolio rebalance on a monthly basis.
Schedule.On(
DateRules.MonthStart(_underlying.Symbol),
TimeRules.AfterMarketOpen(_underlying.Symbol, 0),
SelectionAndRebalance
);
}
private void SelectionAndRebalance()
{
// Get all available put FOP contract for the mapped underlying contract, since the trade liquidity and volatility is the highest.
var contractSymbols = OptionChain(_underlying.Mapped)
.Where(symbol => symbol.ID.OptionRight == OptionRight.Put)
.ToList();
// Select the ATM put expires the same date as the underlying. The max expiry of the FOP will expire the same time as the front month future.
var expiry = contractSymbols.Max(symbol => symbol.ID.Date);
var selected = contractSymbols.Where(symbol => symbol.ID.Date == expiry)
.OrderBy(symbol => Math.Abs(symbol.ID.StrikePrice - Securities[_underlying.Mapped].Price))
.First();
// Request the FOP contract data for trading.
var contract = AddFutureOptionContract(selected);
// A Protective Put consists of long a lot of the underlying, and long a put contract.
MarketOrder(_underlying.Mapped, contract.SymbolProperties.ContractMultiplier);
MarketOrder(contract.Symbol, 1);
}
} class FutureOptionExampleAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_start_date(2024, 9, 1)
self.set_end_date(2024, 12, 31)
self.set_cash(1000000000)
# Seed the security price to ensure the underlying price is available at the initial filtering.
self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices)))
# Set data normalization mode to raw for fair strike price comparison.
self.universe_settings.data_normalization_mode = DataNormalizationMode.RAW
# Subscribe the underlying since the updated price is needed for filtering.
self.underlying = self.add_future(Futures.Indices.SP_500_E_MINI,
data_mapping_mode=DataMappingMode.OPEN_INTEREST,
data_normalization_mode=DataNormalizationMode.RAW,
contract_depth_offset=0)
# Filter the underlying continuous Futures to narrow the FOP spectrum.
self.underlying.set_filter(0, 31)
# Schedule a monthly event on selection of future-future option pair, since the portfolio rebalance on a monthly basis.
self.schedule.on(
self.date_rules.month_start(self.underlying.symbol),
self.time_rules.after_market_open(self.underlying.symbol, 0),
self.selection_and_rebalance
)
def selection_and_rebalance(self) -> None:
# Get all available put FOP contract for the mapped underlying contract, since the trade liquidity and volatility is the highest.
contract_symbols = self.option_chain(self.underlying.mapped)
contract_symbols = [symbol for symbol in contract_symbols if symbol.id.option_right == OptionRight.PUT]
# Select the ATM put expires the same date as the underlying. The max expiry of the FOP will expire the same time as the front month future.
expiry = max(symbol.id.date for symbol in contract_symbols)
filtered_symbols = [symbol for symbol in contract_symbols if symbol.id.date == expiry]
selected = sorted(filtered_symbols, key=lambda symbol: abs(symbol.id.strike_price - self.securities[self.underlying.mapped].price))[0]
# Request the FOP contract data for trading.
contract = self.add_future_option_contract(selected)
# A Protective Put consists of long a lot of the underlying, and long a put contract.
self.market_order(self.underlying.mapped, contract.symbol_properties.contract_multiplier)
self.market_order(contract.symbol, 1)
Example 2: Weekly Covered Call
The below example demonstrates a weekly-renewing
covered call
strategy to collect credit of selling the option. It filters the ATM call contract that expires within the current week at week start using
SetFilter
set_filter
filtering function.
public class FutureOptionExampleAlgorithm : QCAlgorithm
{
private Future _underlying;
public override void Initialize()
{
SetStartDate(2024, 9, 1);
SetEndDate(2024, 12, 31);
SetCash(1000000000);
// Set data normalization mode to raw for fair strike price comparison.
UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
// Subscribe the underlying since the updated price is needed for filtering.
_underlying = AddFuture(Futures.Indices.SP500EMini,
extendedMarketHours: true,
dataMappingMode: DataMappingMode.OpenInterest,
dataNormalizationMode: DataNormalizationMode.Raw,
contractDepthOffset: 0);
// Filter the underlying continuous Futures to narrow the FOP spectrum.
_underlying.SetFilter(0, 182);
// Filter for the current-week-expiring calls to formulate a covered call that expires at the end of week.
AddFutureOption(_underlying.Symbol, (u) => u.IncludeWeeklys().CallsOnly().Expiration(0, 5));
}
public override void OnData(Slice slice)
{
// Create canonical symbol for the mapped future contract, since option chains are mapped by canonical symbol.
var symbol = QuantConnect.Symbol.CreateCanonicalOption(_underlying.Mapped);
// Get option chain data for the mapped future, as both the underlying and FOP have the highest liquidity among all other contracts.
if (!Portfolio.Invested &&
slice.OptionChains.TryGetValue(symbol, out var chain))
{
// Obtain the ATM call that expires at the end of week, such that both underlying and the FOP expires the same time.
var expiry = chain.Max(x => x.Expiry);
var atmCall = chain.Where(x => x.Expiry == expiry)
.OrderBy(x => Math.Abs(x.Strike - x.UnderlyingLastPrice))
.First();
// Use abstraction method to order a covered call to avoid manual error.
var optionStrategy = OptionStrategies.CoveredCall(symbol, atmCall.Strike, expiry);
Buy(optionStrategy, 1);
}
}
} class FutureOptionExampleAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_start_date(2024, 9, 1)
self.set_end_date(2024, 12, 31)
self.set_cash(1000000000)
# Set data normalization mode to raw for fair strike price comparison.
self.universe_settings.data_normalization_mode = DataNormalizationMode.RAW
# Subscribe the underlying since the updated price is needed for filtering.
self.underlying = self.add_future(Futures.Indices.SP_500_E_MINI,
extended_market_hours=True,
data_mapping_mode=DataMappingMode.OPEN_INTEREST,
data_normalization_mode=DataNormalizationMode.RAW,
contract_depth_offset=0)
# Filter the underlying continuous Futures to narrow the FOP spectrum.
self.underlying.set_filter(0, 182)
# Filter for the current-week-expiring calls to formulate a covered call that expires at the end of week.
self.add_future_option(self.underlying.symbol, lambda u: u.include_weeklys().calls_only().expiration(0, 5))
def on_data(self, slice: Slice) -> None:
# Create canonical symbol for the mapped future contract, since option chains are mapped by canonical symbol.
symbol = Symbol.create_canonical_option(self.underlying.mapped)
# Get option chain data for the mapped future, as both the underlying and FOP have the highest liquidity among all other contracts.
chain = slice.option_chains.get(symbol)
if not self.portfolio.invested and chain:
# Obtain the ATM call that expires at the end of week, such that both underlying and the FOP expires the same time.
expiry = max(x.expiry for x in chain)
atm_call = sorted([x for x in chain if x.expiry == expiry],
key=lambda x: abs(x.strike - x.underlying_last_price))[0]
# Use abstraction method to order a covered call to avoid manual error.
option_strategy = OptionStrategies.covered_call(symbol, atm_call.strike,expiry)
self.buy(option_strategy, 1)
Note that since both the underlying Future and the Future Option are expiring on the same day and are cash-settling in most cases, Lean can exercise the Future Option into account cash automatically at expiry and we do not need to handle the option exercise/assignment event.