Backtrader 文档学习-Strategy(下)

Backtrader 文档学习-Strategy(下)

1. 关于生存期测试

复制代码
class Test_Strategy(bt.Strategy):  
    # 策略通用初始参数
    params = (
        ('maperiod1', 5),
        ('maperiod2', 20),
        ('printlog', True),  # 写入日志标志
        ('logfilename', 'Test_Strategy.log'), # 日志文件名
        ('counter', 0), # 计数器
    )
    
    def __init__(self):  
        
        #Open, High, Low, Close, Volume
        
        self.dataopen = self.datas[0].open
        self.datahigh = self.datas[0].high
        self.datalow = self.datas[0].low
        self.dataclose = self.datas[0].close  
        self.datavol = self.datas[0].volume
        
        # 5 20 日均线
        self.sma5 = bt.indicators.SimpleMovingAverage(self.dataclose, period=self.params.maperiod1)  
        self.sma20 = bt.indicators.SimpleMovingAverage(self.dataclose, period=self.params.maperiod2)  

    # doprint 打印日志标志
    def log(self, txt, dt=None, doprint=False):
        ''' Logging function fot this strategy'''
        if self.params.printlog or doprint:
            dt = dt or self.datas[0].datetime.date(0)
            #print('%s, %s' % (dt.isoformat(), txt))
            with open(self.params.logfilename, 'a') as file:
                file.write('%s, %s' % (dt.isoformat(), txt))
                file.write('\n')

    def start(self):    
        # 从0 开始
        #self.params.counter += 1
        self.log('Test_Strategy start %s' % self.params.counter, doprint=True)
    
    def prenext(self):
        self.params.counter += 1
        self.log('Test_Strategy prenext  %s' % self.params.counter, doprint=True)
                
    def next(self):  
        # 最简单的策略,观察各个属性和方法
        if self.position:  
            self.close()  
        else:  
            if self.sma5 > self.sma20:  
                self.buy()  
            else:  
                self.sell()  
        
        self.params.counter += 1        
        self.log('Test_Strategy next %s' % self.params.counter, doprint=True)
        
        
    def stop(self):
        self.params.counter += 1        
        self.log('Test_Strategy stop  %s' % self.params.counter, doprint=True)
        self.log('(MA Period %2d) Ending Value %.2f' %
                 (self.params.maperiod1, self.broker.getvalue()), doprint=True)
        
        #最后打印所有属性和方法
        self.log(dir(self), doprint=True)
        
if __name__ == '__main__':
    
    # delete log file
    log_file = './Test_Strategy.log'
    delete_file(log_file)
    
    # 创建Cerebro引擎  导入2019-1-1 到 2019-3-31 三个月数据
    cerebro = declare_cerebar()

    cerebro.addstrategy(Test_Strategy)  
    cerebro.run()

说明:

  • start()时,数据是日期最末一天。3月29日。30 31日非交易日。

2019-03-29, Test_Strategy start 0

  • 2个周期,5天和20天,以最长的周期为准,执行prenext方法。

2019-01-29, Test_Strategy next 20

  • stop(),停止在日期的最末一天,3月29日。

输出结果:

复制代码
#cat Test_Strategy.log 
2019-03-29, Test_Strategy start 0
2019-01-02, Test_Strategy prenext  1
2019-01-03, Test_Strategy prenext  2
2019-01-04, Test_Strategy prenext  3
2019-01-07, Test_Strategy prenext  4
2019-01-08, Test_Strategy prenext  5
2019-01-09, Test_Strategy prenext  6
2019-01-10, Test_Strategy prenext  7
2019-01-11, Test_Strategy prenext  8
2019-01-14, Test_Strategy prenext  9
2019-01-15, Test_Strategy prenext  10
2019-01-16, Test_Strategy prenext  11
2019-01-17, Test_Strategy prenext  12
2019-01-18, Test_Strategy prenext  13
2019-01-21, Test_Strategy prenext  14
2019-01-22, Test_Strategy prenext  15
2019-01-23, Test_Strategy prenext  16
2019-01-24, Test_Strategy prenext  17
2019-01-25, Test_Strategy prenext  18
2019-01-28, Test_Strategy prenext  19
2019-01-29, Test_Strategy next 20
2019-01-30, Test_Strategy next 21
2019-01-31, Test_Strategy next 22
2019-02-01, Test_Strategy next 23
2019-02-11, Test_Strategy next 24
2019-02-12, Test_Strategy next 25
2019-02-13, Test_Strategy next 26
2019-02-14, Test_Strategy next 27
2019-02-15, Test_Strategy next 28
2019-02-18, Test_Strategy next 29
2019-02-19, Test_Strategy next 30
2019-02-20, Test_Strategy next 31
2019-02-21, Test_Strategy next 32
2019-02-22, Test_Strategy next 33
2019-02-25, Test_Strategy next 34
2019-02-26, Test_Strategy next 35
2019-02-27, Test_Strategy next 36
2019-02-28, Test_Strategy next 37
2019-03-01, Test_Strategy next 38
2019-03-04, Test_Strategy next 39
2019-03-05, Test_Strategy next 40
2019-03-06, Test_Strategy next 41
2019-03-07, Test_Strategy next 42
2019-03-08, Test_Strategy next 43
2019-03-11, Test_Strategy next 44
2019-03-12, Test_Strategy next 45
2019-03-13, Test_Strategy next 46
2019-03-14, Test_Strategy next 47
2019-03-15, Test_Strategy next 48
2019-03-18, Test_Strategy next 49
2019-03-19, Test_Strategy next 50
2019-03-20, Test_Strategy next 51
2019-03-21, Test_Strategy next 52
2019-03-22, Test_Strategy next 53
2019-03-25, Test_Strategy next 54
2019-03-26, Test_Strategy next 55
2019-03-27, Test_Strategy next 56
2019-03-28, Test_Strategy next 57
2019-03-29, Test_Strategy next 58
2019-03-29, Test_Strategy stop  59
2019-03-29, (MA Period  5) Ending Value 10016.50
2019-03-29, ['IndType', 'ObsType', 'PriceClose', 'PriceDateTime', 'PriceHigh', 'PriceLow', 'PriceOpen', 'PriceOpenInteres', 'PriceVolume', 'StratType', '_OwnerCls', '__abs__', '__add__', '__bool__', '__call__', '__class__', '__delattr__', '__dict__', '__dir__', '__div__', '__doc__', '__eq__', '__floordiv__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__len__', '__lt__', '__module__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pow__', '__radd__', '__rdiv__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__weakref__', '_addanalyzer', '_addanalyzer_slave', '_addindicator', '_addnotification', '_addobserver', '_addsizer', '_addwriter', '_alnames', '_clk_update', '_clock', '_dlens', '_getanalyzer_slave', '_getline', '_getminperstatus', '_id', '_lineiterators', '_ltype', '_makeoperation', '_makeoperationown', '_mindatas', '_minperiod', '_minperiods', '_minperstatus', '_next', '_next_analyzers', '_next_observers', '_next_open', '_nextforce', '_notify', '_oldsync', '_once', '_oncepost', '_oncepost_open', '_operation', '_operation_stage1', '_operation_stage2', '_operationown', '_operationown_stage1', '_operationown_stage2', '_opstage', '_orders', '_orderspending', '_owner', '_periodrecalc', '_periodset', '_plotinit', '_plotlabel', '_roperation', '_settz', '_sizer', '_slave_analyzers', '_stage1', '_stage2', '_start', '_stop', '_tradehistoryon', '_trades', '_tradespending', 'add_timer', 'addindicator', 'addminperiod', 'advance', 'alias', 'aliased', 'analyzers', 'array', 'backwards', 'bind2line', 'bind2lines', 'bindlines', 'broker', 'buy', 'buy_bracket', 'cancel', 'cerebro', 'clear', 'close', 'csv', 'data', 'data0', 'data0_0', 'data0_1', 'data0_2', 'data0_3', 'data0_4', 'data0_5', 'data0_6', 'data0_close', 'data0_datetime', 'data0_high', 'data0_low', 'data0_open', 'data0_openinterest', 'data0_volume', 'data1', 'data1_0', 'data1_1', 'data1_2', 'data1_3', 'data1_4', 'data1_5', 'data1_6', 'data1_close', 'data1_datetime', 'data1_high', 'data1_low', 'data1_open', 'data1_openinterest', 'data1_volume', 'data_0', 'data_1', 'data_2', 'data_3', 'data_4', 'data_5', 'data_6', 'data_close', 'data_datetime', 'data_high', 'data_low', 'data_open', 'data_openinterest', 'data_volume', 'dataclose', 'datahigh', 'datalow', 'dataopen', 'datas', 'datavol', 'ddatas', 'dnames', 'env', 'extend', 'forward', 'frompackages', 'getdatabyname', 'getdatanames', 'getindicators', 'getindicators_lines', 'getobservers', 'getposition', 'getpositionbyname', 'getpositions', 'getpositionsbyname', 'getsizer', 'getsizing', 'getwriterheaders', 'getwriterinfo', 'getwritervalues', 'home', 'incminperiod', 'l', 'line', 'line0', 'line_0', 'linealias', 'lines', 'log', 'minbuffer', 'next', 'next_open', 'nextstart', 'nextstart_open', 'notify_cashvalue', 'notify_data', 'notify_fund', 'notify_order', 'notify_store', 'notify_timer', 'notify_trade', 'observers', 'once', 'oncestart', 'order_target_percent', 'order_target_size', 'order_target_value', 'p', 'packages', 'params', 'plotinfo', 'plotlabel', 'plotlines', 'position', 'positionbyname', 'positions', 'positionsbyname', 'prenext', 'prenext_open', 'preonce', 'qbuffer', 'reset', 'rewind', 'sell', 'sell_bracket', 'set_tradehistory', 'setminperiod', 'setsizer', 'sizer', 'sma20', 'sma5', 'start', 'stats', 'stop', 'updateminperiod', 'writers']

未完待续!

相关推荐
郭庆汝3 小时前
pytorch、torchvision与python版本对应关系
人工智能·pytorch·python
思则变6 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
漫谈网络6 小时前
WebSocket 在前后端的完整使用流程
javascript·python·websocket
try2find8 小时前
安装llama-cpp-python踩坑记
开发语言·python·llama
博观而约取9 小时前
Django ORM 1. 创建模型(Model)
数据库·python·django
精灵vector10 小时前
构建专家级SQL Agent交互
python·aigc·ai编程
Zonda要好好学习10 小时前
Python入门Day2
开发语言·python
Vertira10 小时前
pdf 合并 python实现(已解决)
前端·python·pdf
太凉10 小时前
Python之 sorted() 函数的基本语法
python
项目題供诗11 小时前
黑马python(二十四)
开发语言·python