I am new to Python and Quantopian.
I target to rebalance the portfolio every quarter end by using the schedule function together with an if statement. However, it just doesn't work.
I am new to Python and Quantopian.
I target to rebalance the portfolio every quarter end by using the schedule function together with an if statement. However, it just doesn't work.
A couple of things...
The 'initialize' method get's executed exactly once when you launch your algorithm. The following statements won't get executed like you probably want.
def initialize(context):
# Schedule our rebalance function to run at the end of each quarter.
now = datetime.datetime.now()
if now.month == 3 or now.month == 6 or now.month == 9 or now.month == 12:
schedule_function(my_rebalance, date_rules.month_end(), time_rules.market_close(minutes=30))
Keep your schedule_ function for month end in initialize, however move the month check into your 'my_rebalance' function. Also, don't use the 'datetime' function (it will return the current time NOT the backtest time during backtesting). Use 'get-datetime' instead (see https://www.quantopian.com/help#api-get-datetime). Your if statement will work but using an 'if n in list' may be more readable?
def my_rebalance(context, data):
"""
Rebalance quarterly.
"""
this_month = get_datetime('US/Eastern').month
if this_month not in [3, 6, 9, 12]:
log.info("skipping this month")
return
else:
log.info("trading this month")
# put the code you want executed quarterly below
Also, consider using one of the built in universe filters (eg Q500US see https://www.quantopian.com/help#built-in-filters). You will find your algo runs much faster.
Good luck.