Since there doesn't seem to be an easy way to schedule rebalancing to a once-a-month or once-a-week fequency, I have implemented the following RebalancingTimer class:

class RebalancingTimer(PortfolioConstructionModel):
def __init__(self,startTime, rebalanceFrequency):
self.lastRebalance = startTime
self.rebalanceFrequency = rebalanceFrequency
self.timeToRebalance = True
def isTimeToRebalance(self,algorithm,currentTime, securityExchange):
if self.timeToRebalance and securityExchange.DateTimeIsOpen(currentTime):
self.lastRebalance = currentTime
self.timeToRebalance = False
return True
else:
if "month" in self.rebalanceFrequency
and self.lastRebalance.month != currentTime.month : self.timeToRebalance = True
if "week" in self.rebalanceFrequency
and self.lastRebalance.week != currentTime.week : self.timeToRebalance = True
return False

The class is initialized in the main method and passed to the AlphaModel as follows:   

def Initialize(self):

        # Set requested data resolution
        self.UniverseSettings.Resolution = Resolution.Daily
        self.SetStartDate(2019, 2, 1)   #Set Start Date
        self.SetEndDate(2019, 3, 6)    #Set End Date
        self.SetCash(100000)           #Set Strategy Cash
        self.rebalancingTimer = RebalancingTimer(self.Time,"monthly")
        # selection will run on mon/tues/thurs at 00:00/06:00/12:00/18:00
        self.SetUniverseSelection(QC500UniverseSelectionModel())
        
        self.SetAlpha(SlopeBasedEquityMomentumAlphaModel(indexAverageWindow = 0,
rebalancingTimer=self.rebalancingTimer))

In the Update method of the AlphaModel, the class is used to return an empty insight list, if it is not yet time to rebalance:

 

def Update(self, algorithm, data):
''' Determines an insight for each security based on two annualized slopes
Args:
algorithm: The algorithm instance
data: The new data available
Returns:
The new insights generated'''
insights = []
if not self.rebalancingTimer.isTimeToRebalance(algorithm,algorithm.Time, self.exchange):
return insights

 

The problem is, that it doesn't work as intended. The following backtest over a period >1month should rebalance once, but does not generate any entries. What could be the problem? 

Author