在前面的例子中使用策略的时候,没有什么参数可以调节测试。框架本身是支持参数的,使用起来也比较简单
参数的定义很简单,如下所示:
params = (('myparam', 27), ('exitbars', 5),)
使用了python基本的数据结构元组(tuple)。每个元组有2个元素。其中,第一个元素为参数的名称,第二个元为变量对应的值。用更直观的格式展示如下:
params = (
('myparam', 27),
('exitbars', 5),
)
除了开始赋值默认值,还可以在框架,增加策略的时候进行赋值,赋值下方法如下:
# Add a strategy
cerebro.addstrategy(TestStrategy, myparam=20, exitbars=7)
下面实现一个通过设置参数,来实现参数指定多个少几交易日后清仓的案例,持股5天就清仓:
# -*- coding: utf-8 -*-
"""
backtrader手册样例代码
@author: 一块自由的砖
"""
#############################################################
#import
#############################################################
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os,sys
import pandas as pd
import backtrader as bt
#############################################################
#global const values
#############################################################
#############################################################
#static function
#############################################################
#############################################################
#class
#############################################################
# Create a Stratey
class TestStrategy(bt.Strategy):
params = (
('exitbars', 5),
)
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
# To keep track of pending orders and buy price/commission(价格、佣金)
self.order = None
self.buyprice = None
self.buycomm = None
def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
# Buy/Sell order submitted/accepted to/by broker - Nothing to do
return
# Check if an order has been completed
# Attention: broker could reject order if not enough cash
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
elif order.issell():
# 实际发生卖单的价格,成本,佣金
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')
# Write down: no pending order
self.order = None
def notify_trade(self, trade):
if not trade.isclosed:
return
# 一次卖出后交易完成后的收益情况: gross 毛利 net 净/纯利
self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
(trade.pnl, trade.pnlcomm))
def next(self):
# Simply log the closing price of the series from the reference(调用日志方法,显示收盘价)
self.log('Close, %.2f' % self.dataclose[0])
# Check if an order is pending ... if yes, we cannot send a 2nd one
if self.order:
return
# Check if we are in the market(检查是否持股)
if not self.position:
# 判定当前交易日的收盘价是否小于昨日的
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!!! 购买动作,创建买单,给买入价
self.log('BUY CREATE, %.2f' % self.dataclose[0])
# Keep track of the created order to avoid a 2nd order
self.order = self.buy()
else:
# Already in the market ... we might sell,持股检查是否已经大于5个交易日
if len(self) >= (self.bar_executed + self.params.exitbars):
# SELL, SELL, SELL!!! (with all possible default parameters)
self.log('SELL CREATE, %.2f' % self.dataclose[0])
# Keep track of the created order to avoid a 2nd order
self.order = self.sell()
#############################################################
#global values
#############################################################
#############################################################
#global function
#############################################################
# 通过读取cvs文件,获取想要的数据
def get_dataframe():
# Get a pandas dataframe(这里是股票数据文件放的目录路径)
datapath = 'qtbt\data\stockinfo.csv'
# 数据转换用临时文件路径和名称,用完后删除
tmpdatapath = datapath + '.tmp'
print('-----------------------read csv---------------------------')
dataframe = pd.read_csv(datapath,
skiprows=0,
header=0,
parse_dates=True,
index_col=0)
# 定义交易日期格式
dataframe.trade_date = pd.to_datetime(dataframe.trade_date, format="%Y%m%d")
# 原始cvs数据有很多列,这里组织需要使用的数据列,生成目标数据的tmp数据文件后,读取需要的数据
dataframe['openinterest'] = '0'
feedsdf = dataframe[['trade_date', 'open', 'high', 'low', 'close', 'vol', 'openinterest']]
feedsdf.columns =['datetime', 'open', 'high', 'low', 'close', 'volume', 'openinterest']
# 按照交易日期升序排列
feedsdf.set_index(keys='datetime', inplace =True)
# 生成临时文件
feedsdf.iloc[::-1].to_csv(tmpdatapath)
# 获取需要使用的数据
feedsdf = pd.read_csv(tmpdatapath, skiprows=0, header=0, parse_dates=True, index_col=0)
# 删除tmp临时文件
if os.path.isfile(tmpdatapath):
os.remove(tmpdatapath)
print(tmpdatapath+" removed!")
# 返回需要的数据
return feedsdf
########################################################################
#main
########################################################################
if __name__ == '__main__':
# Create a cerebro entity(创建cerebro)
cerebro = bt.Cerebro()
# Add a strategy(加入自定义策略,可以设置自定义参数,方便调节)
cerebro.addstrategy(TestStrategy)
# Get a pandas dataframe(获取dataframe格式股票数据)
feedsdf = get_dataframe()
# Pass it to the backtrader datafeed and add it to the cerebro(加入数据)
data = bt.feeds.PandasData(dataname=feedsdf)
# 加入数据到Cerebro
cerebro.adddata(data)
# Add a FixedSize sizer according to the stake(国内1手是100股,最小的交易单位)
cerebro.addsizer(bt.sizers.FixedSize, stake=100)
# Set our desired cash start(给经纪人,可以理解为交易所股票账户充钱)
cerebro.broker.setcash(100000.0)
# Set the commission - 0.1% ... divide by 100 to remove the %
cerebro.broker.setcommission(commission=0.001)
# Print out the starting conditions(输出账户金额)
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
# Run over everything(执行回测)
cerebro.run()
# Print out the final result(输出账户金额)
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
执行输出:
2021-09-14, Close, 9.21
2021-09-14, BUY CREATE, 9.21
2021-09-15, BUY EXECUTED, Price: 9.21, Cost: 921.00, Comm 0.92
2021-09-15, Close, 9.19
2021-09-16, Close, 9.12
2021-09-17, Close, 9.11
2021-09-22, Close, 9.03
2021-09-23, Close, 9.03
2021-09-24, Close, 9.02
2021-09-24, SELL CREATE, 9.02
2021-09-27, SELL EXECUTED, Price: 9.02, Cost: 921.00, Comm 0.90
2021-09-27, OPERATION PROFIT, GROSS -19.00, NET -20.82
2021-09-27, Close, 9.02
2021-09-28, Close, 9.03
2021-09-29, Close, 9.02
2021-09-30, Close, 9.00
2021-09-30, BUY CREATE, 9.00
Final Portfolio Value: 99734.77
2021-09-15买入, 2021-09-24 卖出