Universe Selection

Scheduled Universes

Introduction

A Scheduled Universe Selection model selects assets at fixed, regular intervals. In live trading, you can use this type of model to fetch tickers from Dropbox or to perform periodic historical analysis and select some assets.

Scheduled Universe Selection

The ScheduledUniverseSelectionModel selects assets on the schedule you provide. To use this model, provide a DateRule, TimeRule, and a selector function. The DateRule and TimeRule define the selection schedule. The selector function receives a datetimeDateTime object and returns a list of Symbol objects. The Symbol objects you return from the selector function are the constituents of the universe.

UniverseSettings.Asynchronous = true;
AddUniverseSelection(
    new ScheduledUniverseSelectionModel(
        DateRules.MonthStart(), 
        TimeRules.Midnight, 
        dt => new List<Symbol> { 
            QuantConnect.Symbol.Create(dt.Month == 10 ? "SPY" : "QQQ", SecurityType.Equity, Market.USA) 
        }
    )
);
self.universe_settings.asynchronous = True
self.add_universe_selection(
    ScheduledUniverseSelectionModel(
        self.date_rules.month_start(), 
        self.time_rules.midnight, 
        lambda dt: [Symbol.create("SPY" if dt.month == 10 else "QQQ", SecurityType.EQUITY, Market.USA)]
    )
)

The following table describes the arguments the model accepts:

ArgumentData TypeDescriptionDefault Value
dateRuledate_ruleIDateRuleDate rule defines what days the universe selection function will be invoked
timeRuletime_ruleITimeRuleTime rule defines what times on each day selected by date rule the universe selection function will be invoked
selectorFunc<DateTime, IEnumerable<Symbol>>Callable[[datetime], List[Symbol]]Selector function accepting the date time firing time and returning the universe selected symbols
settingsUniverseSettingsThe universe settings. If you don't provide an argument, the model uses the algorithm.UniverseSettingsalgorithm.universe_settings by default.Nonenull

The model assumes the timeRuletime_rule argument is in Coordinated Universal Time (UTC). To use a different timezone, pass a timeZone argument of type DateTimeZone before the dateRuledate_rule argument.

To return the current universe constituents from the selector function, return Universe.Unchanged.

// Selection will run on mon/tues/thurs at 00:00/06:00/12:00/18:00
AddUniverseSelection(new ScheduledUniverseSelectionModel(
    DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Thursday),
    TimeRules.Every(TimeSpan.FromHours(6)),
    SelectSymbols // selection function in algorithm.
));

// Create selection function which returns symbol objects.
private IEnumerable<Symbol> SelectSymbols(DateTime dateTime)
{
    var tickers = new[] {"SPY", "AAPL", "IBM"};
    return tickers.Select(ticker =>
        QuantConnect.Symbol.Create(ticker, SecurityType.Equity, Market.USA));
}
# Selection will run on mon/tues/thurs at 00:00/06:00/12:00/18:00
self.AddUniverseSelection(ScheduledUniverseSelectionModel(
    self.DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Thursday),
    self.TimeRules.Every(timedelta(hours = 6)),
    self.SelectSymbols # selection function in algorithm.
))

# Create selection function which returns symbol objects.
def SelectSymbols(self, dateTime: datetime) -> List[Symbol]:
    tickers = ['SPY', 'AAPL', 'IBM']
    return [Symbol.Create(ticker, SecurityType.Equity, Market.USA)
        for ticker in tickers]

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

Date Rules

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.

Time Rules

The following table describes the supported TimeRules:

MemberDescription
self.time_rules.set_default_time_zone(time_zone: DateTimeZone) TimeRules.SetDefaultTimeZone(DateTimeZone timeZone)Sets the time zone for the TimeRules object used in all methods in this table, except when a different time zone is given. The default time zone is the algorithm time zone.
self.time_rules.after_market_open(symbol: Symbol, minutesAfterOpen: float = 0, extendedMarketOpen: bool = False) TimeRules.AfterMarketOpen(Symbol symbol, double minutesAfterOpen = 0, bool extendedMarketOpen = false)Trigger an event a few minutes after market open for a specific symbol (default is 0). This rule doesn't work for Crypto securities or custom data.
self.time_rules.before_market_close(symbol: Symbol, minutesBeforeClose: float = 0, extendedMarketOpen: bool = False) TimeRules.BeforeMarketClose(Symbol symbol, double minutesBeforeClose = 0, bool extendedMarketOpen = false)Trigger an event a few minutes before market close for a specific symbol (default is 0). This rule doesn't work for Crypto securities or custom data.
self.time_rules.every(interval: timedelta) TimeRules.Every(TimeSpan interval)Trigger an event every period interval starting at midnight.
self.time_rules.nowTimeRules.NowTrigger an event at the current time of day.
self.time_rules.midnightTimeRules.MidnightTrigger an event at midnight.
self.time_rules.noonTimeRules.NoonTrigger an event at noon.
self.time_rules.at(hour: int, minute: int, second: int = 0) TimeRules.At(int hour, int minute, int second = 0)Trigger an event at a specific time of day (e.g. 13:10).
self.time_rules.at(hour: int, minute: int, second: int, time_zone: DateTimeZone) TimeRules.At(int hour, int minute, int second, DateTimeZone timeZone)Trigger an event at a specific time of day in the given time zone (e.g. 13:10 UTC).

Examples

// Select the universe on a specific date at a specific time 
AddUniverseSelection(new ScheduledUniverseSelectionModel(
    DateRules.On(2013, 10, 7),
    TimeRules.At(13, 0),
    SelectSymbols));

// Select the universe 10 minutes after SPY starts trading each day
AddUniverseSelection(new ScheduledUniverseSelectionModel(
    DateRules.EveryDay("SPY"),
    TimeRules.AfterMarketOpen("SPY", 10),
    SelectSymbols));

// Select the universe 10 minutes before SPY stops trading each day
AddUniverseSelection(new ScheduledUniverseSelectionModel(
    DateRules.EveryDay("SPY"),
    TimeRules.BeforeMarketClose("SPY", 10),
    SelectSymbols));

// Select the universe on Monday and Friday at noon
AddUniverseSelection(new ScheduledUniverseSelectionModel(
    DateRules.Every(DayOfWeek.Monday, DayOfWeek.Friday),
    TimeRules.At(12, 0),
    SelectSymbols));

// Select the universe now
AddUniverseSelection(new ScheduledUniverseSelectionModel(
    DateRules.Today,
    TimeRules.Now,
    SelectSymbols));

// Select the universe tomorrow at midnight
AddUniverseSelection(new ScheduledUniverseSelectionModel(
    DateRules.Tomorrow,
    TimeRules.Midnight,
    SelectSymbols));

// Select the universe today at noon
AddUniverseSelection(new ScheduledUniverseSelectionModel(
    DateRules.Today,
    TimeRules.Noon,
    SelectSymbols));

// Select the universe every 10 minutes on everyday 
AddUniverseSelection(new ScheduledUniverseSelectionModel(
    DateRules.EveryDay(), 
    TimeRules.Every(TimeSpan.FromMinutes(10)),
    SelectSymbols));
            
// Select the universe at the market open on the first day of the month the SPY starts trading
AddUniverseSelection(new ScheduledUniverseSelectionModel(
    DateRules.MonthStart("SPY"),
    TimeRules.AfterMarketOpen("SPY"),
    SelectSymbols));

// Select the universe at the market close on the last day of the month the SPY trades
AddUniverseSelection(new ScheduledUniverseSelectionModel(
    DateRules.MonthEnd("SPY"),
    TimeRules.BeforeMarketClose("SPY"),
    SelectSymbols));

// Select the universe 5 minutes after SPY starts trading each week
AddUniverseSelection(new ScheduledUniverseSelectionModel(
    DateRules.WeekStart("SPY"),
    TimeRules.AfterMarketOpen("SPY", 5),
    SelectSymbols));

// Select the universe 5 minutes before the SPY stops trading each week
AddUniverseSelection(new ScheduledUniverseSelectionModel(
    DateRules.WeekEnd("SPY"),
    TimeRules.BeforeMarketClose("SPY", 5),
    SelectSymbols));


// Define a selection function that returns Symbol objects
private IEnumerable<Symbol> SelectSymbols(DateTime dateTime)
{
    var tickers = new[] {"SPY", "AAPL", "IBM"};
    return tickers.Select(ticker =>
        QuantConnect.Symbol.Create(ticker, SecurityType.Equity, Market.USA));
}      
# Select the universe on a specific date at a specific time 
self.add_universe_selection(ScheduledUniverseSelectionModel(
    self.date_rules.on(2013, 10, 7), 
    self.time_rules.at(13, 0),
    self.select_symbols))
    
# Select the universe 10 minutes after SPY starts trading each day
self.add_universe_selection(ScheduledUniverseSelectionModel(
    self.date_rules.every_day("SPY"), 
    self.time_rules.after_market_open("SPY", 10),
    self.select_symbols))

# Select the universe 10 minutes before SPY stops trading each day
self.add_universe_selection(ScheduledUniverseSelectionModel(
    self.date_rules.every_day("SPY"),
    self.time_rules.before_market_close("SPY", 10),
    self.select_symbols))

# Select the universe on Monday and Friday at noon
self.add_universe_selection(ScheduledUniverseSelectionModel(
    self.date_rules.every(DayOfWeek.MONDAY, DayOfWeek.FRIDAY),
    self.time_rules.at(12, 0),
    self.select_symbols))

# Select the universe now
self.add_universe_selection(ScheduledUniverseSelectionModel(
    self.date_rules.today,
    self.time_rules.now,
    self.select_symbols))

# Select the universe tomorrow at midnight
self.add_universe_selection(ScheduledUniverseSelectionModel(
    self.date_rules.tomorrow,
    self.time_rules.midnight,
    self.select_symbols))
    
# Select the universe today at noon
self.add_universe_selection(ScheduledUniverseSelectionModel(
    self.date_rules.today,
    self.time_rules.noon,
    self.select_symbols))

# Select the universe every 10 minutes on everyday 
self.add_universe_selection(ScheduledUniverseSelectionModel(
    self.date_rules.every_day(), 
    self.time_rules.every(timedelta(minutes=10)),
    self.select_symbols))

# Select the universe at the market open on the first day of the month the SPY starts trading
self.add_universe_selection(ScheduledUniverseSelectionModel(
    self.date_rules.month_start("SPY"),
    self.time_rules.after_market_open("SPY"),
    self.select_symbols))

# Select the universe at the market close on the last day of the month the SPY trades
self.add_universe_selection(ScheduledUniverseSelectionModel(
    self.date_rules.month_end("SPY"),
    self.time_rules.before_market_close("SPY"),
    self.select_symbols))

# Select the universe 5 minutes after SPY starts trading each week
self.add_universe_selection(ScheduledUniverseSelectionModel(
    self.date_rules.week_start("SPY"),
    self.time_rules.after_market_open("SPY", 5),
    self.select_symbols))

# Select the universe 5 minutes before the SPY stops trading each week
self.add_universe_selection(ScheduledUniverseSelectionModel(
    self.date_rules.week_end("SPY"),
    self.time_rules.before_market_close("SPY", 5),
    self.select_symbols))


# Define a selection function that returns Symbol objects
def select_symbols(self, date_time: datetime) -> List[Symbol]:
    tickers = ['SPY', 'AAPL', 'IBM']
    return [Symbol.create(ticker, SecurityType.EQUITY, Market.USA)
        for ticker in tickers]

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: