How to compute the exponential moving average with Pandas using Python

1 min

Exponential moving averages are useful when you want to allocate more weight to more recent observations when you compute your average.

The DataFrame.ewm() method can be used to compute the exponential moving average.

The method will require you to pass the decay parameter. (com)

Enough talking,

Here is the code

# To work with dataframes
import pandas as pd

# To get the stock prices
import yfinance as yf

# We get the stock prices
df = yf.download("AAPL", start="2021-01-03")

# We compute the "20 days" exponential moving average
df["ema_20"] = df["Adj Close"].ewm(com=20).mean()

# We plot the ewm_20 along with the close price
df[["ema_20", "Close"]].plot(title="20 days exponential moving average on AAPL stock price")

The results

Here you are! You now know how to compute the exponential moving average with Pandas using Python.

More on financial analysis

If you want to know more about Financial Analysis in Python and avoid the headaches... check out the other articles I wrote by clicking just here:

Financial Analysis - The Python You Need
We gathered the only Python essentials that you will probably ever need.