Universe Selection

Futures Universes

Introduction

A Future Universe Selection model selects contracts for a set of Futures.

Future Universe Selection

The FutureUniverseSelectionModel selects all the contracts for a set of Futures you specify. To use this model, provide a refreshIntervalrefresh_interval and a selector function. The refreshIntervalrefresh_interval defines how frequently LEAN calls the selector function. The selector function receives a DateTimedatetime 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 Futures of the universe.

// Run universe selection asynchronously to speed up your algorithm. This means you cannot rely on method or algorithm state between filter calls.
UniverseSettings.Asynchronous = true;
// Select E-mini S&P 500 symbol for the future universe.
AddUniverseSelection(
    new FutureUniverseSelectionModel(
	// Refresh the universe daily.
        TimeSpan.FromDays(1), 
        _ => new List<Symbol> {{ QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME) }}
    )
);
from Selection.FutureUniverseSelectionModel import FutureUniverseSelectionModel
# Run universe selection asynchronously to speed up your algorithm. This means you cannot rely on method or algorithm state between filter calls.
self.universe_settings.asynchronous = True
# Select E-mini S&P 500 symbol for the future universe.
self.add_universe_selection(
    FutureUniverseSelectionModel(
	# Refresh the universe daily.
        timedelta(1), 
        lambda _: [Symbol.create(Futures.Indices.SP500E_MINI, SecurityType.FUTURE, Market.CME)]
    )
)

The following table describes the arguments the model accepts:

ArgumentData TypeDescriptionDefault Value
refreshIntervalrefresh_intervalTimeSpantimedeltaTime interval between universe refreshes
futureChainSymbolSelectorfuture_chain_symbol_selectorFunc<DateTime, IEnumerable<Symbol>>Callable[[datetime], List[Symbol]]A function that selects the Future symbols for a given Coordinated Universal Time (UTC). To view the supported assets in the US Futures dataset, see Supported Assets.
universeSettingsuniverse_settingsUniverseSettingsThe universe settings. If you don't provide an argument, the model uses the algorithm.UniverseSettingsalgorithm.universe_settings by default.nullNone

The following example shows how to define the Future chain Symbol selector as an isolated method:

// Initialize, configure FutureUniverseSelectionModel with a custom function to selectively choose E-mini S&P 500 and Gold futures, enabling precise trading focus.

public override void Initialize()
{
    // Select future symbols using custom selector function.
    AddUniverseSelection(
        new FutureUniverseSelectionModel(TimeSpan.FromDays(1), SelectFutureChainSymbols)
    );
}

private static IEnumerable<Symbol> SelectFutureChainSymbols(DateTime utcTime)
{
    // Select E-mini S&P 500 and Gold symbols for the future universe. 
    return new[] {
        QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME),
        QuantConnect.Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.COMEX)
    };
}
# Initialize, configure FutureUniverseSelectionModel with a custom function to selectively choose E-mini S&P 500 and Gold futures, enabling precise trading focus.
from Selection.FutureUniverseSelectionModel import FutureUniverseSelectionModel

def initialize(self) -> None:
    # Select future symbols using custom selector function.
    self.set_universe_selection(
        FutureUniverseSelectionModel(timedelta(days=1), self.select_future_chain_symbols)
    )

def select_future_chain_symbols(self, utc_time: datetime) -> List[Symbol]:
    # Select E-mini S&P 500 and Gold symbols for the future universe.
    return [ 
        Symbol.create(Futures.Indices.SP500E_MINI, SecurityType.FUTURE, Market.CME),
        Symbol.create(Futures.Metals.GOLD, SecurityType.FUTURE, Market.COMEX)
    ]

This model uses the default Future contract filter, which doesn't select any Futures contracts. To use a different filter, subclass the FutureUniverseSelectionModel and define a Filterfilter method. The Filterfilter method accepts and returns a FutureFilterUniverse object to select the Futures contracts. The following table describes the filter methods of the FutureFilterUniverse class:

StandardsOnly()standards_only()

Selects standard contracts

IncludeWeeklys()include_weeklys()

Selects non-standard weekly contracts

WeeklysOnly()weeklys_only()

Selects weekly contracts

FrontMonth()front_month()

Selects the front month contract

BackMonths()back_months()

Selects the non-front month contracts

BackMonth()back_month()

Selects the back month contracts

Expiration(TimeSpan minExpiry, TimeSpan maxExpiry)expiration(min_expiry: timedelta, max_expiry: timedelta)

Selects contracts that expire within a range of dates relative to the current day

Expiration(int minExpiryDays, int maxExpiryDays)expiration(min_expiry_days: int, max_expiry_days: 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

The contract filter runs at the first time step of each day.

To move the Future chain Symbol selector and the contract selection function outside of the algorithm class, create a universe selection model that inherits the FundamentalUniverseSelectionModel class and override its Select method.

// Setup algorithm settings and request data in initialize.
UniverseSettings.Asynchronous = true;
AddUniverseSelection(new FrontMonthFutureUniverseSelectionModel());

// Outside of the algorithm class
class FrontMonthFutureUniverseSelectionModel : FutureUniverseSelectionModel
{
    public FrontMonthFutureUniverseSelectionModel()
	// Refresh the universe daily.
        : base(TimeSpan.FromDays(1), SelectFutureChainSymbols) {}

    private static IEnumerable<Symbol> SelectFutureChainSymbols(DateTime utcTime)
    {
	// Select E-mini S&P 500 and Gold symbols for the future universe.
        return new List<Symbol> {
            QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME),
            QuantConnect.Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.COMEX)
        };
    }

    protected override FutureFilterUniverse Filter(FutureFilterUniverse filter)
    {
	// Apply universe filter to return front month contracts.
        return filter.FrontMonth();
    }
}
# Setup algorithm settings and request data in initialize.
self.universe_settings.asynchronous = True
self.add_universe_selection(FrontMonthFutureUniverseSelectionModel())

# Outside of the algorithm class
class FrontMonthFutureUniverseSelectionModel(FutureUniverseSelectionModel):
    def __init__(self) -> None:
	# Refresh the universe daily.
        super().__init__(timedelta(1), self.select_future_chain_symbols)

    def select_future_chain_symbols(self, utc_time: datetime) -> List[Symbol]:
	# Select E-mini S&P 500 and Gold symbols for the future universe.
        return [ 
            Symbol.create(Futures.Indices.SP500E_MINI, SecurityType.FUTURE, Market.CME),
            Symbol.create(Futures.Metals.GOLD, SecurityType.FUTURE, Market.COMEX) 
        ]

    def filter(self, filter: FutureFilterUniverse) -> FutureFilterUniverse:
	# Apply universe filter to return front month contracts.
        return filter.front_month()

Some of the preceding filter methods only set an internal enumeration in the FutureFilterUniverse 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 FutureFilterUniverse.

The AddUniverseSelection method doesn't return a Future object like the AddFuture method. The Future object contains Symbol and Mappedmapped properties, which reference the continuous contract and the currently selected contract in the continuous contract series, respectively. To get the Future object, define the OnSecuritiesChangedon_securities_changed method in your algorithm class or framework models and check the result of the IsCanonical method.

// Return future objects if the added security in the universe is canonical.
public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
{
    foreach (var security in changes.AddedSecurities)
    {
        if (security.Symbol.IsCanonical() && security.Type == SecurityType.Future)
        {
            _future = security as Future;
        }
    }
}
# Return future objects if the added security in the universe is canonical.
def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None:
    for security in changes.added_securities:
        if security.Symbol.IsCanonical():
            self.future = security

To view the implementation of this model, see the LEAN GitHub repositoryLEAN GitHub repository.

Open Interest Future Universe Selection

The OpenInterestFutureUniverseSelectionModel is an extension of the FutureUniverseSelectionModel that selects the contract with the greatest open interest on a daily basis.

// Enable asynchronous universe settings for faster performance and use OpenInterestFutureUniverseSelectionModel with a custom function to select E-mini S&P 500 futures, incorporating contracts with high open interest into the trading universe.
UniverseSettings.Asynchronous = true;
AddUniverseSelection(
    new OpenInterestFutureUniverseSelectionModel(
        this, 
        utcTime => new[] { QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME) }
    )
);
# Enable asynchronous universe settings for faster performance and use OpenInterestFutureUniverseSelectionModel with a custom function to select E-mini S&P 500 futures, incorporating contracts with high open interest into the trading universe.
self.universe_settings.asynchronous = True
self.add_universe_selection(
    OpenInterestFutureUniverseSelectionModel(
        self, 
        lambda utc_time: [Symbol.create(Futures.Indices.SP500E_MINI, SecurityType.FUTURE, Market.CME)]
    )
)

The following table describes the arguments the model accepts:

ArgumentData TypeDescriptionDefault Value
algorithmIAlgorithmAlgorithm
futureChainSymbolSelectorfuture_chain_symbol_selector Func<DateTime, IEnumerable<Symbol>> Callable[[datetime], List[Symbol]]A function that selects the Future symbols for a given Coordinated Universal Time (UTC). To view the supported assets in the US Futures dataset, see Supported Assets.
chainContractsLookupLimitchain_contracts_lookup_limit int? int/NoneLimit on how many contracts to query for open interest6
resultsLimitresults_limit int? int/NoneLimit on how many contracts will be part of the universe1

The following example shows how to define the Future chain Symbol selector as an isolated method:

// Setup algorithm settings and request data in initialize.
public override void Initialize()
{
    UniverseSettings.Asynchronous = true;  
    AddUniverseSelection(
        new OpenInterestFutureUniverseSelectionModel(this, SelectFutureChainSymbols)
    );
}

// Create selection function which returns symbol objects.
private static IEnumerable<Symbol> SelectFutureChainSymbols(DateTime utcTime)
{
    return new[] {
        QuantConnect.Symbol.Create(Futures.Indices.SP500EMini, SecurityType.Future, Market.CME),
        QuantConnect.Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.COMEX)
    };
}

# Setup algorithm settings and request data in initialize.
def initialize(self) -> None:
    self.universe_settings.asynchronous = True
    self.add_universe_selection(
        OpenInterestFutureUniverseSelectionModel(self, self.select_future_chain_symbols)
    )

# Create selection function which returns symbol objects.
def select_future_chain_symbols(self, utc_time: datetime) -> List[Symbol]:
    return [ 
        Symbol.create(Futures.Indices.SP500E_MINI, SecurityType.FUTURE, Market.CME),
        Symbol.create(Futures.Metals.GOLD, SecurityType.FUTURE, Market.COMEX)
    ]

To move the Future chain Symbol selector outside of the algorithm class, create a universe selection model that inherits the OpenInterestFutureUniverseSelectionModel class.

// Setup algorithm settings and request data in initialize.
UniverseSettings.Asynchronous = true;
AddUniverseSelection(new GoldOpenInterestFutureUniverseSelectionModel(this));

// Outside of the algorithm class
class GoldOpenInterestFutureUniverseSelectionModel : OpenInterestFutureUniverseSelectionModel
{
    public GoldOpenInterestFutureUniverseSelectionModel(QCAlgorithm algorithm, 
        int? chainContractsLookupLimit = 6, int? resultsLimit = 1)
        : base(algorithm, SelectFutureChainSymbols, chainContractsLookupLimit, resultsLimit) {}

    private static IEnumerable<Symbol> SelectFutureChainSymbols(DateTime utcTime)
    {
        return new List<Symbol> { 
            QuantConnect.Symbol.Create(Futures.Metals.Gold, SecurityType.Future, Market.COMEX) 
        };
    }
}
# Create selection function which returns symbol objects.
self.universe_settings.asynchronous = True
self.add_universe_selection(GoldOpenInterestFutureUniverseSelectionModel(self))
    
# Outside of the algorithm class
class GoldOpenInterestFutureUniverseSelectionModel(OpenInterestFutureUniverseSelectionModel):
    def __init__(self, algorithm: QCAlgorithm, chain_contracts_lookup_limit: int = 6, results_limit: int = 1):
        super().__init__(algorithm, self.select_future_chain_symbols, chain_contracts_lookup_limit, results_limit)

    def select_future_chain_symbols(self, utcTime: datetime) -> List[Symbol]:
        return [Symbol.Create(Futures.Metals.GOLD, SecurityType.FUTURE, Market.COMEX)]

The AddUniverseSelection method doesn't return a Future object like the AddFuture method. The Future object contains Symbol and Mappedmapped properties, which reference the continuous contract and the currently selected contract in the continuous contract series, respectively. To get the Future object, define the OnSecuritiesChangedon_securities_changed method in your algorithm class or framework models and check the result of the IsCanonical method.

// Return future objects if the added security in the universe is canonical.
public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
{
    foreach (var security in changes.AddedSecurities)
    {
        if (security.Symbol.IsCanonical() && security.Type == SecurityType.Future)
        {
            _future = security as Future;
        }
    }
}
# Return future objects if the added security in the universe is canonical.
def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None:
    for security in changes.added_securities:
        if security.Symbol.IsCanonical():
            self.future = security

To view the implementation of this model, see the LEAN GitHub repository.

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: