Unable to call notify_timer in backtrader

114 Views Asked by At

I am new to backtrader and I am trying to design strategies that involve a timer that triggers an action. Specifically, I am trying to take the action on the first day of each month.

class MyStrategy(bt.Strategy):
    def __init__(self):
        self.add_timer(bt.timer.SESSION_END, monthdays=[1], monthcarry=True)
        
    def notify_timer(self, timer, *args, **kwargs):
        print("Timer triggered. No take action: buy, sell, ...")

cerebro = bt.Cerebro()
cerebro.addstrategy(MyStrategy)
cerebro.adddata(pandasDataFeed(dataname=yf.Ticker("SPY").history(period="5y").reset_index()))
cerebro.broker.setcash(1000.0)
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.run()
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())

With the previous code, I get no print message, which means notify_timer is not being called, even though I included the monthly timer. What am I doing wrong?

1

There are 1 best solutions below

0
Diego Tremper On

Try:

class MyStrategy(bt.Strategy):
    def __init__(self):
        self.add_timer(datetime.time(0, 0, 0), monthdays=[1], monthcarry=True)
        
    def notify_timer(self, timer, *args, **kwargs):
        print("Timer triggered. No take action: buy, sell, ...")

In my case, the issue was related with the timezone.