简体   繁体   中英

Strategy Buy and Hold Monthly Backtrader

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)

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)
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM