python - 移动平均线交叉的错误结果
问题描述
我有一个具有以下值的数据框。当低点低于 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
解决方案
只需添加另一个条件np.where
:
df['crossover'] = np.where(df['today'] & (df['yesterday'] == df['today']),True,True)
推荐阅读
- swiftui - SwiftUI:onDelete 无法正确更新 UI
- python - 对于高索引值,numpy 数组中的索引很慢
- bluetooth-lowenergy - 如何从 HESTA 智能手环中提取温度值
- c# - 如何用另一个表中的数据为一个表做种
- python - sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1062, "Duplicate entry '' " for key ""
- python - “手动”抛出的异常在 PowerShell ISE 中捕获,但不在命令行中
- python - 使用 unittest 框架测试 pandas 数据框
- performance - 我可以依赖 Google Lighthouse 报告(尤其是对于移动网站)吗?
- python - 我正在为这个 python 代码苦苦挣扎(我是初学者)
- javascript - 如何正确注释缓存的mixin