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']

未完待续!

相关推荐
nuclear20111 小时前
使用Python 在Excel中创建和取消数据分组 - 详解
python·excel数据分组·创建excel分组·excel分类汇总·excel嵌套分组·excel大纲级别·取消excel分组
Lucky小小吴1 小时前
有关django、python版本、sqlite3版本冲突问题
python·django·sqlite
GIS 数据栈2 小时前
每日一书 《基于ArcGIS的Python编程秘笈》
开发语言·python·arcgis
爱分享的码瑞哥2 小时前
Python爬虫中的IP封禁问题及其解决方案
爬虫·python·tcp/ip
傻啦嘿哟3 小时前
如何使用 Python 开发一个简单的文本数据转换为 Excel 工具
开发语言·python·excel
B站计算机毕业设计超人3 小时前
计算机毕业设计SparkStreaming+Kafka旅游推荐系统 旅游景点客流量预测 旅游可视化 旅游大数据 Hive数据仓库 机器学习 深度学习
大数据·数据仓库·hadoop·python·kafka·课程设计·数据可视化
IT古董4 小时前
【人工智能】Python在机器学习与人工智能中的应用
开发语言·人工智能·python·机器学习
湫ccc4 小时前
《Python基础》之pip换国内镜像源
开发语言·python·pip
hakesashou4 小时前
Python中常用的函数介绍
java·网络·python
菜鸟的人工智能之路4 小时前
极坐标气泡图:医学数据分析的可视化新视角
python·数据分析·健康医疗