Lag feature

Also known as: lagged variable

On this page 7

A lag feature is an input variable that holds the value of a time series at an earlier time step, for example yesterday’s demand or the temperature 24 hours ago, so that a model can use recent history to predict the next value. In time series & forecasting, lag features are the most basic way to turn a sequence into a supervised learning table that general machine learning models such as gradient-boosted trees or linear regression can learn from.

The concept, also known as a lagged variable, rests on autocorrelation: most real series depend on their own past. A lag of order k for a target y at time t is simply y at time t minus k. Choosing which lags to include, and making sure each lag is actually available at prediction time, is one of the most consequential steps in feature engineering for forecasting in artificial intelligence.

How lag features turn a series into a learning table

A lag feature is created by shifting the series backward in time and aligning the shifted column with the original timestamps. Each row then contains the target at time t and the chosen past values as predictors. The first k rows have no lag-k value and are either dropped or filled, which slightly shortens the usable training set.

The table below shows daily sales with three lag columns. Each lag column repeats the target column moved down by the lag order.

DateSales (target)Lag 1Lag 2Lag 7
Day 8120115130118
Day 9126120115122
Day 10140126120125
Day 11133140126119
Daily sales with lag columns

In a global forecasting model that covers many series at once, lags must be computed within each series separately, usually by grouping on a series identifier before shifting. Shifting across series boundaries silently mixes histories and is a frequent source of errors.

Choosing lag orders

Good lag orders reflect the memory and seasonality of the process. Short lags capture momentum, while seasonal lags capture repeating patterns such as weekly shopping cycles or daily load curves. The autocorrelation function and the partial autocorrelation function are the standard diagnostic tools for finding lags with predictive signal.

Data frequencyShort lagsSeasonal lagsPattern captured
Hourly1 to 3 hours24 and 168 hoursDaily and weekly cycles
Daily1 to 7 days7, 14 and 364 daysWeekday and annual effects
Weekly1 to 4 weeks52 weeksAnnual seasonality
Monthly1 to 3 months12 monthsYear-over-year pattern
Quarterly1 to 2 quarters4 quartersFiscal cycle
Typical lag choices by data frequency

Adding many lags is tempting, but each lag removes rows, increases collinearity between inputs and raises the risk of overfitting. Tree-based models tolerate redundant lags reasonably well; linear models usually benefit from a small, carefully chosen set or from regularization such as L1 penalties.

Lag features and the forecast horizon

The most important rule is that a lag must be known at prediction time. When forecasting h steps ahead, the most recent observed value is at time t minus h. A lag-1 feature is therefore valid only for one-step forecasts, unless the strategy feeds predictions back as inputs.

Two multi-step strategies handle this differently. In recursive forecasting, the model predicts one step, inserts the prediction as the new lag-1 value and repeats, which allows short lags but accumulates errors over the horizon. In the direct forecasting strategy, a separate model is trained for each horizon h using only lags of order h or greater, which avoids error feedback but requires more models.

StrategyMinimum lag for horizon hAdvantageDrawback
Recursive1, using predicted valuesOne model for all horizonsError accumulation
Directh, observed values onlyNo error feedbackOne model per horizon
Direct-recursive hybridh, plus earlier predictionsBalances both effectsHigher complexity
Multi-outputh for the whole vectorJoint horizon learningNeeds suitable model type
Lag availability under multi-step strategies

How lag features relate to other temporal features

Lag features are usually combined with other engineered inputs. A rolling window feature, such as the mean of the last seven days, summarizes several lags into one robust value and reduces noise. Calendar features encode the day of the week, holidays or the month, while Fourier terms represent smooth seasonal cycles with a few sine and cosine pairs.

Classical models embed lags implicitly. An ARIMA model with an autoregressive order p uses the last p values as linear predictors, which is essentially a fixed set of lag features with a specific error structure. Deep-learning forecasters such as DeepAR also receive selected lags as inputs, while attention-based architectures can learn which past positions matter directly from a long input window.

Lags can also be built from exogenous covariates, for example the price or marketing spend one week earlier. Such lagged drivers often capture delayed effects, but they too must respect the availability at forecast time rule.

Common mistakes with lag features

Most failures come from target leakage, where information from the future slips into the inputs during training. Leakage inflates validation scores and then collapses accuracy in production. The table below lists typical problems.

MistakeConsequenceCorrection
Lag shorter than the horizonUses unknown future valuesUse lags of at least h steps
Shifting across series boundariesMixes histories of itemsGroup by series before shifting
Random cross-validationFuture rows train the modelUse time series cross-validation
Rolling mean including time tTarget leaks into featureShift before computing windows
Ignoring missing timestampsLag points to wrong periodReindex to a complete calendar
Frequent errors and corrections

Another subtle issue is irregular sampling. A row-based shift assumes evenly spaced observations; when days are missing, lag 7 no longer means one week. Reindexing to a complete time grid before shifting keeps lag orders aligned with real time.

Stripped to the essentials

To guess tomorrow, it helps to know yesterday. A lag feature is simply a past value placed next to the value you want to predict.

For example, a shop might note sales from yesterday and from the same day last week. A model looks at these numbers and learns how the past usually leads to the present. The past becomes a clue for the future.

The one firm rule is fairness. The model may only use values that are already known at the moment it makes its guess.

Where it is applied

A regional electricity grid operator forecasts hourly load for the next 24 hours every morning at 6:00. The data team builds a gradient-boosted tree model with lag features of 24, 48 and 168 hours, plus a 24-hour rolling mean, calendar features for holidays and lagged temperature readings.

Because the forecast covers up to 24 hours ahead, the team deliberately excludes lags shorter than 24 hours in its direct model, so every input is known when the forecast is issued. The 168-hour lag captures the weekly rhythm, which separates weekday office demand from quieter weekends.

Validated with rolling-origin time series cross-validation over a full year, the model reduces mean absolute error clearly compared with a seasonal naive forecast. Dispatch planners use the result to schedule generation units and reserve capacity with fewer costly last-minute adjustments.