用python写个backtrader股票回测示例,并考虑手续费、滑点、资金管理
时间: 2023-06-15 08:07:40 浏览: 167
好的,下面是一个backtrader股票回测示例,考虑手续费、滑点、资金管理:
```python
import backtrader as bt
class MyStrategy(bt.Strategy):
params = (
('sma_period', 15),
('atr_period', 14),
('atr_multiplier', 2),
('commission', 0.001),
('slippage', 0.001),
('initial_capital', 100000),
)
def __init__(self):
self.sma = bt.indicators.SimpleMovingAverage(
self.data.close, period=self.params.sma_period)
self.atr = bt.indicators.ATR(
self.data.high, self.data.low, self.data.close,
period=self.params.atr_period)
self.position_size = None
def next(self):
if self.position:
if self.data.close[0] < self.sma[0]:
self.close()
else:
if self.data.close[0] > self.sma[0] + \
self.params.atr_multiplier * self.atr[0]:
self.position_size = self.params.initial_capital * \
self.params.risk / self.atr[0]
self.buy(size=self.position_size)
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, Size: %.2f, Price: %.2f, Cost: %.2f, Comm: %.2f' %
(order.executed.size, order.executed.price,
order.executed.value, order.executed.comm))
self.position_size = order.executed.size
else:
self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm: %.2f' %
(order.executed.price, order.executed.value,
order.executed.comm))
self.position_size = None
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log('Order Canceled/Margin/Rejected')
def notify_trade(self, trade):
self.log('Trade Profit/Loss: %.2f' % trade.pnl)
if __name__ == '__main__':
cerebro = bt.Cerebro()
cerebro.addstrategy(MyStrategy, risk=0.01)
data = bt.feeds.YahooFinanceData(
dataname='AAPL',
fromdate=datetime.datetime(2010, 1, 1),
todate=datetime.datetime(2020, 12, 31))
cerebro.adddata(data)
cerebro.broker.setcash(100000)
cerebro.broker.setcommission(commission=self.params.commission,
margin=0, mult=1)
cerebro.broker.set_slippage_fixed(
size=self.params.slippage, price=None)
cerebro.run()
```
这个策略使用了SMA和ATR指标来进行交易决策。如果当前没有持仓且价格上穿SMA加上ATR乘以一个倍数,则进行买入;如果当前持仓且价格下穿SMA,则进行卖出。其中,ATR用于计算每次交易的头寸大小。
在`notify_order`方法中,我们输出了每次交易的成本和手续费,用于计算总体的交易成本。在`notify_trade`方法中,我们输出了每次交易的盈亏情况。
在主程序中,我们使用了YahooFinanceData作为数据源,设置了回测时间和初始资金,并设置了手续费、滑点等交易参数。回测时,我们将risk参数设置为0.01,表示每次交易风险不超过总资金的1%。
阅读全文