Rolling window feature

Also known as: rolling statistics feature

On this page 7

A rolling window feature is an input variable computed by applying a summary statistic to a fixed number of the most recent observations of a time series, recalculated at every time step as the window slides forward. In Time series & forecasting, rolling means, rolling standard deviations and rolling extremes are among the most widely used temporal features for machine learning models.

Rolling window features, also called rolling statistics features, compress recent history into a few stable numbers. They let models such as gradient-boosted trees, which have no built-in memory of time, see the current level, trend and volatility of a series without receiving every past value.

How a rolling window feature is computed

A rolling window feature is computed by choosing a window length w, collecting the w observations that end at or before a reference time, and applying an aggregation function to them. As the reference time moves forward by one step, the oldest value leaves the window and the newest enters, so the feature forms a smooth, continuously updated series.

The critical design rule is strict alignment with the forecast origin. A feature used to predict time t may only contain values available before the prediction is made. In practice the window is usually shifted by at least one step, or by the full forecast horizon in a direct forecasting setup, to prevent target leakage.

The table below shows a rolling mean and a rolling maximum with a window of three days, shifted by one day so that each value uses only past data.

DayDaily salesRolling mean (3, shifted)Rolling max (3, shifted)
1120Not availableNot available
2135Not availableNot available
3128Not availableNot available
4150127.7135
5142137.7150
Three-day rolling features shifted by one day

Common aggregation functions and window types

Each aggregation function describes a different property of recent behavior. Combining several functions over several window lengths is standard practice, because short windows react quickly while long windows capture slow trends and seasonal levels.

AggregationWhat it capturesTypical use
Rolling meanLocal levelDemand and traffic forecasting
Rolling medianRobust local levelSeries with outliers or spikes
Rolling standard deviationVolatilityRisk, energy load, finance
Rolling minimum and maximumRecent extremesCapacity and peak planning
Rolling sumAccumulated volumeRainfall, transaction counts
Rolling quantilesDistribution shapeProbabilistic forecasting inputs
Aggregations used in rolling window features

Window types also differ. A fixed-length window uses the same number of steps everywhere. A time-based window, such as the last 7 days, handles irregular timestamps. An expanding window grows from the start of the series, and an exponentially weighted window gives recent points more weight through a decay parameter instead of a hard cutoff.

Rolling window features complement other temporal features rather than replacing them. A lag feature passes a single past value to the model, while a rolling feature aggregates many past values into one number that is less sensitive to noise.

Feature typeInformation providedMain weakness
Rolling window featureSmoothed recent level or spreadLags behind sudden changes
Lag featureExact past valueNoisy and single-point
Expanding window featureLong-run historyDominated by old data
Exponentially weighted featureRecency-weighted levelDecay rate needs tuning
Calendar featuresDay, week, holiday positionNo information on recent values
Fourier termsSmooth seasonal cyclesNo reaction to recent shocks
Rolling features and neighboring feature types

Deep forecasters such as recurrent networks and the Temporal Fusion Transformer can learn similar summaries internally, yet explicit rolling features still often help, particularly with limited data and in global forecasting models trained on many series at once.

Choosing window lengths in practice

Window lengths should follow the natural periodicities and decision cycles of the data. Daily retail data commonly uses windows of 7, 14, 28 and 91 days, which align with weekly seasonality and monthly or quarterly patterns, while hourly load data uses 24 and 168 hours.

Data frequencyCommon windowsReason
Hourly6, 24, 168 hoursIntraday, daily and weekly cycles
Daily7, 28, 91 daysWeekly seasonality and monthly level
Weekly4, 13, 52 weeksMonth, quarter and year
Monthly3, 6, 12 monthsQuarter, half-year and annual cycle
Typical window choices by data frequency

Selection should be validated with time series cross-validation, using rolling-origin splits rather than random splits. Adding dozens of windows rarely helps; a small, well-chosen set of three to five windows per statistic usually captures most of the value.

Pitfalls and limitations

The most serious pitfall is data leakage from an unshifted window, which includes the target value itself and produces unrealistically good validation scores. Leakage also appears when rolling features are computed on the full dataset before the train-test split, or when the shift is shorter than the forecast horizon.

  • Warm-up gaps: the first w minus one rows have no complete window and need a clear handling policy.
  • Missing timestamps: count-based windows silently span longer periods when data is missing.
  • Lag behind turning points: long windows respond slowly to structural breaks.
  • Recursive forecasting drift: rolling features built from predicted values accumulate errors over the horizon.
  • Group mixing: windows must be computed per series, never across series boundaries.

In multi-step forecasting, each horizon may require its own shifted version of the features. Libraries such as pandas, sktime and many feature stores provide rolling operations, but correct alignment remains the responsibility of the practitioner.

Stripped to the essentials

A rolling window feature looks at the last few values of something and sums them up in one number. For example, it can take the average sales of the last seven days. Tomorrow it drops the oldest day and adds the newest one.

This is like checking how a store has been doing this past week instead of only yesterday. One day can be odd. A week tells a steadier story. Prediction models use these numbers to understand the recent mood of the data. The one strict rule is simple: never include the day being predicted.

Where it is applied

A grocery chain forecasts daily demand for 12,000 products across 300 stores, 14 days ahead, with a single gradient-boosted model. The data team builds rolling means over 7, 28 and 91 days, a 28-day rolling standard deviation and a 7-day rolling maximum, all shifted by 14 days so that every feature is known at the forecast date.

Compared with a model that used only lag features and calendar features, the rolling features reduce the weighted absolute percentage error by several percentage points on rolling-origin validation. The largest gains appear for slow-moving items with noisy daily sales, where a single lag value had been almost useless, and store managers report fewer empty shelves for those products.