Universe Selection
Options Universes
Options Universe Selection
The OptionUniverseSelectionModel
selects all the available contracts for the Equity Options, Index Options, and Future Options you specify. To use this model, provide a refreshInterval
and a selector function. The refreshInterval
defines how frequently LEAN calls the selector function. The selector function receives a
DateTime
datetime
object that represents the current Coordinated Universal Time (UTC) and returns a list of Symbol
objects. The Symbol
objects you return from the selector function are the Options of the universe.
AddUniverseSelection(new OptionUniverseSelectionModel(refreshInterval, optionChainSymbolSelector));
from Selection.OptionUniverseSelectionModel import OptionUniverseSelectionModel self.AddUniverseSelection(OptionUniverseSelectionModel(refreshInterval, optionChainSymbolSelector))
The following table describes the arguments the model accepts:
Argument | Data Type | Description | Default Value |
---|---|---|---|
refreshInterval | TimeSpan timedelta | Time interval between universe refreshes | |
optionChainSymbolSelector | Func<DateTime, IEnumerable<Symbol>> Callable[[datetime], List[Symbol]] | A function that selects the Option symbols | |
universeSettings | UniverseSettings | Universe settings define attributes of created subscriptions, such as their resolution and the minimum time in universe before they can be removed | null None |
If you don't provide a universeSettings
argument, the algorithm.UniverseSettings
is used by default.
public override void Initialize() { AddUniverseSelection( new OptionUniverseSelectionModel(TimeSpan.FromDays(1), SelectOptionChainSymbols) ); } private IEnumerable<Symbol> SelectOptionChainSymbols(DateTime utcTime) { // Equity Options example: //var tickers = new[] {"SPY", "QQQ", "TLT"}; //return tickers.Select(ticker => QuantConnect.Symbol.Create(ticker, SecurityType.Option, Market.USA)); // Index Options example: //var tickers = new[] {"VIX", "SPX"}; //return tickers.Select(ticker => QuantConnect.Symbol.Create(ticker, SecurityType.IndexOption, Market.USA)); // Future Options example: var futureSymbol = QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME); var futureContractSymbols = FutureChainProvider.GetFutureContractList(futureSymbol, Time); foreach (var symbol in futureContractSymbols) { yield return QuantConnect.Symbol.CreateCanonicalOption(symbol); } }
from Selection.OptionUniverseSelectionModel import OptionUniverseSelectionModel def Initialize(self) -> None: universe = OptionUniverseSelectionModel(timedelta(days=1), self.select_option_chain_symbols) self.SetUniverseSelection(universe) def select_option_chain_symbols(self, utc_time: datetime) -> List[Symbol]: # Equity Options example: #tickers = ["SPY", "QQQ", "TLT"] #return [Symbol.Create(ticker, SecurityType.Option, Market.USA) for ticker in tickers] # Index Options example: #tickers = ["VIX", "SPX"] #return [Symbol.Create(ticker, SecurityType.IndexOption, Market.USA) for ticker in tickers] # Future Options example: future_symbol = Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME) future_contract_symbols = self.FutureChainProvider.GetFutureContractList(future_symbol, self.Time) return [Symbol.CreateCanonicalOption(symbol) for symbol in future_contract_symbols]
This model uses the default Option filter, which selects all of the available Option contracts at the current time step. To use a different filter for the contracts, subclass the OptionUniverseSelectionModel
and define a Filter
method. The Filter
method accepts and returns an OptionFilterUniverse
object to select the Option contracts. The following table describes the methods of the OptionFilterUniverse
class:
Method | Description |
---|---|
Strikes(int minStrike, int maxStrike) Strikes(minStrike: int, maxStrike: int) | Selects contracts that are within minStrike strikes below the underlying price and maxStrike strikes above the underlying price |
CallsOnly() | Selects call contracts |
PutsOnly() | Selects put contracts |
StandardsOnly() | Selects standard contracts |
IncludeWeeklys() | Selects non-standard weeklys contracts |
WeeklysOnly() | Selects weekly contracts |
FrontMonth() | Selects the front month contract |
BackMonths() | Selects the non-front month contracts |
BackMonth() | Selects the back month contracts |
Expiration(TimeSpan minExpiry, TimeSpan maxExpiry) Expiration(minExpiry: timedelta, maxExpiry: timedelta) | Selects contracts that expire within a range of dates relative to the current day |
Expiration(int minExpiryDays, int maxExpiryDays) Expiration(minExpiryDays: int, maxExpiryDays: int) | Selects contracts that expire within a range of dates relative to the current day |
Contracts(IEnumerable<Symbol> contracts) Contracts(contracts: List[Symbol]) | Selects a list of contracts |
Contracts(Func<IEnumerable<Symbol>, IEnumerable< Symbol>> contractSelector) Contracts(contractSelector: Callable[[List[Symbol]], List[Symbol]]) | Selects contracts that a selector function selects |
OnlyApplyFilterAtMarketOpen() | Instructs the engine to only filter contracts on the first time step of each market day |
Depending on how you define the contract filter, LEAN may call it once a day or at every time step.
To move the selection functions outside of the algorithm class, create a universe selection model that inherits the OptionUniverseSelectionModel
class.
// In Initialize AddUniverseSelection(new EarliestExpiringAtTheMoneyCallOptionUniverseSelectionModel(this)); // Outside of the algorithm class class EarliestExpiringAtTheMoneyCallOptionUniverseSelectionModel : OptionUniverseSelectionModel { public EarliestExpiringAtTheMoneyCallOptionUniverseSelectionModel(QCAlgorithm algorithm) : base(TimeSpan.FromDays(1), utcTime => SelectOptionChainSymbols(algorithm, utcTime)) {} private static IEnumerable<Symbol> SelectOptionChainSymbols(QCAlgorithm algorithm, DateTime utcTime) { // Equity Options example: //var tickers = new[] {"SPY", "QQQ", "TLT"}; //return tickers.Select(ticker => QuantConnect.Symbol.Create(ticker, SecurityType.Option, Market.USA)); // Index Options example: //var tickers = new[] {"VIX", "SPX"}; //return tickers.Select(ticker => QuantConnect.Symbol.Create(ticker, SecurityType.IndexOption, Market.USA)); // Future Options example: var futureSymbol = QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME); var futureContractSymbols = algorithm.FutureChainProvider.GetFutureContractList(futureSymbol, algorithm.Time); foreach (var symbol in futureContractSymbols) { yield return QuantConnect.Symbol.CreateCanonicalOption(symbol); } } protected override OptionFilterUniverse Filter(OptionFilterUniverse filter) { return filter.Strikes(-1, -1).Expiration(0, 7).CallsOnly().OnlyApplyFilterAtMarketOpen(); } }
from Selection.OptionUniverseSelectionModel import OptionUniverseSelectionModel # In Initialize self.AddUniverseSelection(EarliestExpiringAtTheMoneyCallOptionUniverseSelectionModel(self)) # Outside of the algorithm class class EarliestExpiringAtTheMoneyCallOptionUniverseSelectionModel(OptionUniverseSelectionModel): def __init__(self, algorithm): self.algo = algorithm super().__init__(timedelta(1), self.select_option_chain_symbols) def select_option_chain_symbols(self, utc_time: datetime) -> List[Symbol]: # Equity Options example: #tickers = ["SPY", "QQQ", "TLT"] #return [Symbol.Create(ticker, SecurityType.Option, Market.USA) for ticker in tickers] # Index Options example: #tickers = ["VIX", "SPX"] #return [Symbol.Create(ticker, SecurityType.IndexOption, Market.USA) for ticker in tickers] # Future Options example: future_symbol = Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME) future_contract_symbols = self.algo.FutureChainProvider.GetFutureContractList(future_symbol, self.algo.Time) return [Symbol.CreateCanonicalOption(symbol) for symbol in future_contract_symbols] def Filter(self, option_filter_universe: OptionFilterUniverse) -> OptionFilterUniverse: return option_filter_universe.Strikes(-1, -1).Expiration(0, 7).CallsOnly().OnlyApplyFilterAtMarketOpen()
Some of the preceding filter methods only set an internal enumeration in the OptionFilterUniverse
that it uses later on in the filter process. This subset of filter methods don't immediately reduce the number of contract Symbol
objects in the OptionFilterUniverse
.
To override the default pricing model of the Options, set a pricing model in a security initializer.
To override the initial guess of implied volatility, set and warm up the underlying volatility model.
To view the implementation of this model, see the LEAN GitHub repositoryLEAN GitHub repository.
Option Chained Universe Selection
An Option chained universe subscribes to Option contracts on the constituents of a US Equity universe.
AddUniverseOptions(universe, optionFilter);
self.AddUniverseOptions(universe, optionFilter)
The following table describes the arguments the model accepts:
Argument | Data Type | Description | Default Value |
---|---|---|---|
universe | Universe | The universe to chain onto the Option Universe Selection model | |
optionFilter | Func<OptionFilterUniverse, OptionFilterUniverse> Callable[[OptionFilterUniverse], OptionFilterUniverse] | The Option filter universe to use |
The optionFilter
function receives and returns an OptionFilterUniverse
to select the Option contracts. The following table describes the methods of the OptionFilterUniverse
class:
Method | Description |
---|---|
Strikes(int minStrike, int maxStrike) Strikes(minStrike: int, maxStrike: int) | Selects contracts that are within minStrike strikes below the underlying price and maxStrike strikes above the underlying price |
CallsOnly() | Selects call contracts |
PutsOnly() | Selects put contracts |
StandardsOnly() | Selects standard contracts |
IncludeWeeklys() | Selects non-standard weeklys contracts |
WeeklysOnly() | Selects weekly contracts |
FrontMonth() | Selects the front month contract |
BackMonths() | Selects the non-front month contracts |
BackMonth() | Selects the back month contracts |
Expiration(TimeSpan minExpiry, TimeSpan maxExpiry) Expiration(minExpiry: timedelta, maxExpiry: timedelta) | Selects contracts that expire within a range of dates relative to the current day |
Expiration(int minExpiryDays, int maxExpiryDays) Expiration(minExpiryDays: int, maxExpiryDays: int) | Selects contracts that expire within a range of dates relative to the current day |
Contracts(IEnumerable<Symbol> contracts) Contracts(contracts: List[Symbol]) | Selects a list of contracts |
Contracts(Func<IEnumerable<Symbol>, IEnumerable< Symbol>> contractSelector) Contracts(contractSelector: Callable[[List[Symbol]], List[Symbol]]) | Selects contracts that a selector function selects |
OnlyApplyFilterAtMarketOpen() | Instructs the engine to only filter contracts on the first time step of each market day |
public override void Initialize() { var universe = AddUniverse(Universe.DollarVolume.Top(10)); AddUniverseOptions(universe, OptionFilterFunction); } private OptionFilterUniverse OptionFilterFunction(OptionFilterUniverse optionFilterUniverse) { return optionFilterUniverse.Strikes(-2, +2).FrontMonth().CallsOnly(); }
def Initialize(self) -> None: universe = self.AddUniverse(self.Universe.DollarVolume.Top(10)) self.AddUniverseOptions(universe, self.OptionFilterFunction) def OptionFilterFunction(self, option_filter_universe: OptionFilterUniverse) -> OptionFilterUniverse: return option_filter_universe.Strikes(-2, +2).FrontMonth().CallsOnly()
Some of the preceding filter methods only set an internal enumeration in the OptionFilterUniverse
that it uses later on in the filter process. This subset of filter methods don't immediately reduce the number of contract Symbol
objects in the OptionFilterUniverse
.
To override the default pricing model of the Options, set a pricing model in a security initializer.
To override the initial guess of implied volatility, set and warm up the underlying volatility model.
To view the implementation of this model, see the LEAN GitHub repository.