🚀 AI One-Click Generation of quantconnect Strategy Code

Mastering Scheduled Events in QuantConnect with DateRules and TimeRules

quantconnect | Published on: 2025/12/2
The following content is generated by EasyQuant .

Problem Description

How do I schedule a function to run at the market open on the first day of every month?

Solution

To schedule a function to run at the market open on the first trading day of every month in QuantConnect, you use the self.schedule.on method within the initialize function.

You will need to combine two helper objects:

  1. self.date_rules.month_start(symbol): This triggers on the first trading day of the month for the specific symbol (automatically skipping weekends and holidays).
  2. self.time_rules.after_market_open(symbol, 0): This triggers immediately when the market opens for that symbol.

Implementation Example

Here is a complete, runnable algorithm demonstrating this setup.

from AlgorithmImports import *

class MonthlyScheduleAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2023, 1, 1)
        self.set_end_date(2023, 6, 1)
        self.set_cash(100000)

        # 1. Add a symbol to act as the time reference (e.g., SPY for US Equity market hours)
        self.spy = self.add_equity("SPY", Resolution.MINUTE).symbol

        # 2. Schedule the event
        # - DateRule: First trading day of the month
        # - TimeRule: 0 minutes after market open
        # - Action: The function to execute (self.rebalance_portfolio)
        self.schedule.on(
            self.date_rules.month_start(self.spy),
            self.time_rules.after_market_open(self.spy, 0),
            self.rebalance_portfolio
        )

    def rebalance_portfolio(self):
        """
        This function runs at the market open on the first trading day of every month.
        """
        self.log(f"Monthly Rebalance Triggered at: {self.time}")
        
        # Example logic: Invest 100% in SPY
        if not self.portfolio.invested:
            self.set_holdings(self.spy, 1.0)

    def on_data(self, data):
        pass

Key Details

  • Symbol Dependency: The month_start rule requires a symbol argument. This is crucial because "Month Start" is defined by the trading calendar of that specific asset. If the 1st of the month is a Saturday, month_start will automatically fire on Monday the 3rd (assuming Monday is a trading day).
  • Time Offset: The second argument in after_market_open(symbol, minutes) is the delay in minutes. Setting it to 0 runs it exactly at the open (e.g., 9:30 AM ET for US Equities). If you want to ensure data is fully loaded or avoid opening volatility, you might change 0 to 10 or 30.

Q&A

Q: Can I schedule the event for a specific day of the month other than the first?
A: No, month_start does not accept an index. However, you can use self.date_rules.on(year, month, day) for specific dates, or use logic inside on_data to check self.time.day. For recurring specific days (e.g., the 15th), custom logic inside a daily scheduled event is usually required.

Q: What happens if the market closes early on the first of the month?
A: after_market_open is relative to the open time, so early closes do not affect the start time. However, if you use before_market_close, the engine automatically adjusts for early closes.

Q: Does this work for Crypto?
A: Yes, but Crypto markets (like BTCUSD) trade 24/7. "Market Open" for Crypto in LEAN is typically considered 00:00 UTC. Ensure your set_time_zone matches your expectations if you are trading assets with 24-hour schedules.

Q: How do I stop the scheduled event?
A: Scheduled events defined in initialize run for the duration of the algorithm. To stop executing logic, you should add a conditional check (flag) inside your handler function (e.g., self.rebalance_portfolio) to return early if specific criteria are met.