Build lag and difference features for forecasting

To forecast tomorrow's value with an ordinary model, you turn a series into rows of past values. Rows with missing history are dropped.

Write make_features(series, lags) that returns (X, y). For each time t that has all lags available (t >= max(lags)):
- the row is [series[t - L] for L in lags] + [series[t - 1] - series[t - 2]]
- the target is series[t]
Assume max(lags) >= 2. Return X as a 2D float array and y as a 1D float array.

Signaturedef make_features(series, lags)

Understand the idea

Ordinary models like linear regression do not understand time, so for forecasting you turn a series into a table: each row holds past values and the target is the value now. Each feature must come strictly from the past, or the model sees the answer. Like predicting today's sales using only yesterday's and earlier records. Rows without enough history are dropped. Worked example: series [1, 2, 4, 7, 11], lags [1, 2]. Start at t = 2. Row t = 2: [series[1], series[0]] = [2, 1], plus diff series[1] - series[0] = 1, target 4. Row t = 3: [4, 2] plus diff 2, target 7. Row t = 4: [7, 4] plus diff 3, target 11. So X = [[2, 1, 1], [4, 2, 2], [7, 4, 3]] and y = [4, 7, 11]. Rule: for t >= max(lags), row = [series[t - L] for L in lags] + [series[t - 1] - series[t - 2]], target = series[t]. Demand forecasting with gradient boosted trees commonly uses such features.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: features with lags 1 and 3make_features(_s, [1, 3])[0]
  • Sample 2: targetsmake_features(_s, [1, 3])[1]
  • Test 3: lags 2make_features(_s, [2])[0]