import backtrader as bt
import yfinance as yf
# 定义布林带交易策略
class BollingerBandsStrategy(bt.Strategy):
params = (
('period', 20),
('devfactor', 2)
)
def __init__(self):
self.bbands = bt.indicators.BollingerBands(period=self.params.period, devfactor=self.params.devfactor)
self.order = None
def next(self):
if self.order:
return
if self.data.close[0] > self.bbands.lines.top[0]:
if self.position.size == 0:
commission_info = self.broker.getcommissioninfo(self.data)
cash = self.broker.get_cash() - commission_info.getsize(1, self.data.close[0])
size = cash // self.data.close[0]
self.buy(size=size)
print(f'BUY: {size} shares')
elif self.data.close[0] < self.bbands.lines.bot[0]:
if self.position.size > 0:
size = self.position.size
self.close(size=size)
print(f'SELL: {size} shares')
def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
return
if order.status in [order.Completed]:
if order.isbuy():
print(f'BUY executed at {self.data.num2date(order.executed.dt).date()}, Price: {order.executed.price:.2f}, Cost: {order.executed.value:.2f}, Comm: {order.executed.comm:.2f}')
elif order.issell():
cost = order.executed.value
profit = order.executed.value - order.created.size * order.created.price
profit_percent = (profit / cost) * 100
print(f'SELL executed at {self.data.num2date(order.executed.dt).date()}, Price: {order.executed.price:.2f}, Cost: {cost:.2f}, Profit: {profit:.2f}, Profit %: {profit_percent:.2f}%')
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
print('Order Canceled/Margin/Rejected')
# 创建Cerebro引擎
cerebro = bt.Cerebro()
# 设置初始资金
cerebro.broker.setcash(100000.0)
# 下载苹果股票数据
data = yf.download('AAPL', '2020-01-01', '2023-12-30')
data = data.dropna()
# 将数据添加到Cerebro引擎中
data = bt.feeds.PandasData(dataname=data)
cerebro.adddata(data)
# 添加MACD策略
cerebro.addstrategy(BollingerBandsStrategy)
# 设置佣金为0.1%
cerebro.broker.setcommission(commission=0.001)
# 添加分析指标
cerebro.addanalyzer(bt.analyzers.Returns, _name='returns')
cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='sharpe')
cerebro.addanalyzer(bt.analyzers.DrawDown, _name='drawdown')
# 运行回测
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
results = cerebro.run()
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
# 获取回测结果
strat = results[0]
returns = strat.analyzers.returns.get_analysis()
sharpe = strat.analyzers.sharpe.get_analysis()
drawdown = strat.analyzers.drawdown.get_analysis()
# 打印回测指标
print('Annualized Return: %.2f%%' % (returns['rnorm100']))
print('Sharpe Ratio: %.2f' % (sharpe['sharperatio']))
print('Max Drawdown: %.2f%%' % (drawdown['max']['drawdown']))
print('Max Drawdown Period: %s' % (drawdown['max']['len']))
# 绘制回测结果
cerebro.plot()
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
《量化交易入门(二十九)布林带指标实现和回测》配套源码 原文地址:https://blog.csdn.net/benshu_001/article/details/137157606 代码使用backtrader 进行回测,历史数据是使用苹果股票的历史数据。 代码执行的结果: Starting Portfolio Value: 100000.00 Final Portfolio Value: 173356.80 Annualized Return: 14.78% Sharpe Ratio: 0.60 Max Drawdown: 27.17% Max Drawdown Period: 373 Max Drawdown Period: 441
资源推荐
资源详情
资源评论
收起资源包目录
Examples16.zip (1个子文件)
Examples16
examples16_1.py 3KB
共 1 条
- 1
资源评论
Coder加油!
- 粉丝: 1844
- 资源: 21
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功