前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Backtrader量化平台教程(二):Strategy类

Backtrader量化平台教程(二):Strategy类

作者头像
钱塘小甲子
发布2019-01-28 15:01:24
2K0
发布2019-01-28 15:01:24
举报

AD:(本人录制的backtrader视频课程,大家多多支持哦~ https://edu.csdn.net/course/detail/9040

上次我们分析了回测平台大的框架,这次着重介绍一下策略的编写。先来看一个策略的类,上次说了,一个策略其实被一个类完全描述了。

代码语言:javascript
复制
# Create a Stratey
class TestStrategy(bt.Strategy):

    def log(self, txt, dt=None):
        ''' Logging function fot this strategy'''
        dt = dt or self.datas[0].datetime.date(0)
        print('%s, %s' % (dt.isoformat(), txt))

    def __init__(self):
        # Keep a reference to the "close" line in the data[0] dataseries
        self.dataclose = self.datas[0].close

    def next(self):
        # Simply log the closing price of the series from the reference
        self.log('Close, %.2f' % self.dataclose[0])

        if self.dataclose[0] < self.dataclose[-1]:
            # current close less than previous close

            if self.dataclose[-1] < self.dataclose[-2]:
                # previous close less than the previous close

                # BUY, BUY, BUY!!! (with all possible default parameters)
                self.log('BUY CREATE, %.2f' % self.dataclose[0])
                self.buy()

        既然是类,那么肯定要initiation,策略类当然也一样。这里,我们的初始化函数就是获取了一个数据而已。这个数据的来源就是我们喂给框架的DataFeed。

       这里初始化的数据是一个很重要的东西,是一个heartbeat。什么叫做heartbeat呢?就是一个时间基准,在strategy类中,当我们获取下标为0的数据的时候,表示的是当前的数据,而-1则是前一时刻,一次类推。既然有了时间线,那么怎么走呢?所以我们有一个next方法,这个方法写的其实就是整个策略的核心部分了,就是你要判断什么时候买股票,什么时候卖股票,卖多少,买多少。这个方法,顾名思义,就是每次一天的数据使用完,就会被cerbero调用,所以叫做next。

这样,整个基本的框架就搭建完毕了。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年03月20日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档