backtrader是一个优秀的量化测试框架,但是无法实战环境各种特殊的需求,例如仓位管理、交易信息管理等。冰山量化系统是基于backtrader进行二次开发以满足与实战需求。案例是基于tick数据进行实时模拟交易。
# -*- coding: utf-8 -*-
"""
***冰山量化交易系统***
Created on Wed Jun 10 12:00:56 2020
@作者: juexing2020
@微信号:sleeping2020
@博客:https://blog.csdn.net/dreamchina8888
@网站地址:www.juexing2020.com
"""
import datetime # For datetime objects
import backtrader as bt
from utilclient.reportutil import ReportUtil
from utilclient.fileutil import FileUtil
from feedsextend.csvtick import CSVTick
class TestStrategy(bt.Strategy):
'''
基于tick数据股票交易
'''
# 可配置策略参数
params = dict(
pstake = 100 # 单笔交易股票数目
)
def __init__(self):
self.open_price=self.datas[0].open
self.close_price=self.datas[0].close
self.current_price=self.datas[0].current_price
def next(self):
for i, d in enumerate(self.datas):
buy_price=0.0#买入价格
buy_size=0#买入股票数量
sell_price=0.0#卖出价格
sell_size=0#卖出股票数量
#当前价格大于昨天价格买入
if self.current_price[0]>self.close_price[-1]:
self.buy(data = d, size = self.p.pstake) # 买买买
buy_price=self.current_price[0]
buy_size=self.p.pstake
#仓位
pos = self.getposition(d)
if len(pos):
#当前价格小于等于昨天收盘价卖出
if self.current_price[0]<=self.close_price[-1]:
self.sell(data = d,size = self.p.pstake)
sell_price=self.current_price[0]
sell_size=self.p.pstake
trade_date=self.datas[0].datetime.datetime(0)
stock_code=d._name
#交易记录报告,输出到excel中
ReportUtil.tradeReport(trade_date,stock_code,buy_price,buy_size,sell_price,sell_size,pos)
def stop(self):
pass
#股票tick数据
#,id,datetime,close,high,low,open,volume,money,current_price,bid_buy_price,bid_sell_price,
#buy_volume1,buy_price1,buy_volume2,buy_price2,buy_volume3,buy_price3,buy_volume4,
#buy_price4,buy_volume5,buy_price5,sell_volume1,sell_price1,sell_volume2,sell_price2,
#sell_volume3,sell_price3,sell_volume4,sell_price4,sell_volume5,sell_price5
FileUtil.deleteFile('..\\report\\000002.sz.xls')
cerebro=bt.Cerebro()
datapath='..\\datas\\000002.sz.tick'
data=CSVTick(dataname=datapath,
fromdate = datetime.datetime(2020, 6, 1),
todate = datetime.datetime(2020, 9, 1),
nullvalue=0.0,
dtformat=('%Y-%m-%d %H:%M:%S'),
timeframe=bt.TimeFrame.Seconds,
datetime=2,
close=3,
high=4,
low=5,
open=6,
volume=7,
openinterest=-1,
current_price=9)
datatest=cerebro.adddata(data)
cerebro.addstrategy(TestStrategy)
cerebro.broker.set_cash(100000.0)
# 设置佣金为零
cerebro.broker.setcommission(commission=0.00)
cerebro.run(maxcpus = 1)
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
#cerebro.plot()