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:
spancontrols the window size for the EMA.adjust=Truemeans 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 ofewm(), which calculates a simple moving average, not exponential. - Not setting the
spanparameter correctly, which affects smoothing. - Confusing
adjust=Trueandadjust=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. spancontrols how fast weights decay.adjust=Trueuses all data for weights;adjust=Falseuses recursive calculation.- Call
mean()afterewm()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.