v8主要介绍如何自定义策略参数。
v8主要做了两处修改:
params = (
('exitbars', 5),
)
在使用时,可使用self.params.exitbars进行调用:
if len(self) >= (self.bar_executed + self.params.exitbars):
...
这里使用Python的元组(tuple)结构定义参数,如果需要自定义其他参数,可继续添加其他元组。例如,添加自定义参数myparam为27:
params = (
('exitbars', 5),
('myparam', 27),
)
cerebro.addsizer(bt.sizers.FixedSize, stake = 100)
这里按照A股的交易习惯,将交易单位设置为100股,即1手。从输出结果可以看出,买卖操作都是按1手进行的。
程序v8-自定义策略参数:
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import datetime # 用于datetime对象操作
import os.path # 用于管理路径
import sys # 用于在argvTo[0]中找到脚本名称
import backtrader as bt # 引入backtrader框架
# 创建策略
class TestStrategy(bt.Strategy):
params = (
('exitbars', 5),
)
def log(self, txt, dt=None):
''' 策略的日志函数'''
dt = dt or self.datas[0].datetime.date(0)
print('%s, %s' % (dt.isoformat(), txt))
def __init__(self):
# 引用data[0]数据的收盘价数据
self.dataclose = self.datas[0].close
# 用于记录订单状态
self.order = None
self.buyprice = None
self.buycomm = None
def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
# 提交给代理或者由代理接收的买/卖订单 - 不做操作
return
# 检查订单是否执行完毕
# 注意:如果没有足够资金,代理会拒绝订单
if order.status in [order.Completed]:
if order.isbuy():
self.log(
'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price,
order.executed.value,
order.executed.comm))
self.buyprice = order.executed.price
self.buycomm = order.executed.comm
else: # 卖
self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price,
order.executed.value,
order.executed.comm))
self.bar_executed = len(self)
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log('Order Canceled/Margin/Rejected')
# 无等待处理订单
self.order = None
def notify_trade(self, trade):
if not trade.isclosed:
return
self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
(trade.pnl, trade.pnlcomm))
def next(self):
# 日志输出收盘价数据
self.log('Close, %.2f' % self.dataclose[0])
# 检查是否有订单等待处理,如果是就不再进行其他下单
if self.order:
return
# 检查是否已经进场
if not self.position:
# 还未进场,则只能进行买入
# 当日收盘价小于前一日收盘价
if self.dataclose[0] < self.dataclose[-1]:
# 前一日收盘价小于前前日收盘价
if self.dataclose[-1] < self.dataclose[-2]:
# 买买买
self.log('BUY CREATE, %.2f' % self.dataclose[0])
# 记录订单避免二次下单
self.order = self.buy()
# 如果已经在场内,则可以进行卖出操作
else:
# 卖卖卖
if len(self) >= (self.bar_executed + self.params.exitbars):
self.log('SELL CREATE, %.2f' % self.dataclose[0])
# 记录订单避免二次下单
self.order = self.sell()
# 创建cerebro实体
cerebro = bt.Cerebro()
# 添加策略
cerebro.addstrategy(TestStrategy)
# 先找到脚本的位置,然后根据脚本与数据的相对路径关系找到数据位置
# 这样脚本从任意地方被调用,都可以正确地访问到数据
modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
datapath = os.path.join(modpath, '../TQDat/day/stk/000001.csv')
# 创建价格数据
data = bt.feeds.GenericCSVData(
dataname = datapath,
fromdate = datetime.datetime(2019, 10, 1),
todate = datetime.datetime(2020, 2, 29),
nullvalue = 0.0,
dtformat = ('%Y-%m-%d'),
datetime = 0,
open = 1,
high = 2,
low = 3,
close = 4,
volume = 5,
openinterest = -1
)
# 在Cerebro中添加价格数据
cerebro.adddata(data)
# 设置启动资金
cerebro.broker.setcash(100000.0)
# 设置交易单位大小
cerebro.addsizer(bt.sizers.FixedSize, stake = 100)
# 设置佣金为千分之一
cerebro.broker.setcommission(commission=0.001)
# 打印开始信息
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
# 遍历所有数据
cerebro.run()
# 打印最后结果
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
v8输出为:
Starting Portfolio Value: 100000.00
2019-10-08, Close, 16.20
2019-10-09, Close, 16.25
…
2020-01-15, BUY CREATE, 16.52
2020-01-16, BUY EXECUTED, Price: 16.52, Cost: 1652.00, Comm 1.65
2020-01-16, Close, 16.33
2020-01-17, Close, 16.39
2020-01-20, Close, 16.45
2020-01-21, Close, 16.00
2020-01-22, Close, 16.09
2020-01-23, Close, 15.54
2020-01-23, SELL CREATE, 15.54
2020-02-03, SELL EXECUTED, Price: 13.99, Cost: 1652.00, Comm 1.40
2020-02-03, OPERATION PROFIT, GROSS -253.00, NET -256.05
2020-02-03, Close, 13.99
2020-02-03, BUY CREATE, 13.99
2020-02-04, BUY EXECUTED, Price: 14.05, Cost: 1405.00, Comm 1.41
2020-02-04, Close, 14.60
Final Portfolio Value: 99891.97
为了便于相互交流学习,新建了微信群,感兴趣的读者请加微信。