Scheduling Functions
Scheduled events allow you to trigger code to run at specific times of day. This happens regardless of your data events. The schedule API requires a date and time rule to specify when the event is fired:
# Quantopian
schedule_function(func=rebalance,
date_rules=date_rules.every_day(),
time_rules=time_rules.market_open(hours=1))
# QuantConnect
self.Schedule.On(self.DateRules.EveryDay("SPY"),
self.TimeRules.AfterMarketOpen(self.spy, 60),
Action(self.rebalance))
Unlike Quantopian, the func does not require a data object:
def rebalance(self):
self.Log("EveryDay.SPY 60 min after open: Fired at: {0}".format(self.Time))
At this point, we need to introduce another member of QCAlgorithm: Securities. This object have the information about all the subcribed securities and can be accessed anywhere in the algorithm, unlike the Slice object that arrives at OnData:
def rebalance(self):
spy = self.Securities["SPY"]
price = spy.Price
self.Log("EveryDay.SPY 60 min after open: Fired at: {0}".format(self.Time))
The following working example takes a long position in SPY at the start of the week, and closes out the position at 3:30pm on the last day of the week:
def initialize(context):
context.spy = sid(8554)
schedule_function(open_positions, date_rules.week_start(), time_rules.market_open())
schedule_function(close_positions, date_rules.week_end(), time_rules.market_close(minutes=30))
def open_positions(context, data):
order_target_percent(context.spy, 0.10)
def close_positions(context, data):
order_target_percent(context.spy, 0)
class MyAlgo(QCAlgorithm):
def Initialize(self):
AddEquity("SPY")
self.Schedule.On(self.DateRules.Every(DayOfWeek.Monday, DayOfWeek.Monday), \
self.TimeRules.AfterMarketOpen(self.spy), \
Action(self.open_positions))
self.Schedule.On(self.DateRules.Every(DayOfWeek.Friday, DayOfWeek.Friday), \
self.TimeRules.BeforeMarketClose(self.spy, 30), \
Action(self.close_positions))
def open_positions(self):
self.SetHoldings("SPY", 0.10)
def close_positions(self):
self.Liquidate("SPY")
From complete Date and Time rules, please checkout these reference tables. Since the equivalent date rule for week start and week end are missing, we can look into implementing it.