前言
- 策略描述
日线
无持仓,收盘上穿20日均线买入(昨日低于20日均线,今日高于20日均线),买入
无持仓,收盘在20日之上,且相比昨天,低点(最低价)抬高,买入
有持仓,盈利回撤30%卖出
- (个人认为)backtrader不太友好的设计
当日:(观察)创建买、卖(单),次日:执行买、卖(单);backtrader的默认买卖规则
实际操作中,一天之内只观察信号,不交易,等第二天再交易,不太符合交易习惯
实操中的尾盘交易,14:55分买卖即可,如果很纠结这样对不对,可以划走
请注意,下面代码中的打印、注释非常重要,看注释!看注释!看注释!
backtrader到底要什么样(格式)的数据
#如果没有openinterest字段要增加一个,未平仓(合约)量,暂时没用到
df_kline_day['openinterest'] = 0.0
# 确保datetime字段是datetime类型
df_kline_day.set_index('datetime',inplace=True)
# 处理索引的类型
df_kline_day.index = pd.to_datetime(df_kline_day.index)
# 确保字段顺序正确
df_kline_day = df_kline_day[['open', 'high', 'low', 'close', 'volume','openinterest']]
实现尾盘买卖必须开启COC模式(Chip On Close)
# 设置初始资金为100万
cerebro.broker.setcash(1000000.0)
# 开启COC模式
cerebro.broker.set_coc(True)
策略类的创建及其初始化
注:由于backtrader官网的例子,策略类包含log函数的实现,所以日期相关的不少打印让人疑惑,甚至可以说是,坑了不少人,从这里开始,请注意查看,哪些没用使用self.log打印
class NewStrategy(bt.Strategy):
params = (
('maperiod', 20), # 20日均线
('printlog', True),
('trail_percent', 0.3), # 30%回撤
)
# 这个打印函数,对COC也就是 Chip On Close 或者 COO Chip on Open不友好
# 这里打印里取的时间 self.datas[0].datetime.date(0) 并不是交易的时间
def log(self, txt, dt=None, doprint=False):
''' Logging function fot this strategy'''
if self.params.printlog or doprint:
dt = dt or self.datas[0].datetime.date(0)
print('%s, %s' % (dt.isoformat(), txt))
def __init__(self):
# 初始化20日均线
self.sma = bt.indicators.SimpleMovingAverage(
self.datas[0], period=self.params.maperiod)
# 跟踪最高价
self.highest_high = -1 # 初始化为-1,确保可以比较
# 跟踪最低价
self.lowest_low = float('inf') # 初始化为无穷大,确保可以比较
# 记录前一个低点
self.order = None
self.prev_low = None
策略,创建买卖订单的实现,关键的 next(bar)
注意:当前持有现金计算满仓位买入的size
def next(self):
# Simply log the closing price of the series from the reference
#self.log('Close, %.2f' % self.data.close[0])
if self.order:
return
# Check if we are in the market
if not self.