How to compute the exponential moving average with Pandas using Python

7-Day Challenge

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.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

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.

7-Day Challenge

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.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

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. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.