Exponentially Weighted Moving Average
Apply exponential smoothing to give recent values more weight with ewm(span=), a standard technique in financial analysis.
The Problem with Simple Moving Averages
A simple moving average treats all n observations in the window equally — a price from 30 days ago contributes the same as yesterday's price. But for predicting near-term values, recent observations are more informative than old ones. An Exponentially Weighted Moving Average (EWMA) solves this by assigning exponentially decreasing weights to older observations: yesterday counts the most, the day before counts slightly less, and so on back to the beginning of the series.
import pandas as pd
import numpy as np
np.random.seed(42)
prices = pd.Series(
100 + np.cumsum(np.random.normal(0.5, 2, 30)),
index=pd.date_range('2024-01-01', periods=30)
)
df = pd.DataFrame({'price': prices})
df['SMA_7'] = df['price'].rolling(7).mean()
df['EWM_span7'] = df['price'].ewm(span=7).mean()
print(df.tail(5).round(2))How EWMA Weighting Works
EWMA computes each value as a weighted combination of the current observation and the previous EWMA: EWM_t = alpha * x_t + (1 - alpha) * EWM_{t-1}. The alpha (smoothing factor) determines how quickly weights decay — a large alpha (close to 1) responds quickly to recent changes (less smoothing), a small alpha (close to 0) is slow to respond (more smoothing). The weights form a geometric series: the most recent value has weight alpha, the previous has alpha*(1-alpha), and so on.
import numpy as np
# Manually show EWMA weights
alpha = 0.3
n_points = 8
weights = [alpha * (1 - alpha)**i for i in range(n_points)]
print(f'Alpha = {alpha}')
print(f'Weights (most recent first):')
for i, w in enumerate(weights):
print(f' t-{i}: {w:.4f}')
print(f'Sum of shown weights: {sum(weights):.4f} (converges to 1.0)')All lessons in this course
- Rolling Windows
- Expanding Windows
- Exponentially Weighted Moving Average
- Rank and Percentile within Groups