Scheduling Rebalance Day

I'm attempting to capture the month end rebalance effect in a Momentum strategy. I'd like the rebalance to occur on the 17th trading day of the month (out of 21). I used the following code in the "def_initialize" and "schedule_function" to offset the rebalance from the "month_start" but in the backtest the trades are consistently occurring later in the month. Any guidance would be appreciated.

def initialize(context):
    algo.set_benchmark(algo.symbol("SPY"))
    algo.attach_pipeline(make_pipeline(), "pipe")

    # rebalance monthly
    algo.schedule_function(
        rebalance,
        algo.date_rules.month_start(17),
        algo.time_rules.market_close(),
    )

schedule_function() determines when your functions run, but in daily mode, orders will be executed in the session following the one in which they're placed. The assumption with daily mode is that you're running the strategy after the close, so orders get filled the next day. If you want to trade on the 17th day, try scheduling the function on the 16th day.

1 Like

Brian, I see the day, week, and month functions. Do I need to create a custom function for a Quarterly Rebalance? Thanks.

You can schedule your function monthly and then place an additional block of code at the start of your function that checks whether it is month 1, 4, 7, or 10.

1 Like

Great. Thank you.