Skip to content
Visual explainer 4h to learn 5 steps

Time series forecasting with lag features and backtests

Forecast a seasonal series with lag features, beat a seasonal naive baseline in a rolling backtest and report a forecast interval.

By Invicly Tech, , in AI and Machine Learning with Python. About 13 minutes to read.

Topic 17 of 34

In short

Forecasting predicts future values of a series, such as daily sales, from its own past and from known calendar facts. You turn the series into a table with lag and rolling features, compare against naive and seasonal naive baselines, and test with a rolling-origin backtest that only ever trains on the past. A useful forecast also says how uncertain it is, with an interval rather than a single number.

Think of it like this: Backtesting is like checking a weather forecaster by giving them only last year's data up to each morning and scoring what they said about the next day.

Explained simply

A time series is a list of measurements in time order: daily sales, hourly web visits, monthly electricity use. Forecasting means guessing the next values. The order matters. Unlike most tables, you cannot shuffle the rows, because yesterday really does help explain today.

Most series have a few familiar parts. Trend is the slow drift up or down. Seasonality is a pattern that repeats on a fixed cycle, such as busy weekends or a December peak. What is left over is noise. Plotting the series is the first and most useful step, because your eyes spot these parts quickly.

Before any clever model, make a dumb forecast. The naive forecast says tomorrow equals today. The seasonal naive forecast says next Monday equals last Monday. These baselines are free and often hard to beat. If your model cannot beat them, it is not ready.

To use normal machine learning models, you turn the series into a table. Each row gets features such as the value one day ago (a lag), the value seven days ago, and the average of the last week. The big rule: a feature may only use information you would really have at the time you make the forecast.

Finally, a single number hides uncertainty. A good forecast says something like: we expect 120 orders, and 80 percent of the time it will be between 100 and 140. You build that range from your past errors and then check that it is honest.

Press Play on a diagram to walk through it one step at a time.

FlowA leak-free forecasting workflow
  1. 1
    Plot the series

    Look for trend, seasonality and breaks

  2. 2
    Set baselines

    Naive and seasonal naive forecasts

  3. 3
    Build features

    Lags and rolling stats from past values only

  4. 4
    Rolling backtest

    Train on the past, test on the next window, repeat

  5. 5
    Add intervals

    From backtest errors, then check coverage

CompareRandom split versus time split
Random K-fold
  • Mixes future rows into training
  • Scores look too good
  • Ignores the order of time
  • Fine for independent rows only
Rolling-origin backtest
  • Training always ends before the test window
  • Mimics real use
  • Gives one score per origin
  • TimeSeriesSplit in scikit-learn
MapForecasting baselines and models
Forecast options
  • Baselines
    • Naive: last value
    • Seasonal naive: value one season ago
    • Moving average
  • Statistical models
    • Exponential smoothing (ETS)
    • SARIMAX in statsmodels
  • Machine learning on lag features
    • Linear regression
    • Gradient boosting
  • Uncertainty
    • Residual percentiles
    • Quantile loss
    • Model-based intervals

In depth

Spotting trend and seasonality

Start with a line plot of the whole series, then zoom into a few weeks. Weekly patterns show up as a repeating saw-tooth; yearly ones need at least two years of data to confirm. A seasonal plot, where you group values by day of week or month and draw a box plot for each group, makes the pattern obvious.

statsmodels can split a series into parts. STL, in statsmodels.tsa.seasonal, separates trend, seasonal and remainder components using local smoothing and copes well with changing seasonality. An autocorrelation plot (plot_acf in statsmodels.graphics.tsaplots) shows how strongly the series relates to itself at each lag; spikes at 7, 14 and 21 confirm weekly seasonality. Also look for breaks: a price change, a new store or a pandemic can shift the level, and old data from before the break may mislead the model.

  • Seasonal period m: 7 for daily data with weekly cycles, 12 for monthly data with yearly cycles
  • STL(series, period=7).fit() returns trend, seasonal and resid
  • ACF spikes at multiples of m suggest seasonality

Lag and rolling features without leakage

In pandas, shift(k) moves the series down k rows, so each row sees the value from k steps earlier. Rolling statistics need care: df["y"].rolling(7).mean() includes the current row, which is the target. Write df["y"].shift(1).rolling(7).mean() instead, so the window ends yesterday.

The horizon changes what is allowed. If you forecast 7 days ahead, the latest value you know is 7 days old, so the smallest valid lag is 7. Either build one model per horizon with lags of at least that horizon, or forecast one step at a time and feed predictions back in, which compounds errors. Calendar features such as day of week, month and known holidays are safe because they are known in advance. External features, such as weather, are only safe if you use forecasts of them, not the values that were later observed.

LayersWhich features are allowed at forecast time
  1. 1
    Calendar

    Day of week, month, holidays: always known

  2. 2
    Lags at or beyond the horizon

    lag_7 is fine for a 7-day forecast

  3. 3
    Shifted rolling stats

    shift(h) first, then rolling

  4. 4
    External forecasts

    Weather forecast, not observed weather

  5. 5
    Not allowed

    Anything computed from the target period

Rolling-origin backtests

A backtest replays history. Pick an origin date, train on everything before it, forecast the next horizon, record the errors, then move the origin forward and repeat. The average error over many origins is a far more honest estimate than one split, because it covers different seasons and events.

scikit-learn's TimeSeriesSplit does this for tabular features. By default it uses an expanding window: each split trains on all earlier rows. Use max_train_size for a sliding window when old data is less relevant, test_size to fix the window length to your horizon, and gap to leave rows between train and test when the latest data arrives late. Run the seasonal naive baseline through exactly the same splits so the comparison is fair. Use metrics in business units, such as mean absolute error, and MASE, which divides your error by the seasonal naive error so that values below 1 mean you beat it.

SequenceThree origins of an expanding-window backtest
History
Model
Scorer
  1. 1Origin 1: train on Jan to Jun
    History to Model: Origin 1: train on Jan to Jun
  2. 2Forecast first week of July
    Model to Scorer: Forecast first week of July
  3. 3Origin 2: train on Jan to early Jul
    History to Model: Origin 2: train on Jan to early Jul
  4. 4Forecast second week of July
    Model to Scorer: Forecast second week of July
  5. 5Origin 3: train on Jan to mid Jul
    History to Model: Origin 3: train on Jan to mid Jul
  6. 6Forecast third week of July
    Model to Scorer: Forecast third week of July
  7. 7Average errors and compare with baseline
    Scorer to Scorer: Average errors and compare with baseline

Forecast intervals you can trust

A simple and honest way to build intervals is from backtest residuals, the actual minus the forecast, collected per horizon. For an 80 percent interval, take the 10th and 90th percentiles of those residuals and add them to each new point forecast. Because errors grow with the horizon, compute separate percentiles for one day ahead, two days ahead and so on.

Model-based options also exist. Statistical models in statsmodels, such as ETS or SARIMAX, return intervals through get_forecast(...).conf_int(). Gradient boosting can produce quantiles directly with a quantile loss, such as HistGradientBoostingRegressor(loss="quantile", quantile=0.9). Whatever the method, check coverage on later backtest windows: an 80 percent interval should contain about 80 percent of actual values. If coverage is much lower, the intervals are too narrow, often because the backtest period was calmer than reality.

  • Residual = actual - forecast
  • 80 percent interval: 10th and 90th residual percentiles
  • Compute percentiles per horizon step
  • Coverage = share of actuals inside the interval

Learn it in 5 short steps

About 50m each. Track them with a timer in your plan.

  1. 1
    Spot trend and seasonality~50m
  2. 2
    Build lag and rolling features~50m
  3. 3
    Start from naive and seasonal baselines~50m
  4. 4
    Run a rolling-origin backtest~50m
  5. 5
    Report forecast intervals~50m

Key points

  • Seasonal naive, which repeats the value from one season ago, is the baseline your model must beat.
  • Every feature must be computable at the moment of forecasting: shift before you roll.
  • Never shuffle time series rows; use a rolling-origin backtest such as TimeSeriesSplit.
  • Report a forecast interval and check how often real values fall inside it.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
import numpy as np, pandas as pd

idx = pd.date_range("2025-01-01", periods=365, freq="D")
rng = np.random.default_rng(0)
sales = 100 + 0.1 * np.arange(365) + 15 * (idx.dayofweek >= 5) + rng.normal(0, 5, 365)
df = pd.DataFrame({"y": sales}, index=idx)
df["lag_1"] = df["y"].shift(1)
df["lag_7"] = df["y"].shift(7)
df["roll_mean_7"] = df["y"].shift(1).rolling(7).mean()
df["dow"] = df.index.dayofweek
df = df.dropna()

shift(1) before rolling keeps today's value out of today's features.

Beating seasonal naive in a rolling backtest

Use a synthetic daily series with a trend, a weekend bump and noise. Step 1: build lag_7, lag_14, a shifted 7-day mean and day of week. Step 2: create TimeSeriesSplit(n_splits=5, test_size=7) so each fold forecasts one week. Step 3: in each fold, fit a gradient boosting model and also predict with lag_7, which is exactly the seasonal naive forecast. Step 4: compare mean absolute errors across folds. If the model's error is not clearly lower on most folds, keep the baseline.

python
from sklearn.model_selection import TimeSeriesSplit
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error

# df has y, lag_7, lag_14, roll_mean_7 (shifted by 7), dow; NaNs dropped
X, y = df[["lag_7", "lag_14", "roll_mean_7", "dow"]], df["y"]
for i, (tr, te) in enumerate(TimeSeriesSplit(n_splits=5, test_size=7).split(X)):
    m = HistGradientBoostingRegressor(random_state=0).fit(X.iloc[tr], y.iloc[tr])
    mae_model = mean_absolute_error(y.iloc[te], m.predict(X.iloc[te]))
    mae_naive = mean_absolute_error(y.iloc[te], X["lag_7"].iloc[te])
    print(i, round(mae_model, 2), round(mae_naive, 2))

Adding an 80 percent interval from residuals

Step 1: during the backtest, store every residual (actual minus forecast) from all folds. Step 2: take the 10th and 90th percentiles of those residuals. Step 3: for the final forecast, refit on all data and add the two percentiles to each point forecast. Step 4: on a later hold-out month, count how often actuals fall inside; aim for close to 80 percent. Simplification: this pools all horizons; a stricter version computes percentiles per horizon step.

python
import numpy as np

# residuals: list of actual - forecast collected in the backtest
lo, hi = np.percentile(residuals, [10, 90])
point = final_model.predict(X_future)
lower, upper = point + lo, point + hi

# later, when actuals arrive
coverage = np.mean((actuals >= lower) & (actuals <= upper))
print(f"coverage: {coverage:.0%} (target 80%)")

Quick reference

  • Seasonal naive: forecast = value one season ago (lag m); always report it
  • Leak-free rolling mean: y.shift(h).rolling(w).mean() for horizon h
  • Smallest valid lag equals the forecast horizon
  • TimeSeriesSplit(n_splits, test_size, gap, max_train_size); never shuffle
  • MASE below 1 means you beat the naive benchmark
  • 80 percent interval: add the 10th and 90th residual percentiles
  • Check interval coverage on later data; low coverage means too narrow

Common mistakes

  • Computing rolling(7).mean() without shift, so the feature includes the value you are predicting.
  • Using lag_1 to forecast 7 days ahead, when that lag will not exist yet at forecast time.
  • Reporting accuracy without a seasonal naive baseline, so nobody knows if the model adds value.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which feature leaks the target when forecasting today's sales?

Question 2

2You forecast 14 days ahead. Which lag can you safely use without feeding predictions back in?

Question 3

3Your model's MASE is 1.15. What does that tell you?

Question 4

4What does TimeSeriesSplit do by default?

Question 5

5An 80 percent interval contains the actual value 95 percent of the time. What should you do?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create a daily series for 120 days with a weekly pattern, then compute the mean absolute error of the naive and seasonal naive forecasts over the last 28 days.

  2. Exercise 2medium

    Build lag_7, lag_14 and a leak-free 7-day rolling mean for a 7-day horizon, and assert that no feature uses data from the last 6 days before each row.

  3. Exercise 3hard

    Run a 6-fold rolling backtest with a 7-day test window, collect residuals per horizon step (day 1 to day 7), and print the 80 percent interval width for each step.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use ARIMA or machine learning for forecasting?
Try both against the same baseline and backtest. Statistical models such as ETS and SARIMAX work well on single series with clear seasonality; gradient boosting on lag features often wins when you forecast many related series with extra features.
How much history do I need?
At least two full seasonal cycles to see seasonality reliably, for example two years for yearly patterns. More history helps only if the process has not changed.
Why not just use a random train-test split?
Random splits let the model learn from the future, so the test score is too optimistic and will not match real forecasts.

Go deeper

ShareXLinkedInWhatsApp