首页 > 解决方案 > 移动平均线交叉的错误结果

问题描述

我有一个具有以下值的数据框。当低点低于 SMA8Low 时,我想计算日期。

  df['SMA10High'] = df.loc[:,'High'].rolling(window=10).mean()
  df['SMA8Low'] = df.loc[:,'Low'].rolling(window=8).mean()
  df['yesterday'] = df['Low'].shift(1) >= df['SMA8Low'].shift(1) #yesterdays 
  LOW >= SMA8Low
  df['today'] = df['Low'] <= df['SMA8Low']  #Todays Low <= SMA8Low
  df.dropna(inplace=True) #droping NaN values

上述代码后的数据帧结果如下:

数据框

现在,如果昨天为真而今天为真,则新列交叉应该为真。

我尝试了以下代码:

df['crossover'] = np.where(df['yesterday'] == df['today'],True,False)
#df['crossover'] = np.where(df['today'] & (df['yesterday'] == 
df['today']),True,True)

在此处输入图像描述

但结果是错误的。列交叉中只有以下日期应为 True:2021-01-08 和 2021-01-22

标签: pythonpandasdataframe

解决方案


只需添加另一个条件np.where

df['crossover'] = np.where(df['today'] & (df['yesterday'] == df['today']),True,True)

推荐阅读