ewm Method¶
The ewm() method computes exponentially weighted statistics, where recent observations have more influence than older ones.
Basic EWM¶
Create exponentially weighted calculations.
1. EWMA (Exponentially Weighted Moving Average)¶
import pandas as pd
import yfinance as yf
aapl = yf.download('AAPL', start='2023-01-01', end='2024-01-01')
aapl['EWMA_10'] = aapl['Close'].ewm(span=10, adjust=False).mean()
print(aapl[['Close', 'EWMA_10']].head(10))
2. EWM Standard Deviation¶
aapl['EWMA_Std'] = aapl['Close'].ewm(span=10).std()
3. EWM Variance¶
aapl['EWMA_Var'] = aapl['Close'].ewm(span=10).var()
Weight Parameters¶
Control the decay of weights.
1. span¶
# Specify decay in terms of "center of mass"
s.ewm(span=10).mean() # Roughly equivalent to 10-period window
# alpha = 2 / (span + 1)
2. halflife¶
# Time for weight to decay to half
s.ewm(halflife=5).mean()
3. alpha¶
# Direct smoothing factor (0 < alpha <= 1)
s.ewm(alpha=0.1).mean() # Lower alpha = more smoothing
EWMA Formula¶
How exponentially weighted mean is calculated.
1. Recursive Formula¶
When adjust=False:
\[\text{EWMA}_t = (1 - \alpha) \cdot \text{EWMA}_{t-1} + \alpha \cdot x_t\]
2. Alpha from Span¶
\[\alpha = \frac{2}{\text{span} + 1}\]
3. Example Calculation¶
# With span=10: alpha = 2/11 ≈ 0.182
# Recent observation gets 18.2% weight
# Previous EWMA gets 81.8% weight
EWM vs Rolling¶
Compare EWM to simple rolling average.
1. Weight Distribution¶
# Rolling: equal weights within window
# EWM: exponentially decaying weights
2. Responsiveness¶
# EWM responds faster to recent changes
# Rolling has more lag
3. Visual Comparison¶
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(10, 6))
aapl['Close'].plot(ax=ax, label='Price', alpha=0.5)
aapl['Close'].rolling(20).mean().plot(ax=ax, label='SMA(20)')
aapl['Close'].ewm(span=20).mean().plot(ax=ax, label='EWMA(20)')
ax.legend()
plt.show()
Financial Applications¶
EWM in financial analysis.
1. EWMA Volatility¶
import numpy as np
returns = aapl['Close'].pct_change()
aapl['EWMA_Volatility'] = returns.ewm(span=20).std() * np.sqrt(252)
2. Fast vs Slow¶
# Trading signal: fast EWMA crosses slow EWMA
aapl['EWMA_Fast'] = aapl['Close'].ewm(span=12).mean()
aapl['EWMA_Slow'] = aapl['Close'].ewm(span=26).mean()
aapl['Signal'] = aapl['EWMA_Fast'] > aapl['EWMA_Slow']
3. Risk Management¶
# EWMA responds quickly to volatility spikes
aapl['Risk'] = returns.ewm(span=10).std()
adjust Parameter¶
Control bias correction.
1. adjust=True (Default)¶
# Divides by decaying adjustment factor
# More accurate but slower to compute
s.ewm(span=10, adjust=True).mean()
2. adjust=False¶
# Pure recursive formula
# Faster, commonly used in finance
s.ewm(span=10, adjust=False).mean()
3. Difference¶
The difference is most noticeable at the beginning of the series.