PeaBox Lab › PeaLang › Learn › Chapter 18 › Lesson 2

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:

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.

WindowIncludesWeightsTypical use
RollingThe last k rows or last durationEqual7-day average, 30-day volatility
ExpandingAll rows from the start to nowEqualRunning total, year-to-date average, all-time high
Exponentially weightedAll history, in principleDecaying with ageSmoothed 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:

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

Guided practice

Hands-on lab: An anomaly monitor for daily orders

Review questions

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.

← Previous Next →