前言
过了一遍 Guidance 之后,发现该不会用还是不会用,主要是各种细节还不知道怎么修改。当然,这是正常现象,所以有必要再深入探究下 Guidance 的这些 Demo。这回会把每个 Demo 都进行变化实验,多问几个为什么。
正文
Demo 的代码就不往上贴了,所以以下内容请对照 Quickstart 文档 中的代码同步阅读。
Basic Setup
这个 Demo 主要展示如何引入 backtrader,以及最主要的 Cerebro
类,它是整个框架的「基石」,文档中如此描述:
This class is the cornerstone of
backtrader
because it serves as a central point for:
- Gathering all inputs (Data Feeds), actors (Stratgegies), spectators (Observers), critics (Analyzers) and documenters (Writers) ensuring the show still goes on at any moment.
- Execute the backtesting/or live data feeding/trading
- Returning the results
- Giving access to the plotting facilities
Setting the Cash
加了一句:
cerebro.broker.setcash(100000.0)
复制代码
其实很好理解,就是设置一下你的初始资金。值得注意的是这个 broker
,文档中的描述用百度翻译一下:
Broker Simulator
Simulator 支持不同的订单类型,根据当前现金检查提交的订单现金需求,跟踪 Cerbero 每次迭代的现金和价值,并在不同数据上保持当前位置。
虽然翻译的不算完全准确,但是大概也能够理解 broker 的作用了。
Adding a Data Feed
事情开始有意思起来了,开始有数据导入了,Demo 中多了如下代码:
# Datas are in a subfolder of the samples. Need to find where the script is
# because it could have been called from anywhere
modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
datapath = os.path.join(modpath, '../../datas/orcl-1995-2014.txt')
# Create a Data Feed
data = bt.feeds.YahooFinanceCSVData(
dataname=datapath,
# Do not pass values before this date
fromdate=datetime.datetime(2000, 1, 1),
# Do not pass values after this date
todate=datetime.datetime(2000, 12, 31),
reverse=False)
# Add the Data Feed to Cerebro
cerebro.adddata(data)
复制代码
代码很简单,可以看到,加载数据,主要是 feeds
对象来实现的,其文档中列举了能够解析的数据格式:
- Yahoo (online or already saved to a file)
- VisualChart (see www.visualchart.com)
- Backtrader CSV (own cooked format for testing)
- Generic CSV support
作为小白,笔者对这几种格式了解的不多,不过盲猜应该就是固定了顺序的 CSV。这里只需要会用即可,更深入的理解待后续再研究。
Our First Strategy
添加策略很简单,只需要一条命令即可:
cerebro.addstrategy(TestStrategy)
复制代码
最关键的还是 TestStrategy
类中的逻辑,我们重点看一下:
# Create a Stratey
class TestStrategy(bt.Strategy):
def log(self, txt, dt=None):
''' Logging function for 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])
复制代码
总共有 3 个方法,我们分别来看一下:
- log:顾名思义,就是一个专门打印 log 的函数,一般会在
next
方法中调用; - __init__:主要用来给
self
上初始化一些属性,方便next
中使用; - next:核心方法,所有策略的逻辑几乎都写在这里,后面也主要是扩展此方法。
值得注意的是,self.datas
属性是自带的,很明显是个数组,具体格式暂时还没在文档里找到,但可以肯定的是一定有 open
、high
、low
、close
、volume
这几个 key。
总结
为了保证阅读体验,本文先梳理到这,基本用法到这里基本就介绍完了,接下来就要开始添加买卖逻辑了。基本上就是在 next
当中写一些逻辑判断。TO BE CONTINUED……