0

当我使用下面的策略运行我的反向交易代码时,它不起作用。有人会知道为什么吗?甚至没有调用 notify_timer 函数!谢谢!

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

1 回答 1

0

我不确定从哪里开始。您的策略在我的机器上运行良好,即使它并没有真正做任何事情......我只做了 2 处调整:

  1. 用init ()替换 start( )
  2. 删除init (arg1, arg2, argn,)中的尾随逗号

给出:

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)

然后稍后调用它:

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

# Add a strategy
cerebro.addstrategy(BuyEveryMonth)
...
于 2020-07-15T18:46:10.730 回答