Part III — Advanced Systems · Chapter 18 · Lesson 2 of 7 · 7 min read
Lesson 2: Rolling, Expanding, and Exponentially Weighted Statistics
Lesson level: Advanced
Purpose: Summarize recent history with moving windows so that noise is reduced, trends become visible, and each row carries context about its neighbourhood in time.
Learning objectives
By the end of this lesson you will be able to:
- distinguish rolling, expanding, and exponentially weighted windows
- choose between row-count and time-based windows
- set minimum-period rules so early rows are not misleading
- compute rolling means, sums, standard deviations, minimums, and maximums
- use rolling statistics to flag anomalies with z-scores
- avoid look-ahead bias by aligning windows correctly
2.1 Three kinds of window
Every window statistic answers the question "what does recent history look like from this row?" The three kinds differ in how much history they include and how they weight it.
| Window | Includes | Weights | Typical use |
|---|---|---|---|
| Rolling | The last k rows or last duration | Equal | 7-day average, 30-day volatility |
| Expanding | All rows from the start to now | Equal | Running total, year-to-date average, all-time high |
| Exponentially weighted | All history, in principle | Decaying with age | Smoothed level that reacts quickly to change |
2.2 Rolling windows
A rolling window of size 7 on a daily series covers the current day and the six before it. Rolling means smooth day-to-day noise; rolling standard deviations measure recent volatility; rolling minimums and maximums show recent range.
Illustrative listing.
roll = (daily
.sort("date")
.with_column("rev_ma7", col("revenue").rolling_mean(window=7, min_periods=7))
.with_column("rev_sd28", col("revenue").rolling_std(window=28, min_periods=14))
.with_column("rev_max28", col("revenue").rolling_max(window=28, min_periods=1)))
Row-count or time-based windows. A window of "7 rows" equals "7 days" only when the series has exactly one row per day. With gaps, a 7-row window can stretch over two weeks. Prefer time-based windows (for example 7d) on irregular data, or regularize the series first as in Lesson 1.
Minimum periods. The first rows of a rolling window have fewer observations than the window size. A 28-day standard deviation computed from three values is noise. Set a minimum-period rule that returns null until enough data exists, and choose it according to the statistic: a mean is usable earlier than a standard deviation.
Centred versus trailing windows. A centred window uses future values (three days before and three after for a 7-day centred mean). Centred windows are fine for describing history in a chart but must never be used as forecasting features, because they leak the future. Default to trailing windows.
2.3 Expanding windows
An expanding window starts at the first row and grows by one row each step. Expanding sums are running totals; expanding maximums are "highest so far"; expanding means are cumulative averages. They are useful for year-to-date reporting and for features such as "days since the all-time high".
Illustrative listing.
ytd = (daily
.with_column("year", col("date").year())
.sort(["year", "date"])
.with_column("rev_ytd", col("revenue").cum_sum().over("year"))
.with_column("rev_high", col("revenue").cum_max()))
Expanding statistics must be reset at the correct boundary. A year-to-date total that is not partitioned by year keeps growing across years. Reset by fiscal year when the business uses one, and document which calendar applies.
2.4 Exponentially weighted statistics
An exponentially weighted moving average (EWMA) gives the newest value the largest weight and lets older values fade geometrically. It is controlled by a smoothing factor α between 0 and 1:
levelt = α × valuet + (1 − α) × levelt−1
A large α (for example 0.5) reacts quickly and smooths little; a small α (for example 0.05) reacts slowly and smooths a lot. α is often expressed as a span s, where α = 2 / (s + 1), so a span of 7 behaves roughly like a 7-period moving average while reacting faster to recent change. A half-life h is another parameterization: the weight halves every h periods.
Illustrative listing.
smooth = (daily
.sort("date")
.with_column("rev_ewm7", col("revenue").ewm_mean(span=7, adjust=True))
.with_column("rev_ewm_sd", col("revenue").ewm_std(span=28)))
The adjust setting controls how the first few values are weighted. With adjustment, early values are normalized so the average is not biased toward the first observation; without it, the recursive formula above is applied directly. Choose one, document it, and keep it consistent between training and production, because the two give different numbers for the first part of the series.
2.5 Rolling anomaly detection
A rolling z-score compares today's value with the recent mean and standard deviation:
zt = (valuet − mean of previous k values) / standard deviation of previous k values
Note "previous": the window must end before the current row. Including today in its own baseline dampens every anomaly, because a spike raises both the mean and the standard deviation it is compared against. Shift the window by one period, or use a closed-left window.
base = col("revenue").shift(1)
flags = (daily
.sort("date")
.with_column("mu", base.rolling_mean(window=28, min_periods=14))
.with_column("sd", base.rolling_std(window=28, min_periods=14))
.with_column("z", (col("revenue") - col("mu")) / col("sd"))
.with_column("is_anomaly", col("z").abs() > 3))
Rolling z-scores assume roughly symmetric noise. Sales series are often skewed and strongly weekly. Two practical refinements are to compare each day with the same weekday over recent weeks, and to use the rolling median and median absolute deviation, which are less affected by the outliers you are trying to find.
2.6 Choosing window sizes
Window size is a trade-off between responsiveness and stability. Choose it from the rhythm of the data and the decision it supports, not by trial and error on a chart:
- Match the seasonal cycle: 7 days for daily retail data, 24 hours for hourly load, 12 months for monthly data. A window equal to the cycle length removes that seasonality from the average.
- Match the decision horizon: a weekly staffing decision needs a stable 4-week signal; an on-call alert needs a fast 1-hour signal.
- Use several windows when needed: a short and a long moving average together show both the current direction and the underlying level.
Record each window choice in the feature definition, with its reason. When a model is retrained, the windows must be identical, or yesterday's features and today's features measure different things.
2.7 Window statistics within groups
With many stores or products in one table, every window must be computed within its group. Sort by group and time, then apply the window over the group key. A window that crosses from the last day of store A into the first day of store B produces a plausible-looking but meaningless number, and nothing in the output warns you. A cheap safeguard is to check that the first min_periods − 1 rows of every group are null.
Common mistakes
- Including the current value in an anomaly baseline: shift the window so it ends before the row being scored.
- Using centred windows as features: they contain future values and leak.
- Row-count windows on gappy data: use time-based windows or regularize first.
- No minimum-period rule: early values look precise but are based on one or two points.
- Windows crossing group boundaries: always partition by the group key.
- Changing α, span, or adjustment between training and production: treat window parameters as part of the model contract.
Guided practice
- Plot daily revenue with a 7-day and a 28-day trailing mean and an EWMA with span 7. Describe how each reacts to a one-day spike and to a permanent step change.
- Compute a rolling z-score twice — once with the current day inside the window and once with it excluded — and compare the number of anomalies flagged.
- Compute 7-day means for two stores in one table without grouping, then with grouping. Find the rows that differ.
Hands-on lab: An anomaly monitor for daily orders
- Start from the validated daily table built in Lesson 1.
- Add 7-day and 28-day trailing means, a 28-day trailing standard deviation with a 14-day minimum, and an EWMA with span 7.
- Compute a same-weekday baseline: the median of the previous four values for the same weekday.
- Flag a day as anomalous when its z-score against the trailing window exceeds 3 and it differs from the same-weekday baseline by more than 30%.
- Produce a table of flagged days with the value, both baselines, and the reason, and compare it with known events such as promotions or outages.
Review questions
- How do rolling, expanding, and exponentially weighted windows differ?
- When is a row-count window not equal to a time-based window?
- Why is a minimum-period rule needed?
- Why must the baseline for an anomaly score exclude the current value?
- How does the span of an EWMA relate to α?
- Why are centred windows unsafe as forecasting features?
Applied challenge
An operations team receives about 40 false alerts a week from a fixed threshold on hourly support tickets. Replace the threshold with a rolling, weekday-and-hour-aware baseline. Evaluate the new rule on three months of history: how many alerts does it raise, and how many known incidents does it catch? Present the trade-off between sensitivity and alert volume for at least three threshold settings.
Lesson summary
Rolling windows describe recent history, expanding windows describe all history so far, and exponentially weighted windows describe history with fading memory. Use trailing, time-based windows with minimum-period rules, partition by group, keep the scored value out of its own baseline, and treat window parameters as part of the feature contract.
Transition to Lesson 3
Windows assume a reasonably complete series. Lesson 3 repairs gaps, compares groups, and separates a series into trend, seasonality, and remainder.
Lesson status: Ready for review.