Calculating Exponential Moving Average (EMA) of Stock Prices
Python
Calculates the EMA over the previous 20 days for each day in a stock price dataset. The EMA metric is grouped by each stock in the dataset.
1| days = 20 2| df['ema_20'] = df.groupby(['stock'])['close'].transform(lambda x: x.ewm(span=days, 3| min_periods=0, 4| adjust=False, 5| ignore_na=True).mean())
133
121
116
109