# ===策略参数 # n代表取平均线和标准差的参数 # m代表标准差的倍数 n = int(para[0]) m = para[1] ma_n = para[2] # MA指标的参数 # ===计算指标 # 计算均线 df['median'] = df['close'].rolling(n).mean() # 此处只计算最后几行的均线值,因为没有加min_period参数 median = df.iloc[-1]['median'] median2 = df.iloc[-2]['median'] # 计算标准差 df['std'] = df['close'].rolling(n).std(ddof=0) # ddof代表标准差自由度,只计算最后几行的均线值,因为没有加min_period参数 std = df.iloc[-1]['std'] std2 = df.iloc[-2]['std'] # 计算上轨、下轨道 upper = median + m * std lower = median - m * std upper2 = median2 + m * std2 lower2 = median2 - m * std2 # ===计算MA指标 df['MA'] = df['close'].rolling(ma_n).mean() ma = df.iloc[-1]['MA'] ma2 = df.iloc[-2]['MA'] # ===寻找交易信号 signal = None close = df.iloc[-1]['close'] close2 = df.iloc[-2]['close'] # 找出做多信号 if (close > upper) and (close2 <= upper2) and (close > ma) and (close2 <= ma2): signal = 1 # 找出做空信号 elif (close < lower) and (close2 >= lower2) and (close < ma) and (close2 >= ma2): signal = -1 # 找出做多平仓信号 elif (close < median) and (close2 >= median2): signal = 0 # 找出做空平仓信号 elif (close > median) and (close2 <= median2): signal = 0 return signal以上代码加入波动率来过滤信号
时间: 2023-12-10 09:42:04 浏览: 98
Ecc.zip_site:www.pudn.com_椭圆曲线_椭圆曲线参数_求基点的阶
要加入波动率来过滤信号的话,可以在计算标准差时,将参数ddof设为1,这样计算得到的是无偏估计的标准差,再将上下轨道分别乘以一个波动率因子即可。具体实现如下:
```python
# 计算标准差,使用无偏估计
df['std'] = df['close'].rolling(n, min_periods=1).std(ddof=1)
# 计算上下轨道,加入波动率因子
volatility_factor = 2 # 波动率因子,可以根据实际情况调整
df['upper'] = df['median'] + volatility_factor * df['std']
df['lower'] = df['median'] - volatility_factor * df['std']
# 找出做多信号
if (close > upper) and (close2 <= upper2) and (close > ma) and (close2 <= ma2) and (std < volatility_factor * ma):
signal = 1
# 找出做空信号
elif (close < lower) and (close2 >= lower2) and (close < ma) and (close2 >= ma2) and (std < volatility_factor * ma):
signal = -1
```
这里假设波动率因子为2,如果标准差超过了2倍的移动平均值,就视为市场波动较大,此时不考虑交易信号。
阅读全文