Universes

Futures

Introduction

A Futures universe lets you select a basket of contracts for a single Future. LEAN models Future subscriptions as a universe of Future contracts. A Future universe is similar to an Option universe, except Future contracts don't have a strike price, so the universe filter primarily focuses on the contract expiration date.

Create Universes

To add a universe of Future contracts, in the Initializeinitialize method, call the AddFutureadd_future method. This method returns an Future object, which contains the continuous contract Symbolsymbol. The continuous contract Symbol is the key to access the contracts in the FutureChain that LEAN passes to the OnDataon_data method. When you create the Future subscription, save a reference to the continuous contract Symbolsymbol so you can use it later in your algorithm.

UniverseSettings.Asynchronous = true;
_future = AddFuture(Futures.Currencies.BTC);
_symbol = _future.Symbol;
self.universe_settings.asynchronous = True
self.future = self.add_future(Futures.Currencies.BTC)
self._symbol = self.future.symbol

The following table describes the AddFutureadd_future method arguments:

Argument: ticker

The Future ticker. To view the supported assets in the US Futures dataset, see Supported Assets.

Data Type: stringstr | Default Value: None

Argument: resolution

The resolution of the market data. To view the supported resolutions, see Resolutions. If you don't provide a value, it uses Resolution.MinuteResolution.MINUTE by default.

Data Type: Resolution?Resolution/NoneType | Default Value: Nonenull

Argument: market

The Futures market. To view the supported markets in the US Futures dataset, see Supported Markets. If you don't provide a value, it uses the default Future market of your brokerage model.

Data Type: stringstr | Default Value: Nonenull

Argument: fillForwardfill_forward

If true, the current slice contains the last available data even if there is no data at the current time.

Data Type: bool | Default Value: Truetrue

Argument: leverage

The leverage for this Future.

Data Type: decimalfloat | Default Value: Security.NullLeverageSecurity.NULL_LEVERAGE

Argument: extendedMarketHoursextended_market_hours

If true, use data from the pre and post market sessions

Data Type: bool | Default Value: Falsefalse

Argument: dataMappingModedata_mapping_mode

The contract mapping mode to use for the continuous future contract

Data Type: DataMappingMode?DataMappingMode/NoneType | Default Value: Nonenull

Argument: dataNormalizationModedata_normalization_mode

The price scaling mode to use for the continuous future contract

Data Type: DataNormalizationMode?DataNormalizationMode/NoneType | Default Value: Nonenull

Argument: contractDepthOffsetcontract_depth_offset

The continuous future contract desired offset from the current front month. For example, 0 is the front month, 1 is the back month contract.

Data Type: int | Default Value: 0

Continous Contracts

By default, LEAN only subscribes to the continuous Future contract. A continuous Future contract represents a series of separate contracts stitched together to form a continuous price. If you need a lot of historical data to warm up an indicator, apply the indicator to the continuous contract price series. The Future object has a Symbolsymbol property and a Mappedmapped property. The price of the Symbolsymbol property is the adjusted price of the continuous contract. The price of the Mappedmapped property is the raw price of the currently selected contract in the continuous contract series.

// Get the adjusted price of the continuous contract
var adjustedPrice = Securities[_future.Symbol].Price; 

// Get the raw price of the currently selected contract in the continuous contract series
var rawPrice = Securities[_future.Mapped].Price;
# Get the adjusted price of the continuous contract
adjusted_price = self.securities[self.future.symbol].price 

# Get the raw price of the currently selected contract in the continuous contract series
raw_price = self.securities[self.future.mapped].price

To configure how LEAN identifies the current Future contract in the continuous series and how it forms the adjusted price between each contract, provide dataMappingModedata_mapping_mode, dataNormalizationModedata_normalization_mode, and contractDepthOffsetcontract_depth_offset arguments to the AddFutureadd_future method. The Future object that the AddFutureadd_future method returns contains a Mappedmapped property that references the current contract in the continuous contract series. As the contracts roll over, the Mappedmapped property references the next contract in the series and you receive a SymbolChangedEvent object in the OnDataon_data method. The SymbolChangedEvent references the old contract Symbol and the new contract Symbol. You can use SymbolChangedEvents to roll over contracts.

public override void OnData(Slice slice)
{
    foreach (var (symbol, changedEvent) in slice.SymbolChangedEvents)
    {
        var oldSymbol = changedEvent.OldSymbol;
        var newSymbol = changedEvent.NewSymbol;
        var tag = $"Rollover - Symbol changed at {Time}: {oldSymbol} -> {newSymbol}";
        var quantity = Portfolio[oldSymbol].Quantity;
        // Rolling over: to liquidate any position of the old mapped contract and switch to the newly mapped contract
        Liquidate(oldSymbol, tag: tag);
        if (quantity != 0) MarketOrder(newSymbol, quantity, tag: tag);
        Log(tag);
    }
}
def on_data(self, slice: Slice) -> None:
    for symbol, changed_event in  slice.symbol_changed_events.items():
        old_symbol = changed_event.old_symbol
        new_symbol = changed_event.new_symbol
        tag = f"Rollover - Symbol changed at {self.time}: {old_symbol} -> {new_symbol}"
        quantity = self.portfolio[old_symbol].quantity

        # Rolling over: to liquidate any position of the old mapped contract and switch to the newly mapped contract
        self.liquidate(old_symbol, tag = tag)
        if quantity != 0: self.market_order(new_symbol, quantity, tag = tag)
        self.log(tag)

In backtesting, the SymbolChangedEvent occurs at midnight Eastern Time (ET). In live trading, the live data for continuous contract mapping arrives at 6/7 AM ET, so that's when it occurs.

Data Normalization Modes

The dataNormalizationModedata_normalization_mode argument defines how the price series of two contracts are stitched together when the contract rollovers occur. The following DataNormalizatoinMode enumeration members are available for continuous contracts:

We use the entire Futures history to adjust historical prices. This process ensures you get the same adjusted prices, regardless of the backtest end date.

Data Mapping Modes

The dataMappingModedata_mapping_mode argument defines when contract rollovers occur. The DataMappingMode enumeration has the following members:

Contract Depth Offsets

The contractDepthOffsetcontract_depth_offset argument defines which contract to use. 0 is the front month contract, 1 is the following back month contract, and 3 is the second back month contract.

Filter Contracts

By default, LEAN doesn't add any contracts to the FuturesChain it passes to the OnDataon_data method. To add a universe of Future contracts, in the Initializeinitialize method, call the SetFilterset_filter method of the Future object. The following table describes the available filter techniques:

Method
Description
SetFilter(int minExpiryDays, int maxExpiryDays)set_filter(minExpiryDays: int, maxExpiryDays: int)Selects the contracts that expire within the range you set. This filter runs asynchronously by default.
SetFilter(Func<FutureFilterUniverse, FutureFilterUniverse> universeFunc)set_filter(universeFunc: Callable[[FutureFilterUniverse], FutureFilterUniverse])Selects the contracts that a function selects.
# Select the contracts which expire within 182 days
self.future.set_filter(0, 182)

# Select the front month contract
self.future.set_filter(lambda future_filter_universe: future_filter_universe.front_month())
// Select the contracts which expire within 182 days
_future.SetFilter(0, 182);

// Select the front month contract
_future.SetFilter(futureFilterUniverse => futureFilterUniverse.FrontMonth());

The following table describes the filter methods of the FutureFilterUniverse class:

MethodDescription
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 preceding methods return an FutureFilterUniverse, so you can chain the methods together.

// Select the front month standard contracts
_future.SetFilter(futureFilterUniverse => futureFilterUniverse.StandardsOnly().FrontMonth());
# Select the front month standard contracts
self.future.set_filter(lambda future_filter_universe: future_filter_universe.standards_only().front_month())

You can also define an isolated filter method.

// In Initialize
_future.SetFilter(Selector);
    
private FutureFilterUniverse Selector(FutureFilterUniverse futureFilterUniverse)
{
    return futureFilterUniverse.StandardsOnly().FrontMonth();
}
# In Initialize
self.future.set_filter(self.contract_selector)
    
def contract_selector(self, 
    future_filter_universe: Callable[[FutureFilterUniverse], FutureFilterUniverse]) -> FutureFilterUniverse:
    return future_filter_universe.standards_only().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.

By default, LEAN adds contracts to the FutureChain that pass the filter criteria at every time step in your algorithm. If a contract has been in the universe for a duration that matches the minimum time in universe setting and it no longer passes the filter criteria, LEAN removes it from the chain

Navigate Futures Chains

FuturesChain objects represent an entire chain of contracts for a single underlying Future. They have the following properties:

To get the FuturesChain, index the FuturesChainsfutures_chains property of the Slice with the continuous contract Symbol.

public override void OnData(Slice slice)
{
    if (slice.FuturesChains.TryGetValue(_symbol, out var chain))
    {
        // Example: Select the contract with the greatest open interest
        var contract = chain.OrderBy(x => x.OpenInterest).Last();
    }
}
def on_data(self, slice: Slice) -> None:
    chain = slice.futures_chains.get(self.symbol)
    if chain:
        # Example: Select the contract with the greatest open interest
        contract = sorted(chain, key=lambda contract: contract.open_interest, reverse=True)[0]

You can also loop through the FuturesChainsfutures_chains property to get each FuturesChain.

public override void OnData(Slice slice)
{
    foreach (var kvp in slice.FuturesChains)
    {
        var continuousContractSymbol = kvp.Key;
        var chain = kvp.Value;
    }
}

public void OnData(FuturesChains futuresChains)
{
    foreach (var kvp in futuresChains)
    {
        var continuousContractSymbol = kvp.Key;
        var chain = kvp.Value;
    }
}
def on_data(self, slice: Slice) -> None:
    for continuous_contract_symbol, chain in slice.futures_chains.items():
        pass

Selection Frequency

By default, Futures universes run at the first time step of each day to select their contracts.

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: