策略买入并持有月度回补交易者

2024-05-08 18:41:07 发布

您现在位置:Python中文网/ 问答频道 /正文

当我使用下面的策略运行backtrader代码时,它不起作用。谁都知道为什么?甚至没有调用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)

Tags: importselfaddsizedefnotifymathcash
1条回答
网友
1楼 · 发布于 2024-05-08 18:41:07

我不知道从哪里开始。你的策略在我的机器上运行得很好,尽管它实际上没有任何作用。。。我刚刚做了两个调整:

  1. 将start()替换为init()
  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)
...

相关问题 更多 >