import backtrader as bt
import yfinance as yf
# 定义BIAS指标
class BIAS(bt.Indicator):
lines = ('bias',)
params = (('period', 20),)
def __init__(self):
self.lines.bias = (self.data.close - bt.indicators.SMA(period=self.params.period)) / bt.indicators.SMA(period=self.params.period) * 100
# 定义交易策略
class BIASStrategy(bt.Strategy):
params = (('bias_upper', 10), ('bias_lower', -10),)
def __init__(self):
self.bias = BIAS(self.data)
self.order = None
def next(self):
if not self.position:
if self.bias[0] > self.params.bias_upper:
pass # 不进行操作
elif self.bias[0] < self.params.bias_lower:
commission_info = self.broker.getcommissioninfo(self.data)
cash = self.broker.get_cash()
size = int(cash / (self.data.close[0] * (1 + commission_info.p.commission)))
self.order = self.buy(size=size)
print(f'BUY: {size} shares')
else:
if self.order and self.order.isbuy() and self.bias[0] > self.params.bias_upper:
self.close()
self.order = None # 重置self.order为None
print(f'SELL: {self.position.size} shares')
elif self.order and self.order.issell() and self.bias[0] < self.params.bias_lower:
self.close()
self.order = None # 重置self.order为None
print(f'BUY: {self.position.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(BIASStrategy)
# 设置佣金为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()
Coder加油!
- 粉丝: 1w+
- 资源: 21
最新资源
- 笼养蛋鸡健康行为监测机器人系统研究
- 销售数据集,客户购买行为影响因素数据,38万多条数据(它包含了详细的客户人口统计信息、购买详情、忠诚度计划参与情况以及交易结果 该数据集非常适合用于分析客户行为、评估忠诚度计划和预测购买模式)
- 人体脉搏信号的采集与分析
- 汽车空调的太阳能供电控制系统的研究与设计
- 热封式自动包装机控制系统的设计与实现
- 设施农业自动灌溉控制器研发
- 体表汗液多参数电化学传感器及穿戴式检测装置的研制
- 松下FP7大型plc程序,一共18个电机,轴控制程序模块化,拿着就可以直接套用,整个程序结构清晰,注释完整,适合学习借鉴
- ThinkTemplate开发指南完整版PDF最新版本
- 分布式grade:IDL-DataWriter
- 可调谐石墨烯超材料吸收体FDTD仿真模拟 案例内容该案例提供了一种可调谐石墨烯超材料吸收体,其吸收光谱可以通过改变施加于石墨烯的化学势来进行调节 案例文件仿真源文件
- 测量工具,串口调试问问
- php8.x中文手册2023官方CHM版最新版本
- ThinkPHP5.0快速入门手册(新手教程版)中文离线版最新版本
- 十六进制文件源码编辑工具
- unity 自己使用的工具,用来做特殊效果
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈