Universes

Settings

Introduction

Universe settings and security initializers enable you to configure some properties of the securities in a universe.

Resolution

The Resolutionresolution setting defines the time period of the asset data. The Resolution enumeration has the following members:

To view which resolutions are available for the asset class of your universe, follow these steps:

  1. Open the Asset Classes documentation page.
  2. Click an asset class.
  3. Click Requesting Data.
  4. On the Requesting Data page, in the table of contents, click Resolutions.

The default value is Resolution.MinuteResolution.MINUTE. To change the resolution, in the Initialize method, pass a resolution argument to the universe creation method.

AddOption("SPY", resolution: Resolution.Daily);
self.add_option("SPY", resolution=Resolution.DAILY)

Leverage

The Leverageleverage setting is a floatdecimal that defines the maximum amount of leverage you can use for a single asset in a non-derivative universe. The default value is Security.NullLeverageSecurity.NULL_LEVERAGE (0). To change the leverage, in the Initialize method, adjust the algorithm's UniverseSettingsuniverse_settings before you add the universe.

UniverseSettings.Leverage = 2.0m;
AddUniverse(Universe.DollarVolume.Top(50));
self.universe_settings.leverage = 2.0
self.add_universe(self.universe.dollar_volume.top(50))

Fill Forward

The FillForwardfill_forward setting is a bool that defines whether or not too fill forward data. The default value is trueTrue. To disable fill forward in non-derivative universes, in the Initialize method, adjust the algorithm's UniverseSettingsuniverse_settings before you add the universe.

UniverseSettings.FillForward = false;
AddUniverse(Universe.DollarVolume.Top(50));
self.universe_settings.fill_forward = False
self.add_universe(self.universe.dollar_volume.top(50))

To disable fill forward in derivative universes, pass a fillForwardfill_forward argument to the universe creation method.

AddIndexOption("VIX", fillForward: false);
self.add_index_option("VIX", fill_forward=False)

Extended Market Hours

The ExtendedMarketHoursextended_market_hours setting is a bool that defines the trading schedule. If it's trueTrue, your algorithm receives price data for all trading hours. If it's falseFalse, your algorithm receives price data only for regular trading hours. The default value is falseFalse.

You only receive extended market hours data if you create the subscription with an intraday resolution. If you create the subscription with daily resolution, the daily bars only reflect the regular trading hours.

To view the trading schedule of an asset, open Asset Classes, click an asset class, then click Market Hours.

To enable extended market hours in non-derivative universes, in the Initialize method, adjust the algorithm's UniverseSettingsuniverse_settings before you add the universe.

UniverseSettings.ExtendedMarketHours = true;
AddUniverse(Universe.DollarVolume.Top(50));
self.universe_settings.extended_market_hours = True
self.add_universe(self.universe.dollar_volume.top(50))

To enable extended market hours in derivative universes, pass an extendedMarketHoursextended_market_hours argument to the universe creation method.

AddFuture(Futures.Currencies.BTC, extendedMarketHours: true);
self.add_future(Futures.Currencies.BTC, extended_market_hours=True)

Minimum Time in Universe

The MinimumTimeInUniverseminimum_time_in_universe setting is a timedeltaTimeSpan object that defines the minimum amount of time an asset must be in the universe before the universe can remove it. The default value is TimeSpan.FromDays(1)timedelta(1). To change the minimum time, in the Initialize method, adjust the algorithm's UniverseSettingsuniverse_settings before you add the universe.

UniverseSettings.MinimumTimeInUniverse = TimeSpan.FromDays(7);
AddUniverse(Universe.DollarVolume.Top(50));
self.universe_settings.minimum_time_in_universe = timedelta(7)
self.add_universe(self.universe.dollar_volume.top(50))

Data Normalization Mode

The DataNormalizationModedata_normalization_mode setting is an enumeration that defines how historical data is adjusted. This setting is only applicable for US Equities and Futures.

US Equities

In the case of US Equities, the data normalization mode affects how historical data is adjusted for corporate actions. To view all the available options, see Data Normalization. The default value is DataNormalizationMode.AdjustedDataNormalizationMode.ADJUSTED. To change the data normalization mode, in the Initialize method, adjust the algorithm's UniverseSettingsuniverse_settings before you add the universe.

UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw;
AddUniverse(Universe.DollarVolume.Top(50));
self.universe_settings.data_normalization_mode = DataNormalizationMode.RAW
self.add_universe(self.universe.dollar_volume.top(50))

Futures

In the case of Futures, the data normalization mode affects how historical data of two contracts is stitched together to form the continuous contract. To view all the available options, see Data Normalization. The default value is DataNormalizationMode.AdjustedDataNormalizationMode.ADJUSTED. To change the data normalization mode, in the Initialize method, pass a dataNormalizationModedata_normalization_mode argument to the AddFutureadd_future method.

AddFuture(Futures.Currencies.BTC, dataNormalizationMode: DataNormalizationMode.BackwardsRatio);
self.add_future(Futures.Currencies.BTC, data_normalization_mode=DataNormalizationMode.BACKWARDS_RATIO)

Contract Depth Offset

The ContractDepthOffsetcontract_depth_offset setting is an int that defines which contract to use for the continuous Futures contract. 0 is the front month contract, 1 is the following back month contract, and 3 is the second back month contract. The default value is 0. To change the contract depth offset, in the Initialize method, pass a contractDepthOffsetcontract_depth_offset argument to the AddFutureadd_future method.

AddFuture(Futures.Currencies.BTC, contractDepthOffset: 3);
self.add_future(Futures.Currencies.BTC, contract_depth_offset=3)

Asynchronous Selection

The Asynchronousasynchronous setting is a bool that defines whether or not LEAN can run universe selection asynchronously, utilizing concurrent execution to increase the speed of your algorithm. The default value for this setting is falseFalse. If you enable this setting, abide by the following rules:

  • Don't make any history requests in your filter function. History requests can only provide data up to the algorithm time, but if your filter function runs asynchronously, the algorithm time may not be what you expect.
  • Don't use the portfolio, security, or orders state. The Portfolioportfolio, Securitiessecurities, and Transactionstransactions objects are also functions of the algorithm time.
  • If your filter function updates a class variable, don't update the class variable anywhere else in your algorithm.

To enable asynchronous universe selection, in the Initialize method, adjust the algorithm's UniverseSettingsuniverse_settings before you add the universe.

UniverseSettings.Asynchronous = true;
AddUniverse(Universe.DollarVolume.Top(50));
self.universe_settings.asynchronous = True
self.add_universe(self.universe.dollar_volume.top(50))

Schedule

The Scheduleschedule setting defines the selection schedule of the universe. Most universes run on a daily schedule. To change the selection schedule, call the UniverseSettings.Schedule.Onuniverse_settings.schedule.on method with an IDateRule object before you add the universe.

UniverseSettings.Schedule.On(DateRules.MonthStart());
AddUniverse(Universe.DollarVolume.Top(50));
self.universe_settings.schedule.on(self.date_rules.month_start())
self.add_universe(self.universe.dollar_volume.top(50))

The following table describes the supported DateRules:

MemberDescription
self.date_rules.set_default_time_zone(time_zone: DateTimeZone) DateRules.SetDefaultTimeZone(DateTimeZone timeZone);Sets the time zone for the DateRules object used in all methods in this table. The default time zone is the algorithm time zone.
self.date_rules.on(year: int, month: int, day: int) DateRules.On(int year, int month, int day)Trigger an event on a specific date.
self.date_rules.every_day() DateRules.EveryDay()Trigger an event every day.
self.date_rules.every_day(symbol: Symbol) DateRules.EveryDay(Symbol symbol)Trigger an event every day a specific symbol is trading.
self.date_rules.every(days: List[DayOfWeek]) DateRules.Every(params DayOfWeek[] days)Trigger an event on specific days throughout the week. To view the DayOfWeek enum members, see DayOfWeek Enum in the .NET documentation.
self.date_rules.month_start(daysOffset: int = 0) DateRules.MonthStart(int daysOffset = 0)Trigger an event on the first day of each month plus an offset.
self.date_rules.month_start(symbol: Symbol, daysOffset: int = 0) DateRules.MonthStart(Symbol symbol, int daysOffset = 0)Trigger an event on the first tradable date of each month for a specific symbol plus an offset.
self.date_rules.month_end(daysOffset: int = 0) DateRules.MonthEnd(int daysOffset = 0)Trigger an event on the last day of each month minus an offset.
self.date_rules.month_end(symbol: Symbol, daysOffset: int = 0) DateRules.MonthEnd(Symbol symbol, int daysOffset = 0)Trigger an event on the last tradable date of each month for a specific symbol minus an offset.
self.date_rules.week_start(daysOffset: int = 0) DateRules.WeekStart(int daysOffset = 0)Trigger an event on the first day of each week plus an offset.
self.date_rules.week_start(symbol: Symbol, daysOffset: int = 0) DateRules.WeekStart(Symbol symbol, int daysOffset = 0)Trigger an event on the first tradable date of each week for a specific symbol plus an offset.
self.date_rules.week_end(daysOffset: int = 0) DateRules.WeekEnd(int daysOffset = 0)Trigger an event on the last day of each week minus an offset.
self.date_rules.week_end(symbol: Symbol, daysOffset: int = 0) DateRules.WeekEnd(Symbol symbol, int daysOffset = 0)Trigger an event on the last tradable date of each week for a specific symbol minus an offset.
self.date_rules.todayDateRules.TodayTrigger an event once today.
self.date_rules.tomorrowDateRules.TomorrowTrigger an event once tomorrow.

In live trading, scheduled universes run at roughly 8 AM Eastern Time to ensure there is enough time for the data to process.

Configure Universe Securities

Instead of configuring global universe settings, you can individually configure the settings of each security in the universe with a security initializer. Security initializers let you apply any security-level reality model or special data requests on a per-security basis. To set the security initializer, in the Initializeinitialize method, call the SetSecurityInitializerset_security_initializer method and then define the security initializer.

//In Initialize
SetSecurityInitializer(CustomSecurityInitializer);

private void CustomSecurityInitializer(Security security)
{
    // Disable trading fees
    security.SetFeeModel(new ConstantFeeModel(0, "USD"));
}
#In Initialize
self.set_security_initializer(self.custom_security_initializer)

def custom_security_initializer(self, security: Security) -> None:
    # Disable trading fees
    security.set_fee_model(ConstantFeeModel(0, "USD"))

For simple requests, you can use the functional implementation of the security initializer. This style lets you configure the security object with one line of code.

SetSecurityInitializer(security => security.SetFeeModel(new ConstantFeeModel(0, "USD")));
self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0, "USD")))

In some cases, you may want to trade a security in the same time loop that you create the security subscription. To avoid errors, use a security initializer to set the market price of each security to the last known price. The GetLastKnownPricesget_last_known_prices method seeds the security price by gathering the security data over the last 3 days. If there is no data during this period, the security price remains at 0.

var seeder = new FuncSecuritySeeder(GetLastKnownPrices);
SetSecurityInitializer(security => seeder.SeedSecurity(security));
seeder = FuncSecuritySeeder(self.get_last_known_prices)
self.set_security_initializer(lambda security: seeder.seed_security(security))

If you call the SetSecurityInitializerset_security_initializer method, it overwrites the default security initializer. The default security initializer uses the security-level reality models of the brokerage model to set the following reality models of each security:

The default security initializer also sets the leverage of each security and intializes each security with a seeder function. To extend upon the default security initializer instead of overwriting it, create a custom BrokerageModelSecurityInitializer.

// In Initialize
SetSecurityInitializer(new MySecurityInitializer(BrokerageModel, new FuncSecuritySeeder(GetLastKnownPrices)));

// Outside of the algorithm class
class MySecurityInitializer : BrokerageModelSecurityInitializer
{
    public MySecurityInitializer(IBrokerageModel brokerageModel, ISecuritySeeder securitySeeder)
        : base(brokerageModel, securitySeeder) {}    
    
    public override void Initialize(Security security)
    {
        // First, call the superclass definition
        // This method sets the reality models of each security using the default reality models of the brokerage model
        base.Initialize(security);

        // Next, overwrite some of the reality models        
        security.SetFeeModel(new ConstantFeeModel(0, "USD"));    
    }
}
# In Initialize
self.set_security_initializer(MySecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices)))

# Outside of the algorithm class
class MySecurityInitializer(BrokerageModelSecurityInitializer):

    def __init__(self, brokerage_model: IBrokerageModel, security_seeder: ISecuritySeeder) -> None:
        super().__init__(brokerage_model, security_seeder)
    def initialize(self, security: Security) -> None:
        # First, call the superclass definition
        # This method sets the reality models of each security using the default reality models of the brokerage model
        super().initialize(security)

        # Next, overwrite some of the reality models        
        security.set_fee_model(ConstantFeeModel(0, "USD"))

To set a seeder function without overwriting the reality models of the brokerage, use the standard BrokerageModelSecurityInitializer.

var seeder = new FuncSecuritySeeder(GetLastKnownPrices);
SetSecurityInitializer(new BrokerageModelSecurityInitializer(BrokerageModel, seeder));
seeder = FuncSecuritySeeder(self.get_last_known_prices)
self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, seeder))

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: