For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

optstrategy



  • When I change the add policy to traversal parameter and add def stop, the error comes
    I'm a novice. Please help me!

    import backtrader as bt
    import os
    import sys
    import datetime
    import pandas as pd
    import optunity.metrics
    '''Data Feeds(数据加载)、Indicators(技术指标)和Strategies(策略)都会生成 Lines。'''
    class DT_Line(bt.Indicator): # bt.SignalStrategy bt.indicators

    lines = ('U', 'D')  # u-up最高价 D-down最低价
    params = (('period', 2), ('k_u', 0.7), ('k_d', 0.7))  # params简写 .p
    
    
    def __init__(self):
    
        self.addminperiod(self.p.period + 1)
    
    
    def next(self):
    
        HH = max(self.data.high.get(-1, size=self.p.period))
        LC = min(self.data.close.get(-1, size=self.p.period))
        HC = max(self.data.close.get(-1, size=self.p.period))
        LL = min(self.data.low.get(-1, size=self.p.period))
        R = max(HH-LC, HC-LL)
    
        self.lines.U[0] = self.data.open[0] + self.p.k_u * R
        self.lines.D[0] = self.data.open[0] - self.p.k_u * R
    

    class DualThrust(bt.SignalStrategy):

    def __init__(self):
        self.dataclose = self.data0.close
        self.D_Line = DT_Line(self.data1)
    
    
        self.D_Line = self.D_Line()
        self.D_Line.plotinfo.plot = True
        self.D_Line.plotinfo.plotmaster = self.data0 #  把图移到主图
    
        self.buy_signal = bt.indicators.CrossOver(self.dataclose, self.D_Line.U)
        self.sell_signal = bt.indicators.CrossDown(self.dataclose, self.D_Line.D)
    
    def start(self):
        print('这是start')
    
    def prenext(self):
        print('这是prenext')
    
    
    def next(self): # 核心就是这个next方法,本质是数据流
    
        if not self.position and self.buy_signal[0] == 1: # 如果没有持仓和上穿
            self.order = self.buy()
    
        if not self.position and self.sell_signal[0] == -1: # 下穿
            self.order = self.sell()
    
    
        if self.getposition().size < 0 and self.buy_signal[0] == 1:  # self.getposition().size < 0 有空头
            self.order = self.close()
            self.order = self.buy()
    
    
        if self.getposition().size > 0 and self.buy_signal[0] == -1:  # self.getposition().size > 0 有多头
            self.order = self.close()
            self.order = self.sell()
    
    
    def stop(self):  # 打印最优参数    self.broker.getvalue()是策略的净值
       self.log('period:%s,k_u:%s,k_d:%s,final_value:%.2f' %
            (self.p.period, self.p.k_u, self.p.k_d, self.broker.getvalue()), doprint=True)
    

    if name == 'main':

    # 初始化模型
    cerebro = bt.Cerebro()
    
    
    # 2.====== add data feed  添加数据 feed
    # 2.1 creat a data feed 创建数据
    
    data = bt.feeds.GenericCSVData(
        dataname=r'D:\xbxsp\xbx-coin-2020_part3\adaira\EOS-USDT_15m.csv',
        # dataname=dataframe,  D:\adaira\EOS-USDT_15m.h5
        fromdate=datetime.datetime(2020, 12, 1, 0, 0, 0),
        todate=datetime.datetime(2021, 1, 4, 0, 0, 0),
        timeframe=bt.TimeFrame.Minutes, # 告诉框架我们用的是分钟线
        dtformat='%Y-%m-%d %H:%M:%S',
        datetime=1,
        open=2,
        high=3,
        low=4,
        close=5,
        volume=6
    )
    
    # 2.2 add the data feed to cerebro 将数据提要添加到脑
    cerebro.adddata(data)
    cerebro.resampledata(data, timeframe=bt.TimeFrame.Days)
    
    
    # 3. add strategy  添加策略
    # cerebro.addstrategy(DualThrust,)   # optstrategy
    
    cerebro.optstrategy(
                        DualThrust,   # 遍历最优参数 下面的的可视化模块需要注释
                        period=range(1, 7),
                        k_u=[n/10.0 for n in range(2, 10)],
                        k_d=[n/10.0 for n in range(2, 10)]
                        )
    
    
    
    
    # 设定初始资金和佣金
    cerebro.broker.setcash(1000000.0)
    cerebro.broker.setcommission(0.005)
    
    # 策略执行前的资金
    print('启动资金: %.2f' % cerebro.broker.getvalue())
    
    # 4. run 策略执行
    cerebro.run()
    
    
    # 5.plot result  绘图结果
    # cerebro.plot(style='candle')# 可视化


});