1,从tushare上下在000001.SZ的交易数据,并加载到backtrader中。 参考: 【python量化交易学习】backtrader 加载tushare数据(从tushare或从excel获取交易数据)
2,运行backtrader进行回测。 参考:backtrader中文文档412
3,backtrader plot 出现错误的处理办法 ImportError: cannot import name ‘warnings‘ from ‘matplotlib.dates‘
代码:
from datetime import datetime
import backtrader as bt
import pandas as pd
import backtrader.feeds as btfeeds
class TestStrategy(bt.Strategy):
params = (
('maperiod', 15),
)
def log(self, txt, dt=None):
dt = dt or self.datas[0].datetime.date(0)
print('%s, %s' % (dt.isoformat(), txt))
def __init__(self):
self.dataclose = self.datas[0].close
self.order = None
self.buyprice = None
self.buycomm = None
self.sma = bt.indicators.SimpleMovingAverage(self.datas[0], period=self.params.maperiod)
bt.indicators.ExponentialMovingAverage(self.datas[0], period=25)
bt.indicators.WeightedMovingAverage(self.datas[0], period=25, subplot=True)
bt.indicators.StochasticSlow(self.datas[0])
bt.indicators.MACDHisto(self.datas[0])
rsi = bt.indicators.RSI(self.datas[0])
bt.indicators.SmoothedMovingAverage(rsi, period=10)
bt.indicators.ATR(self.datas[0], plot=False)
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(
'已买入, 价格: %.2f, 费用: %.2f, 佣金 %.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('已卖出, 价格: %.2f, 费用: %.2f, 佣金 %.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('订单取消/保证金不足/拒绝')
self.order = None
def notify_trade(self, trade):
if not trade.isclosed:
return
self.log('交易利润, 毛利润 %.2f, 净利润 %.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.sma[0]:
self.log('买入单, %.2f' % self.dataclose[0])
self.order = self.buy()
else:
if self.dataclose[0] < self.sma[0]:
self.log('卖出单, %.2f' % self.dataclose[0])
self.order = self.sell()
if __name__ == '__main__':
cerebro = bt.Cerebro()
cerebro.addstrategy(TestStrategy)
df_read = pd.read_excel('/Users/PycharmProjects/000001.xlsx', sheet_name="1", engine="openpyxl",
index_col=None)
df = df_read.iloc[::-1]
df.trade_date = pd.to_datetime(df.trade_date.apply(str))
data = btfeeds.PandasData(
dataname=df,
fromdate=datetime(2020, 2, 7),
todate=datetime(2022, 1, 1),
datetime='trade_date',
open='open',
high='high',
low='low',
close='close',
volume='vol',
openinterest=-1
)
cerebro.adddata(data)
cerebro.broker.setcash(1000000.0)
cerebro.addsizer(bt.sizers.FixedSize, stake=10000)
cerebro.broker.setcommission(commission=0.001)
print('组合期初资金: %.2f' % cerebro.broker.getvalue())
cerebro.run()
print('组合期末资金: %.2f' % cerebro.broker.getvalue())
cerebro.plot()
从tushare下载数据: 免费接口tushare注册地址
import os
import pandas as pd
import tushare as ts
pro = ts.pro_api('d437*****172')
df = pro.daily(**{
"ts_code": "000001.SZ",
"trade_date": "",
"start_date": "20200101",
"end_date": "20220101",
"offset": "",
"limit": ""
}, fields=[
"ts_code",
"trade_date",
"open",
"high",
"low",
"close",
"pre_close",
"change",
"pct_chg",
"vol",
"amount"
])
print(df)
path = '/Users/PycharmProjects/000001'
print (os.path.abspath('.'))
df.to_excel(path+'.xlsx',sheet_name='1',engine='openpyxl')
|