使用Pandas计算指数加权移动平均(EWMA)遇到问题
Hey there! I’ve run into this exact confusion before with Pandas’ EWMA function—let’s break down why your results might not match the recursive formula you’re expecting.
The Culprit: adjust=True (Default Behavior)
Pandas’ ewm() method uses adjust=True by default, which changes how the EWMA is calculated compared to the recursive formula you referenced:
ewm(t+1) = alpha * price + (1-alpha) * ewm(t)
When adjust=True, Pandas computes the EWMA as a weighted average of all prior values rather than using the incremental recursive update. For example, for the nth data point, it calculates:
ewm(n) = (x0*(1-alpha)^n + x1*(1-alpha)^(n-1) + ... + xn) / sum_{k=0}^n (1-alpha)^k
This differs from the step-by-step recursive approach you’re expecting, which is why your manual checks might not line up.
Fixing the Calculation
To get the recursive EWMA behavior you want, simply add adjust=False to your ewm() call:
df = m1["open"].ewm(min_periods=9, span=9, adjust=False).mean()
Quick Confirmation
Let’s make sure the alpha value aligns with your formula: with span=9, Pandas calculates alpha = 2/(span+1) = 0.2, which matches exactly what you’re using. The min_periods=9 setting also works as intended—it ensures we only start computing the EWMA once we have at least 9 data points, so the first 8 values will return NaN as expected.
Manual Verification Tip
If you want to double-check, grab the first 9 price values and compute the EWMA step-by-step using your recursive formula. The 9th value (0-based index 8) from the adjusted Pandas code should match this manual calculation perfectly.
内容的提问来源于stack exchange,提问作者Erlinska

