0

When I run my backtrader code with the strategy below it doesn't work. Anybody would know why? The notify_timer function is not even called! Thanks!

import math  
import backtrader as bt

class BuyEveryMonth(bt.Strategy):
    params = (('monthly_amount', 100),)

    def start(self):
        self.add_timer(bt.timer.SESSION_END, monthdays=[3], monthcarry = True,) 

    def notify_timer(self, timer, when, *args, **kwargs):
        # Add the influx of monthly cash to the broker
        self.broker.add_cash(self.params.monthly_amount)

        # buy available cash
        self.size = math.floor(self.broker.getcash() / self.data.close)
        print("{}: Buy {} shares at {}".format(self.datetime.date(ago=0), self.size, self.data.close[0]))
        print(self.size)
        self.buy(size=self.size)
Charles Wagner
  • 103
  • 1
  • 2
  • 10

1 Answers1

0

I'm not sure where the start comes from. Your strategy runs fine on my machine, even though it doesn't really do anything... I just made 2 adjustments:

  1. replacing start() with init()
  2. removing the trailing comma in init(arg1, arg2, argn,)

gives:

def __init__(self):
  self.add_timer(bt.timer.SESSION_END, monthdays=[3], monthcarry=True)
  
def notify_timer(self, timer, when, *args, **kwargs):
  # Add the influx of monthly cash to the broker
  self.broker.add_cash(self.params.monthly_amount)

  # buy available cash
  self.size = math.floor(self.broker.getcash() / self.data.close)
  print("{}: Buy {} shares at {}".format(self.datetime.date(ago=0), self.size, self.data.close[0]))
  print(self.size)
  self.buy(size=self.size)

Then calling it later like:

...
# Create a cerebro entity
cerebro = bt.Cerebro()

# Add a strategy
cerebro.addstrategy(BuyEveryMonth)
...
AGI_rev
  • 129
  • 10