Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

python - Wrong result with moving average cross over

I have a dataframe with the following values. I want to dedect dates, when the Low is crossing below the 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

Dataframe result after the above code is the following:

Dataframe

Now the new column crossing should only be True, if yesterday is true and today is true.

I tried the following code:

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

enter image description here

But the result is wrong. Only the following dates should be True in the column crossover: 2021-01-08 and 2021-01-22

question from:https://stackoverflow.com/questions/65847773/wrong-result-with-moving-average-cross-over

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just add another condition to np.where:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...