打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

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

  1. # Create a Stratey  
  2. class TestStrategy(bt.Strategy):  
  3.   
  4.     def log(self, txt, dt=None):  
  5.         ''''' Logging function fot this strategy'''  
  6.         dt = dt or self.datas[0].datetime.date(0)  
  7.         print('%s, %s' % (dt.isoformat(), txt))  
  8.   
  9.     def __init__(self):  
  10.         # Keep a reference to the "close" line in the data[0] dataseries  
  11.         self.dataclose = self.datas[0].close  
  12.   
  13.     def next(self):  
  14.         # Simply log the closing price of the series from the reference  
  15.         self.log('Close, %.2f' % self.dataclose[0])  
  16.   
  17.         if self.dataclose[0] < self.dataclose[-1]:  
  18.             # current close less than previous close  
  19.   
  20.             if self.dataclose[-1] < self.dataclose[-2]:  
  21.                 # previous close less than the previous close  
  22.   
  23.                 # BUY, BUY, BUY!!! (with all possible default parameters)  
  24.                 self.log('BUY CREATE, %.2f' % self.dataclose[0])  
  25.                 self.buy()  
        既然是类,那么肯定要initiation,策略类当然也一样。这里,我们的初始化函数就是获取了一个数据而已。这个数据的来源就是我们喂给框架的DataFeed。

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

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




本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
使用Backtrader对股票历史数据进行指标回测
backtrader量化平台教程(二)第一个可用的策略
Backtrader 基本使用教程 — 量化投资实战教程(1)
backtrader源码解析_【大操手量化投资课堂源码解析】使用量化交易回测神器BackTrader初识,回测双均线策略!...
【策略】Dual Thrust 交易策略
(ok)python3 将print输出的内容保存到txt文件中
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服