0
0
PandasHow-ToBeginner · 3 min read

How to Calculate Exponential Moving Average in pandas

You can calculate the exponential moving average in pandas using the ewm() method followed by mean(). This method applies exponential weights to the data, giving more importance to recent values.
📐

Syntax

The basic syntax to calculate the exponential moving average (EMA) in pandas is:

DataFrame.ewm(span=<window>, adjust=True).mean()

Here:

  • span controls the window size for the EMA.
  • adjust=True means weights are calculated using the entire history.
  • mean() computes the weighted average.
python
df['EMA'] = df['column_name'].ewm(span=10, adjust=True).mean()
💻

Example

This example shows how to calculate the EMA of a simple numeric series using pandas.

python
import pandas as pd

data = {'price': [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]}
df = pd.DataFrame(data)

df['EMA_3'] = df['price'].ewm(span=3, adjust=True).mean()
print(df)
Output
price EMA_3 0 10 10.000000 1 11 10.500000 2 12 11.250000 3 13 12.125000 4 14 13.062500 5 15 14.031250 6 16 15.015625 7 17 16.007812 8 18 17.003906 9 19 18.001953
⚠️

Common Pitfalls

Common mistakes when calculating EMA include:

  • Using rolling() instead of ewm(), which calculates a simple moving average, not exponential.
  • Not setting the span parameter correctly, which affects smoothing.
  • Confusing adjust=True and adjust=False, which changes how weights are applied.

Example of wrong vs right:

python
# Wrong: simple moving average
# df['SMA'] = df['price'].rolling(window=3).mean()

# Right: exponential moving average
# df['EMA'] = df['price'].ewm(span=3, adjust=True).mean()
📊

Quick Reference

Summary tips for EMA in pandas:

  • Use ewm() for exponential weighting.
  • span controls how fast weights decay.
  • adjust=True uses all data for weights; adjust=False uses recursive calculation.
  • Call mean() after ewm() to get EMA values.

Key Takeaways

Use pandas' ewm() method with mean() to calculate exponential moving average.
The span parameter controls the smoothing window size for EMA.
Adjust parameter changes how weights are calculated; adjust=True uses full history.
Do not confuse EMA with simple moving average calculated by rolling().
EMA gives more weight to recent data points, useful for trend analysis.