Quant notes · 02 · interactive

Volatility estimation by EWMA

The exponentially weighted moving average assigns weights to past observations that decay geometrically with age. Applied to squared returns it gives the volatility estimate used to size positions in the backtester. This page states the weighting, the formulas, the volatility estimator and its alternatives, and its place in the backtest. Labs use simulated series.

All series on this page are simulated so the "true" answer is known. Nothing here is market data or a performance claim.

1 · Simple and exponentially weighted averages

A simple moving average looks back a fixed number of days and gives each of them the same vote. Day 20 counts as much as yesterday; day 21 counts for nothing. That sharp edge is unnatural: a market does not suddenly forget what happened three weeks ago.

An EWMA gives every past day a vote, but each day's vote shrinks by a fixed factor the further back it is. Yesterday counts most, the day before a bit less, and so on forever. There is no edge, only a smooth fade. One number, λ (lambda, "the memory"), sets how fast the fade is.

Worked example, four days of returns: 1%, 2%, 3%, 4% (4% is yesterday). Simple window of 4. Every day gets a 25% vote. Average = 0.25·4 + 0.25·3 + 0.25·2 + 0.25·1 = 2.5%. EWMA with λ = 0.5. Votes shrink by half each day back: 53%, 27%, 13%, 7% (newest first, scaled to add to 100%). Average = 0.53·4 + 0.27·3 + 0.13·2 + 0.07·1 = 3.3%. The EWMA answer sits closer to yesterday's 4% because yesterday got the biggest vote. The chart below draws exactly these votes, for 120 days instead of four.

Lab A · How much does each past day count?

weights · illustrative

This chart shows no prices or returns. It shows the recipe. Each bar is one past day (yesterday on the left, older to the right). Bar height is that day's vote: what share of the final average comes from that day. Each colour's bars add up to 100%.

EWMA: each bar is 94% of the one before it (at λ = 0.94), never reaching zeroSimple average: equal bars inside the window, nothing outside it
11.1half-life, days (weight halves)
15.7centre of mass, days ("average age" of the data)
6.0%yesterday's share of the total
1.4%share still held by days older than 60

Try λ = 0.94: that is the value RiskMetrics made famous for daily data. Try λ = 0.985: that is roughly a 60-day centre of mass, the setting used in the time-series momentum paper (note 01).

2 · Formulas

EWMAt = λ · EWMAt−1 + (1 − λ) · xt

"Today's average is λ parts of yesterday's average plus (1 − λ) parts of today's new observation." You never store the history. You keep one number and nudge it each day. Blue is the share kept from the past; orange is the share given to the newest point. The two always add to 1.

Unrolling that recursion shows where the name comes from. Each old observation ends up multiplied by λ raised to its age:

EWMAt = (1 − λ) · [ xt + λ xt−1 + λ2 xt−2 + λ3 xt−3 + … ]
EWMAt = (1 − λ) · Σi = 0, 1, 2, … λi · xt−i

The second line is the first written compactly: Σ means "add up for every i", where i is how many days back the observation is. The weights 1, λ, λ², λ³ … are a geometric series. Multiplying by (1 − λ) makes them sum to exactly one, so it is a true weighted average. The weight is an exponential function of age, hence "exponentially weighted".

Three ways to say the same λ, which you will meet in code and papers:

half-life = ln(½)ln(λ)
centre of mass = λ1 − λ
α = 1 − λ

Half-life: after this many days, a data point has lost half its weight. Centre of mass: the weighted average age of the data being used. α (alpha): the share given to the newest point, the same orange quantity as above. All four describe one fade; pick whichever reads most naturally.

3 · Volatility estimation

Volatility is the typical size of a day's move, ignoring direction. A market that moves ±0.5% a day is calm; one that moves ±3% a day is wild. You cannot observe volatility directly. You estimate it from recent returns.

The recipe is: square each daily return (so up and down moves both count as "movement"), average the squares, take the square root. The only question is which average.

→Use a simple average of squared returns over a window and you get rolling realised volatility, the plain rolling(N).std().
→Use an EWMA of squared returns and you get EWMA volatility, the RiskMetrics estimator.
σ2t = λ · σ2t−1 + (1 − λ) · r2t−1
σannual = √σ2t · √252

"Today's variance estimate is λ parts yesterday's estimate plus (1 − λ) parts yesterday's squared return." Note the t−1 on the return: the estimate for today uses only returns you had already seen. The second line turns it into the number people quote: square root to get back from variance to volatility, then √252 (trading days in a year) to state it per year.

Lab B · Which estimator tracks a change in volatility faster?

simulated · not market data

The simulated market is calm, then turns wild on day 200, then calms down on day 350. Because it is simulated, the true volatility is known (grey band). Watch how long each estimator takes to catch up, and how noisy each is while it waits.

How to read the two charts Top strip: the raw returns, one thin line per day. Up = the market rose that day, down = it fell, length = size of the move. Your eye can already see that days 200–350 have longer lines. That impression is what "volatility" measures. Bottom chart: the estimators' day-by-day answer to "how volatile is it right now?", in % per year. Grey band = the true setting (12%, 45%, 18%). You never see this in real life; it is here only to grade the estimators. Blue = EWMA's guess. Orange = rolling window's guess. Each day's guess uses only the returns already seen. Four things to try: (1) at day 200 the truth jumps; count the days until each line gets near it. (2) with a 60-day window, orange climbs in a straight ramp because one more wild day enters the window each day. (3) at day 350 blue falls at once, while orange waits until the wild days leave its window and then drops in a cliff around day 410, when nothing happened in the market. (4) set λ = 0.85 and window = 10: both react fast, but now look at days 0–200 where nothing changes. The wiggle you see there is the price of fast reaction.
true vol (known because simulated)EWMA volrolling-window vol
–EWMA: average gap to the grey band, in percentage points
–rolling: average gap to the grey band, in percentage points
–EWMA: days after day 200 to get 80% of the way to 45%
–rolling: days after day 200 to get 80% of the way to 45%
What to notice.Short memory (low λ, small window) reacts fast but jitters. Long memory is smooth but late. There is no free lunch; you are choosing where on that trade-off to sit. The rolling window also has a second problem: when a wild day finally falls out of the window, the estimate drops suddenly, for no economic reason. EWMA never does that.

4 · Volatility estimators

EWMA is one branch of a bigger tree. Click any box to see what it is, what it needs, and when people use it.

5 · Position in the backtest

A backtest is a pipeline. Volatility enters at one specific step, and the step right after it is where most beginners' backtests silently cheat. Click a step for the detail.

Click a step. The explanation appears beside it.

6 · Implementation

pandas has EWMA built in as .ewm(). It accepts the fade in any of the four spellings from section 2. Type a half-life and see the others.

half-life (days)
λ (lambda)0.939
alpha = 1 − λ0.061
com = λ/(1−λ)15.4
span = 2/α − 131.8

Any one of halflife=, alpha=, com=, span= fully specifies the same fade. Pass exactly one.

# r is a pandas Series of daily returns, oldest first
# three ways to write the same EWMA volatility (λ ≈ 0.94)
vol_a = r.ewm(halflife=11).std()
vol_b = r.ewm(alpha=0.06).std()
vol_c = r.ewm(com=15.7).std()

# quoted per year, and lagged one day so today's size uses
# only returns that were already known this morning
sigma = (vol_a * 252 ** 0.5).shift(1)

# the plain rolling version, for comparison
sigma_roll = (r.rolling(60).std() * 252 ** 0.5).shift(1)

Default pandas .ewm().std() applies a small bias correction (bias=False) and centres on the mean, so it will not match the RiskMetrics recursion to the last decimal. For sizing positions the difference is irrelevant; for reproducing a paper, pass bias=True and apply it to r**2 instead.

In this project

How the xau-btc-models backtester spells it.This page uses λ = 0.94 and √252, the stock-market conventions from the RiskMetrics document. The project's realised_vol uses r.ewm(span=30, adjust=False).std() * sqrt(365): span 30 is λ ≈ 0.935, almost the same fade, and 365 because the daily table has one row per calendar day (bitcoin trades every day; gold is forward-filled over weekends and frozen by a tradable mask). The lag is applied once to the whole target, pos = target.shift(1), which includes the volatility inside it, rather than to σ on its own. Same protection, one place.

7 · Failure modes

All three are versions of the same error: letting a decision in the past use a number that only existed later.

Using today's move to decide today's trade.In a backtest you decide the size of Monday's trade using the volatility number. If that number already includes Monday's return, you are using a move that had not happened yet when the decision was made. In real life you could never do that. In a backtest it is easy to do by accident, and it makes the results look better than any real trader could achieve.Fix: compute the volatility, then push it one day later with .shift(1), so Monday's trade uses Friday's number.
One volatility number for all ten years.Taking the standard deviation of the entire history, one number, and using it to size every trade from the first day to the last. The trades in 2015 are then sized with information from 2026. Same problem as above, on a larger scale.Fix: the volatility must be recomputed every day from the days before it. Rolling or EWMA, never one number for the whole sample.
Daily numbers mixed with yearly ones.Volatility is usually quoted per year, but it is computed from daily returns. Converting between the two means multiplying by the square root of the number of trading days in a year, √252 ≈ 15.9. Compare a daily number to a yearly target without converting, or use 365 for a market that trades 252 days, and every position ends up the wrong size.Fix: decide once whether you work in daily or yearly units, and convert everything to it before dividing.

8 · Terminology

Each entry: the technical definition first, then the same idea in everyday words in the orange strip.

returntoday's price ÷ yesterday's − 1. A 1% rise is 0.01.how much you made or lost in one day, as a percentage. Gold at 100 yesterday and 101 today is a return of 1%.
volatility (σ)standard deviation of returns: the typical size of a move. Quoted per year by convention.how jumpy the market is. A calm market moves a little each day, a volatile one swings a lot. It says nothing about direction, only size.
variance (σ²)volatility squared. Easier to average, which is why the recursion runs on squares.the same "jumpiness" idea, but squared so that up and down moves do not cancel each other out when you average them. Take the square root to get back to volatility.
realised volvolatility measured from returns that actually happened, as opposed to implied vol, which is what option prices expect.how jumpy the market actually was, measured after the fact from the moves that happened. "Implied" vol is instead a guess about the future, read off option prices.
λ, half-life, com, αfour spellings of how fast the EWMA forgets. See section 2.four dials that all set the same thing: how quickly old days stop mattering. Half-life is the easiest to picture: "after this many days, a day's vote has shrunk to half."
look-ahead biasusing information in a backtest that was not available at the time. The most common reason a backtest looks too good.accidentally letting your test "see tomorrow's newspaper". Any result built that way is fiction, however good it looks.
vol targetingchoosing position size so that each trade carries the same expected risk: size = target ÷ σ.bet smaller when the market is jumpy and bigger when it is calm, so that every bet risks about the same amount of money.
RiskMetricsa 1990s J.P. Morgan risk method that popularised λ = 0.94 for daily EWMA volatility.a bank's published rule book from the 1990s. Its choice of λ = 0.94 became the default everyone copies.
GARCHan EWMA for variance with one extra term pulling the estimate back toward a long-run level.an EWMA that also remembers what "normal" looks like, so after a wild patch it expects things to drift back to normal rather than staying wild forever.

Companion to note 01 (time-series momentum), where the same EWMA, with a 60-day centre of mass, sizes every position.

Sources

RiskMetricsJ.P. Morgan / Reuters, RiskMetrics Technical Document, 4th ed., 1996. The origin of the EWMA variance recursion and the λ = 0.94 daily default (ch. 5).
CarverR. Carver, Systematic Trading, Harriman House, 2015. Volatility targeting and position sizing by recent volatility (ch. 9–10); why the estimate should be fast-moving.
Moskowitz et al.T. Moskowitz, Y. H. Ooi, L. H. Pedersen, "Time Series Momentum", Journal of Financial Economics 104 (2012). Positions scaled by an EWMA volatility with a 60-day centre of mass (section 2).
Parkinson; Garman–KlassM. Parkinson, "The Extreme Value Method for Estimating the Variance of the Rate of Return", Journal of Business 53 (1980); M. Garman and M. Klass, "On the Estimation of Security Price Volatilities from Historical Data", Journal of Business 53 (1980). Range-based estimators in section 4.
Andersen et al.T. Andersen, T. Bollerslev, F. Diebold, P. Labys, "Modeling and Forecasting Realized Volatility", Econometrica 71 (2003). Intraday realised variance.
BollerslevT. Bollerslev, "Generalized Autoregressive Conditional Heteroskedasticity", Journal of Econometrics 31 (1986). GARCH(1,1).
pandaspandas.Series.ewm documentation: the four equivalent spellings com, span, halflife, alpha, and the adjust and bias switches.

All charts on this page are generated from simulated series inside the page; no market data is used. Part of quant-notes. See also 01 · Time-series momentum, 03 · Backtest errors and controls and Backtester implementation.