技术老师您好,我利用均线 RSI 还有MACD 三指标共振编写的代码系统识别不了,请老师帮忙改进优化一下可以吗 ```python import backtrader as bt; import pandas as pd; import talib; # 定义策略 class OptimizedStrategy(bt.Strategy): params = ( ('sma_period_short', 5), ('sma_period_long', 20), ('rsi_period', 14), ('atr_period', 14), ('stop_loss_multiplier', 2), ('trail_offset', 10), ('vix_threshold', 20), ('position_size', 0.01), # 每笔交易的资金比例 ); def __init__(self): self.sma_short = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.sma_period_short); # 短期SMA self.sma_long = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.sma_period_long); # 长期SMA self.rsi = bt.indicators.RSI(self.data.close, period=self.params.rsi_period); # RSI指标 self.atr = bt.indicators.ATR(self.data.high, self.data.low, self.data.close, period=self.params.atr_period); # ATR指标 self.vix = self.data1.close; # VIX指数数据 self.order = None; # 当前订单状态 def log(self, txt): ''' Logging function for this strategy''' dt = self.datas[0].datetime.date(0).isoformat(); # 获取日期 print(f'{dt}, {txt}'); # 打印日志 def next(self): if self.order: return; # 如果有未完成的订单,则不执行任何操作 if self.vix[0] > self.params.vix_threshold: return; # 高波动时段不交易 if not self.position: # 开多条件 if (self.sma_short[0] > self.sma_long[0]) and (self.rsi[0] < 30) and (self.data.close[0] > self.data.open[0]): size = int(self.broker.getvalue() * self.params.position_size / self.data.close[0]); # 计算买入数量 self.buy(size=size); # 买入 self.stop_loss = self.data.close[0] - self.atr[0] * self.params.stop_loss_multiplier; # 设置止损 # 开空条件 elif (self.sma_short[0] < self.sma_long[0]) and (self.rsi[0] > 70) and (self.data.close[0] < self.data.open[0]): size = int(self.broker.getvalue() * self.params.position_size / self.data.close[0]); # 计算卖出数量 self.sell(size=size); # 卖出 self.stop_loss = self.data.close[0] + self.atr[0] * self.params.stop_loss_multiplier; # 设置止损 else: # 止损检查 if self.position.size > 0: # 多头仓位 if self.data.close[0] <= self.stop_loss: self.log(f'STOP OUT, {self.data.close[0]:.2f}'); # 记录日志 self.close(); # 平仓 elif self.position.size < 0: # 空头仓位 if self.data.close[0] >= self.stop_loss: self.log(f'STOP OUT, {self.data.close[0]:.2f}'); # 记录日志 self.close(); # 平仓
|