【问题标题】:Strategy Buy and Hold Monthly Backtrader策略买入并持有月度反向交易者
【发布时间】:2020-07-16 02:46:10
【问题描述】:

当我使用下面的策略运行我的反向交易者代码时,它不起作用。有人会知道为什么吗?甚至没有调用 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)

【问题讨论】:

    标签: python backtrader


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-18
      相关资源
      最近更新 更多