advanced26 min studyLesson 833 in Engineering

Build lagged features around the forecast origin

Construct grouped temporal windows with explicit closure, availability checks, and transformation boundaries.

On this page

What you’ll understand

  • Translate an origin-based lag definition into a target-indexed table.
  • Compute a causal rolling aggregate.
  • Detect cross-entity, revision, and preprocessing leakage.

A feature named lag_1 sounds precise until two implementations disagree about its reference point. One means the value immediately before the prediction origin; another means one period before the target. For a six-step forecast, the second interpretation may include five future outcomes. Define lags using timestamps before generating a table. Then establish entity grouping, observation closure, usable-version eligibility, and preprocessing fit boundaries. These rules turn feature engineering from a sequence of convenient dataframe operations into a reproducible statement about the information the forecasting system is allowed to use.

Choose a row convention before shifting

For a regular discrete series, let origin t denote the latest period that is permitted as observed under the stated availability policy. A feature vector can contain values at t, t−1, and t−2 while its target is y at t+h. If the dataframe is indexed by target time s instead, the same most recent feature is y at s−h. A one-row shift is correct for one-step prediction under this convention, but it is not automatically correct for every horizon.

Group by the complete series identity before shifting: site, metric, and aggregation definition may all be needed. Sort within that group and resolve duplicate timestamps according to the version contract. A global shift over a table sorted by site can copy the final observation of one site into the first row of another. An apparently reasonable validation score cannot excuse this error; compare selected feature rows with hand-built examples at entity boundaries and after missing timestamps.

xt,j=yt−j[t],j=0,…,L−1,zt=yt+hx_{t,j}=y^{[t]}_{t-j},\quad j=0,\ldots,L-1,\qquad z_t=y_{t+h}
h≥1 and L≥1 are integer periods on a regular grid. Superscript [t] means the version usable at origin t; unavailable values remain missing. Features and target retain the units of y.↔ Scroll wide equations horizontally.

Close windows on the legal side

A rolling mean must specify included timestamps and how missing values affect its denominator. For an origin after period t has become usable, a length-three window may include t, t−1, and t−2. For a row indexed by the next target t+1, that same calculation requires shifting before rolling. A centered window generally includes future observations and is unsuitable for causal online features unless its output is delayed enough to make every constituent genuinely available.

Row count and elapsed time are different window definitions. The last twenty observations may cover twenty minutes during normal reporting and several hours during an outage. A one-hour average over irregular samples also needs a measurement interpretation: an arithmetic average of event samples is not necessarily a time-weighted average of a continuously held rate. Store sample count and elapsed coverage with aggregates. These auxiliary features help the model distinguish low demand from weak observation support.

yˉt,L=∑j=0L−1mt,jyt−j[t]∑j=0L−1mt,j,∑j=0L−1mt,j>0\bar y_{t,L}=\frac{\sum_{j=0}^{L-1}m_{t,j}y^{[t]}_{t-j}}{\sum_{j=0}^{L-1}m_{t,j}},\qquad \sum_{j=0}^{L-1}m_{t,j}>0
m is 1 only for eligible, observed constituents and 0 otherwise. Missing terms are omitted rather than multiplied as NaN. This is an equal-period observed-value mean, not a time-weighted irregular-sample average.↔ Scroll wide equations horizontally.

Fit transformations without future information

Scaling, imputation statistics, feature selection, and learned embeddings are parts of the model pipeline. Fit them using only the training information allowed at each replay cutoff. A standardization mean computed over the entire series leaks later level changes into earlier folds even when every explicit lag points backward. For a global model, also decide whether each entity’s scale is estimated independently and how a newly appearing series obtains a scale without access to its future history.

Version the feature definition along with the model. Changing a window’s closure, timezone conversion, minimum-observation threshold, or revision selection can alter predictions without modifying learned weights. In pandas 2.3.3, distinguish shifting values by periods from shifting index labels with a frequency; relabeling timestamps does not by itself build the intended lagged alignment. Test full training-serving parity using a fixed historical snapshot and compare each intermediate feature, not merely the final forecast.

Align a three-value window for a two-step forecast

A regular series has usable values y₇=4, y₈=8, y₉=6, and y₁₀=12 at origin 10. Predict y₁₂ using a three-period trailing mean ending at the origin. A target-indexed table uses row s=12. Compute the feature and the required value shift.

  1. The legal trailing window ends at origin 10 and contains y₈, y₉, and y₁₀: values 8, 6, and 12. It does not include target-adjacent y₁₁ because that value is future at issue time.

  2. Add the three values to obtain 26 and divide by 3, giving a mean of 8⅔ units. The preceding y₇=4 is outside this length-three window.

  3. On target row s=12, shift the underlying series by h=2 periods before taking its trailing three-row mean. A shift of only one would include y₁₁ and violate the declared origin.

The result

Origin-based definitions explain both the numeric feature and the implementation offset. The correct shift depends on target alignment, horizon, and the input availability contract.

Explore the model

Interactive lab

Interactive lab · cache

A lag window also creates a working set

Reset, set Cache capacity C to 4 and Request stride s to 4. Predict four distinct addresses and 4 misses plus 12 hits among the initial 16 requests; one Step adds a hit. Reset, set C=3 and s=4, then Step: all 17 requests are misses. The trace is capped at 4096 requests. This deterministic LRU model illustrates reuse while reading history; it does not construct temporal features or determine causal eligibility.

A lag window also creates a working setA fully associative LRU cache starts empty and requests address (i·s) mod 16. Hits move an address to the newest position; misses evict the oldest when full. Playback starts with 16 requests and adds two per second, capped at 4096 explicitly simulated requests. This toy stream is not a processor-cache benchmark. Current readings: Hits / requests: 0 / 16; Hit rate: 0%; Address-stream period: 16 addresses. All parameters are adjustable with the labeled controls below.Fully associative LRU cache after 16 deterministic requests: 0 hits and 16 misses.Most recent 16 requestsaddress = i × 3 mod 160M3M6M9M12M15M2M5M8M11M14M1M4M7M10M13MCurrent cache order · oldest → newest471013Latest address 13 · miss: inserted as newestToy address stream · period 16 · starts empty
Cached addressMiss / evictionMost recent request
Hits / requests
0 / 16
Hit rate
0%
Address-stream period
16 addresses
t = 0 s

A fully associative LRU cache starts empty and requests address (i·s) mod 16. Hits move an address to the newest position; misses evict the oldest when full. Playback starts with 16 requests and adds two per second, capped at 4096 explicitly simulated requests. This toy stream is not a processor-cache benchmark. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forA temporal feature pipeline has both a statistical window contract and a separate data-access cost.

Check your understanding

Which feature is legal when forecasting y₁₂ at origin 10 under the example’s policy?

Try it yourself

At origin 20, a length-four window has values 5, missing, 9, and 10. Use the observed-value mean with a missingness count. What mean and count should be stored? Is replacing the missing value by zero equivalent?

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

The denominator is the count of observed eligible values, not the nominal window length.

Compare with the solution

The observed sum is 24 and its count is 3, so store mean 8 with observed count 3 and missing count 1. Zero filling yields 24/4=6, which makes a different assumption about the unobserved period. The two features are not equivalent, even if both calculations are easy to implement.

Take it with you

  • Define lags relative to the issue origin before choosing dataframe offsets.
  • Declare grouping, window closure, and missing-value denominators.
  • Fit transformations inside the historical training boundary.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.