How to compute the exponential moving average with Pandas using Python
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
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:
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Related Articles
Continue your learning journey with these related topics
Master Data Science in Days, Not Months 🚀
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚