用python写一个用backtrader库的RSI均线量化回测,数据从tushare获取
时间: 2024-03-21 12:41:20 浏览: 95
好的,以下是一个简单的用backtrader库的RSI均线量化回测,数据从tushare获取的Python代码。请确保你已经安装了backtrader和tushare库。
```python
import backtrader as bt
import tushare as ts
class RSI_Moving_Average(bt.Strategy):
params = (('rsi_period', 14), ('ma_period', 30), ('printlog', False))
def log(self, txt, dt=None, doprint=False):
if self.params.printlog or doprint:
dt = dt or self.datas[0].datetime.date(0)
print('%s, %s' % (dt.isoformat(), txt))
def __init__(self):
self.rsi = bt.indicators.RSI_SMA(self.data.close, period=self.params.rsi_period)
self.sma = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.ma_period)
def next(self):
if not self.position:
if self.rsi < 30:
self.buy()
else:
if self.rsi > 70:
self.sell()
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))
else:
self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price, order.executed.value, order.executed.comm))
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log('Order Canceled/Margin/Rejected')
def notify_trade(self, trade):
if not trade.isclosed:
return
self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' % (trade.pnl, trade.pnlcomm))
if __name__ == '__main__':
cerebro = bt.Cerebro()
# 获取数据
data = ts.get_k_data('000001', start='2010-01-01', end='2021-01-01')
data = bt.feeds.PandasData(dataname=data)
cerebro.adddata(data)
# 添加策略
cerebro.addstrategy(RSI_Moving_Average)
# 设定初始资金和手续费
cerebro.broker.setcash(100000.0)
cerebro.broker.setcommission(commission=0.002)
# 运行回测
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.run()
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
```
这个策略是基于RSI和移动平均线的交叉进行交易的。当RSI低于30时,策略会买入股票,当RSI高于70时,策略会卖出股票。回测数据来自于tushare的历史数据,回测结果将会输出到控制台,包括每次交易的成本和收益。
阅读全文