-1

I have been calculating the simple moving average of a stock using the code below:

def SMA(data, period =30, column='Close'):
    return data[column].rolling(window=period).mean()

df['SMA20']=SMA(df,20)
df['SMA50']=SMA(df,50)

How do I calculate the moving average for various stocks that are apart of the same data set? If I apply the above code then the moving average for the second or third stock in the row will be incorrect.

taylorSeries
  • 505
  • 2
  • 6
  • 18

1 Answers1

0

Can you try this, if this works for you

df = (
    df.fillna(0).groupby(["ticker_exchange"])[["price"]]
    .rolling(30)
    .corr().iloc[0::2,-1]
)
Kavi Harjani
  • 661
  • 5
  • 15