Quick start¶
You have a forecaster. Before you trust it with real data, you want to know which kinds of series it gets right, and which ones it quietly gets wrong.
Real data can't tell you that, because nobody knows what the best possible forecast would have been. TimeGym makes up series from recipes it knows, so it also knows the best forecast anyone could make from the same history: the answer key. A forecast is scored by how close it gets to the answer key, not to the values that came next, because those include noise that no model can predict.
In this notebook we score the simplest forecaster there is, "the future looks like the last value", and then a Ridge regression that learns from the last 24 values. Each turns out to be blind exactly where the other one sees.
One call, one picture¶
Wrap a forecaster in a Pipeline, call run() and look at the scorecard on its result. The built-in last-value forecaster (LastValueForecaster) stands in for yours here: it predicts that every future value equals the last one it saw.
from timegym import LastValueForecaster, Pipeline
pipeline = Pipeline(LastValueForecaster()) # put your own forecaster here
result = pipeline.run()
result.scorecard
Each row is a kind of series. The left column says what a perfect forecaster could get right (✓) and what nobody can (✗). The next two columns are a low and a high noise level, each showing one of the ten series drawn for that cell: gray dots are the data, the black line is the answer key and the blue crosses are the forecast. The badge is the score out of 100. The short line beside it is the score's 95% interval, roughly where it would land on ten other series, on a 0 to 100 scale ticked at 40, 70 and 90; a question mark and a paler badge mean the interval reaches into another band, so ten draws can't settle that verdict. The small triangle above the line is what the right kind of model, fitted to the same history, would score: the answer key knows the true settings, a fitted model has to estimate them, and that alone costs even the right kind of model from a fraction of a point to about 13 points, depending on the row. A score of 100 means as close as the answer key, and 50 means the avoidable error is as large as the noise nobody could predict. The bands read "Nails it" from 90, "Good" from 70, "Struggles" from 40 and "Fails" below that. The last column names the mistakes, and the line at the top says whether every forecast passed the output checks: the right dates, the right shape, no missing values.
The last-value forecaster scores 51, and the rows say why. It nails the random walk at low noise (99): when shocks never fade, the last value really is the best guess for every step ahead. It fails on the straight-line trend and the seasonal cycle at low noise (10 and 3), because a flat line can follow neither; the mistakes column says "Trend too flat" and "Misses the cycle".
Every number on the card is also in its table, so the story can be checked in code:
card = result.scorecard
baseline_table = card.table.set_index(["pattern", "noise"])
assert baseline_table.loc[("random_walk", "Low noise"), "score"] >= 90 # the last value is the answer for a random walk
assert baseline_table.loc[("seasonal", "Low noise"), "score"] < 40 # but a flat line misses every cycle
The same scorecard, as text¶
For a pull request, a log or a chat message, print the scorecard: the same scores and mistakes as a Markdown table.
print(card)
## LastValueForecaster: 51/100 TimeGym scorecard: 10 kinds of series x 2 noise levels, 10 instances each, seed 0. | Pattern | Low noise | High noise | Mistakes | |---|---|---|---| | Pure noise | 56 Struggles? | 56 Struggles? | Misreads the current level | | Noise around a fixed level | 56 Struggles? | 56 Struggles? | Misreads the current level | | Straight-line trend | 10 Fails | 43 Struggles? | Low: Forecasts too low; Trend too flat · High: Misreads the current level | | Repeating seasonal cycle | 3 Fails | 28 Fails? | Misses the cycle; Forecasts too low | | Trend + seasonal cycle | 2 Fails | 21 Fails | Forecasts too low; Misses the cycle | | Sudden level shift | 70 Good? | 70 Good? | none found | | Mean reversion (AR(1)): shocks fade | 78 Good? | 72 Good? | none found | | Irregular cycles (AR(2)) | 35 Fails? | 47 Struggles? | Misreads the current level | | Random walk: shocks never fade | 99 Nails it | 87 Good? | none found | | Random walk with drift | 64 Struggles | 71 Good? | Low: Forecasts too low; Trend too flat | **Good at:** Mean reversion (AR(1)): shocks fade, Random walk: shocks never fade. **Fails at:** Straight-line trend, Repeating seasonal cycle, Trend + seasonal cycle, Irregular cycles (AR(2)). **Output checks:** ✓ Runs without errors (200/200) · ✓ Forecasts the requested dates (200/200) · ✓ Returns every series, in order (200/200) · ✓ Right number of steps and series (200/200) · ✓ No missing or infinite values (200/200) Score: 100 = as close as a forecaster that knows the true process; 50 = its avoidable error equals the unavoidable noise. Bands: 90+ nails it, 70+ good, 40+ struggles, below 40 fails. A question mark means the verdict is not settled: the score's 95% interval reaches into another band. 14 of 20 verdicts are not settled at 10 instances. Run pipeline.run(instances=30) to narrow them.
A contender that can learn shapes¶
Now a model that can learn a line or a cycle. window_length=24 cuts the history into windows of 24 consecutive values, each followed by the value that came next. scikit-learn's Ridge learns to predict that next value from the window (after StandardScaler puts the inputs on one scale); the pipeline takes the two as a list of steps, and feeds each forecast back in as the newest value to reach 24 steps ahead.
from sklearn.linear_model import Ridge
from sklearn.preprocessing import StandardScaler
contender = Pipeline([StandardScaler(), Ridge(alpha=1.0)], window_length=24)
ridge_result = contender.run()
ridge_card = ridge_result.scorecard
ridge_card
Ridge scores 69. It learned what the baseline couldn't: the trend, the seasonal cycle and the two together are "Good" at both noise levels. Now look at the bottom of the card. On the random walk at low noise Ridge drops to 56, where the baseline scored 99, and it fails on the sudden level shift (21 at low noise) and on the random walk with drift (23 at high noise). For the random walk and the level shift, the mistakes column says what goes wrong: it "invents a trend", adding a slope the answer key doesn't have.
Side by side¶
Put the two models' scores next to each other, one row per kind of series and noise level:
import numpy as np
import pandas as pd
side_by_side = pd.DataFrame({
"Kind of series": card.table["title"],
"Noise": card.table["noise"],
"Last value": card.table["score"].round().astype(int),
"Ridge": ridge_card.table["score"].round().astype(int),
})
side_by_side["Better"] = np.select(
[side_by_side["Ridge"] > side_by_side["Last value"], side_by_side["Ridge"] < side_by_side["Last value"]],
["Ridge", "Last value"], default="Tie")
side_by_side
| Kind of series | Noise | Last value | Ridge | Better | |
|---|---|---|---|---|---|
| 0 | Pure noise | Low noise | 56 | 84 | Ridge |
| 1 | Pure noise | High noise | 56 | 84 | Ridge |
| 2 | Noise around a fixed level | Low noise | 56 | 84 | Ridge |
| 3 | Noise around a fixed level | High noise | 56 | 84 | Ridge |
| 4 | Straight-line trend | Low noise | 10 | 83 | Ridge |
| 5 | Straight-line trend | High noise | 43 | 78 | Ridge |
| 6 | Repeating seasonal cycle | Low noise | 3 | 77 | Ridge |
| 7 | Repeating seasonal cycle | High noise | 28 | 74 | Ridge |
| 8 | Trend + seasonal cycle | Low noise | 2 | 78 | Ridge |
| 9 | Trend + seasonal cycle | High noise | 21 | 71 | Ridge |
| 10 | Sudden level shift | Low noise | 70 | 21 | Last value |
| 11 | Sudden level shift | High noise | 70 | 45 | Last value |
| 12 | Mean reversion (AR(1)): shocks fade | Low noise | 78 | 70 | Last value |
| 13 | Mean reversion (AR(1)): shocks fade | High noise | 72 | 83 | Ridge |
| 14 | Irregular cycles (AR(2)) | Low noise | 35 | 72 | Ridge |
| 15 | Irregular cycles (AR(2)) | High noise | 47 | 82 | Ridge |
| 16 | Random walk: shocks never fade | Low noise | 99 | 56 | Last value |
| 17 | Random walk: shocks never fade | High noise | 87 | 87 | Tie |
| 18 | Random walk with drift | Low noise | 64 | 41 | Last value |
| 19 | Random walk with drift | High noise | 71 | 23 | Last value |
ridge_table = ridge_card.table.set_index(["pattern", "noise"])
assert ridge_card.score > card.score # Ridge is better overall...
assert (ridge_table.loc[("random_walk", "Low noise"), "score"]
< baseline_table.loc[("random_walk", "Low noise"), "score"]) # ...but not on a random walk
side_by_side["Better"].value_counts()
Better Ridge 13 Last value 6 Tie 1 Name: count, dtype: int64
Ridge is better in 13 of the 20 cells and the baseline in 6, with one tie. So neither is the better forecaster in general. If your series wander like a random walk or jump to a new level now and then, the one-line baseline is the one to beat, and Ridge doesn't beat it there.
Why score against the answer key?¶
You could score against what actually happened instead: that error is in card.table too, as mse. Here is why TimeGym doesn't. Take mean reversion at high noise and measure both models both ways:
row = ("mean_reverting", "High noise")
yardsticks = pd.DataFrame({
"Last value": baseline_table.loc[row, ["mse", "avoidable_mse"]],
"Ridge": ridge_table.loc[row, ["mse", "avoidable_mse"]],
}).astype(float).rename(index={"mse": "Error against what actually happened",
"avoidable_mse": "Error against the answer key"})
assert yardsticks.loc["Error against what actually happened", "Last value"] < yardsticks.loc["Error against what actually happened", "Ridge"]
assert yardsticks.loc["Error against the answer key", "Ridge"] < yardsticks.loc["Error against the answer key", "Last value"] # the two yardsticks disagree
yardsticks.round(2)
| Last value | Ridge | |
|---|---|---|
| Error against what actually happened | 8.66 | 9.33 |
| Error against the answer key | 2.56 | 1.38 |
Against what actually happened, the baseline looks better (8.66 against 9.33). Against the answer key, Ridge's error is about half the baseline's (1.38 against 2.56). They disagree because what actually happened includes fresh noise, and over ten short series the way that noise happened to fall is enough to flip the ranking. The answer key has no noise in it, so comparing against it measures the models, not the luck. The score is built from the same split: 100 × unavoidable / (unavoidable + avoidable).
Look behind a score¶
A score is a summary over ten series. Is Ridge a little worse on every random walk, or much worse on a few? Run it on just that row and the low noise level (["random_walk"] and noise_levels), with 20 draws, and plot how the error against the answer key spreads over them:
import matplotlib.pyplot as plt
walks = contender.run(["random_walk"], noise_levels=[0.5], instances=20)
walk_errors = walks.metrics["avoidable_mse"]
print(f"{(walk_errors < 2).sum()} of {len(walk_errors)} draws have an error below 2; "
f"the others: {', '.join(f'{e:.1f}' for e in walk_errors[walk_errors >= 2])}")
walks.plot_errors()
plt.show()
17 of 20 draws have an error below 2; the others: 19.8, 6.7, 19.4
Most draws sit close to the answer key and a few run away. Draw i uses seed seed + i, so seed=5 with three instances draws seeds 5, 6 and 7 (instances 1 to 3 in the panel titles), and seed 6 is one of the runaways. plot_forecasts draws the series and the forecasts themselves, so this run keeps them (keep_data=True):
three_walks = contender.run(["random_walk"], noise_levels=[0.5], seed=5, instances=3, keep_data=True)
three_walks.plot_forecasts(figsize=(15, 3.8))
plt.show()
In instance 1 (seed 5) Ridge sits on the flat answer key and scores 100; in instance 3 (seed 7) it drifts a little above it and scores 85. In instance 2 (seed 6) it sets off downhill on a slope of its own and scores 15: that is the invented trend. Two runaways among the scorecard's ten draws, seeds 6 and 9, pull Ridge's score on this cell down to 56; the other eight alone would score in the 90s. plot_errors(metric="mse") draws the same histogram against what actually happened.
Is the gap real, or the luck of the draw?¶
Ten draws per cell is a quick look, and a different set of draws gives a different score. Before believing a gap between two models, score them on other draws, and on more of them. seed picks the draws (the same seeds in every cell) and instances sets how many there are per cell:
rows = []
for instances in (10, 30):
for seed in (0, 1000, 2000):
rows.append({
"Draws per cell": instances,
"Seed": seed,
"Last value": pipeline.run(seed=seed, instances=instances).scorecard.score,
"Ridge": contender.run(seed=seed, instances=instances).scorecard.score,
})
luck = pd.DataFrame(rows)
luck["Gap"] = luck["Ridge"] - luck["Last value"]
assert (luck["Gap"] > 10).all() # Ridge stays well ahead on every set of draws
luck.round(0).astype(int)
| Draws per cell | Seed | Last value | Ridge | Gap | |
|---|---|---|---|---|---|
| 0 | 10 | 0 | 51 | 69 | 18 |
| 1 | 10 | 1000 | 42 | 63 | 21 |
| 2 | 10 | 2000 | 45 | 58 | 13 |
| 3 | 30 | 0 | 48 | 68 | 20 |
| 4 | 30 | 1000 | 44 | 66 | 22 |
| 5 | 30 | 2000 | 45 | 64 | 19 |
With 10 draws per cell, Ridge's overall score moves between 58 and 69 depending on the seed; with 30 draws it stays between 64 and 68. The gap to the baseline is 13 to 22 points in every row, so it is real. A difference of a few points between two closer models would not be, at 10 draws: compare those with 20 or 30.
Every run can be repeated from its seed. seed=None draws a fresh seed each time, which is what you want when tuning a model on the scorecard, because the model never sees the same series twice and can't be tuned to them. The seed it drew is kept on card.seed:
fresh = pipeline.run(seed=None).scorecard
again = pipeline.run(seed=fresh.seed).scorecard
assert again.score == fresh.score # the recorded seed repeats the run exactly
print(f"seed {fresh.seed}: {fresh.score:.0f}/100")
seed 1281710465: 41/100
Use it as a test¶
Scores never fail a build: TimeGym sets no pass mark for accuracy, because only you know what is good enough. Broken output does. result.checks lists each output check with how many forecasts passed it, and result.assert_passed() raises if any forecast had the wrong dates or shape or missing values, or if the model crashed. Faults, repairs and replay shows what those failures look like.
ridge_result.assert_passed() # raises on any broken forecast or crash
pd.DataFrame(ridge_result.checks)
| check | title | passed | failed | |
|---|---|---|---|---|
| 0 | runs | Runs without errors | 200 | 0 |
| 1 | dates | Forecasts the requested dates | 200 | 0 |
| 2 | series | Returns every series, in order | 200 | 0 |
| 3 | shape | Right number of steps and series | 200 | 0 |
| 4 | finite | No missing or infinite values | 200 | 0 |
To keep the evidence, result.save("report.json") saves every case: its scenario, seed and metrics, every check's verdict, the pipeline's settings, and the Python and library versions, so a failure with a built-in model can be replayed from the file alone. Here we keep the JSON in memory, as result.to_json() gives it:
import json
saved = json.loads(ridge_result.to_json())
first = saved["cases"][0]
print(f"{len(saved['cases'])} cases; the first is {first['manifest']['kind']!r} with seed {first['seed']}")
print("Library versions:", saved["metadata"]["dependencies"])
200 cases; the first is 'white_noise' with seed 0
Library versions: {'numpy': '2.5.5', 'pandas': '3.1.1', 'scikit-learn': '1.9.1', 'scipy': '1.18.1', 'timegym': '1.14.1'}
Compare with the version you trust¶
assert_passed catches broken output, not a model that has become worse. For that, save the scorecard of the version you trust and compare each change with it on the same series: compare says, cell by cell, whether the new version is further from the answer key. Say you shorten Ridge's window from 24 steps to 12:
from pathlib import Path
from tempfile import TemporaryDirectory
trusted = contender.run(instances=30).scorecard
shorter = Pipeline([StandardScaler(), Ridge(alpha=1.0)], window_length=12)
with TemporaryDirectory() as folder:
saved_baseline = trusted.save_baseline(Path(folder) / "scorecard-baseline.json")
diff = shorter.run(instances=30).scorecard.compare(saved_baseline) # the same seed, so the same series
print(diff)
Compared with scorecard-baseline.json (30 series per cell)
19 cells changed, no worse
Pure noise, low noise avoidable error 0.0455 -> 0.0129 (-72%)
Pure noise, high noise avoidable error 0.729 -> 0.206 (-72%)
Noise around a fixed level, low noise avoidable error 0.0455 -> 0.0129 (-72%)
Noise around a fixed level, high noise avoidable error 0.729 -> 0.206 (-72%)
Straight-line trend, low noise avoidable error 0.0579 -> 0.0611 (+5.5%)
Straight-line trend, high noise avoidable error 1.29 -> 1.30 (+1.1%)
Repeating seasonal cycle, low noise avoidable error 0.0694 -> 0.0755 (+8.8%)
Repeating seasonal cycle, high noise avoidable error 1.31 -> 1.18 (-9.5%)
Trend + seasonal cycle, high noise avoidable error 1.74 -> 2.00 (+15%)
Sudden level shift, low noise avoidable error 1.42 -> 0.341 (-76%)
Sudden level shift, high noise avoidable error 8.56 -> 1.36 (-84%)
Mean reversion (AR(1)): shocks fade, low noise avoidable error 0.903 -> 0.427 (-53%)
Mean reversion (AR(1)): shocks fade, high noise avoidable error 1.38 -> 0.449 (-67%)
Irregular cycles (AR(2)), low noise avoidable error 2.02 -> 1.07 (-47%)
Irregular cycles (AR(2)), high noise avoidable error 2.41 -> 1.17 (-52%)
Random walk: shocks never fade, low noise avoidable error 2.90 -> 0.581 (-80%)
Random walk: shocks never fade, high noise avoidable error 2.51 -> 0.655 (-74%)
Random walk with drift, low noise avoidable error 5.27 -> 2.81 (-47%)
Random walk with drift, high noise avoidable error 14.1 -> 5.31 (-62%)
1 cell changed and worse
Trend + seasonal cycle, low noise avoidable error 0.0855 -> 0.118 (+38%), p = 0.0006
The shorter window is closer to the answer key in most cells, by more than 70% on the level shift and the random walk without drift, and compare calls those cells "changed, no worse". One cell is worse: the trend with a seasonal cycle at low noise, where the avoidable error rises by 38%. In a test suite, diff.assert_no_regression() would fail on that cell and name it, and you decide whether the change is worth it. Save the baseline once, next to your tests, and compare on every change:
# once, on the version you trust
contender.run(instances=30).scorecard.save_baseline("tests/scorecard-baseline.json")
# in the test suite
def test_no_cell_is_further_from_the_answer_key():
card = contender.run(instances=30).scorecard
card.compare("tests/scorecard-baseline.json").assert_no_regression()
"Changed, no worse" does not mean better, and a change too small for 30 series passes; Compare with a saved baseline says what the test assumes.
Your own series¶
The scorecard's grid is fixed so that scores can be compared across models. To ask your own question, describe the series with Scenario and pass them to run. Here is one the scorecard raised: would Ridge stop inventing trends on a random walk if it saw more history? Thirty draws each of 120, 480 and 1,000 steps of history, without drift and with a drift of 0.1 per step:
from timegym import Scenario
suite = [Scenario("random_walk", history_length=history, horizon=24, parameters={"drift": drift})
for drift in (0.0, 0.1) for history in (120, 480, 1000)]
def error_against_answer_key(model):
run = model.run(suite, seed=0, instances=30)
return pd.DataFrame([{"Drift": case.manifest["parameters"]["drift"][0],
"History": case.manifest["history_length"],
"error": case.metrics["avoidable_mse"]} for case in run.report.cases]
).groupby(["Drift", "History"])["error"].mean()
history_errors = pd.DataFrame({"Last value": error_against_answer_key(pipeline),
"Ridge": error_against_answer_key(contender)})
assert history_errors.loc[(0.1, 1000), "Ridge"] < history_errors.loc[(0.1, 1000), "Last value"] # with enough history Ridge finds the drift
history_errors.round(2)
| Last value | Ridge | ||
|---|---|---|---|
| Drift | History | ||
| 0.0 | 120 | 0.00 | 16.76 |
| 480 | 0.00 | 1.52 | |
| 1000 | 0.00 | 0.99 | |
| 0.1 | 120 | 2.04 | 14.18 |
| 480 | 2.04 | 2.26 | |
| 1000 | 2.04 | 1.36 |
More history helps Ridge a lot: on the walk without drift its error against the answer key falls from 16.76 with 120 steps to 0.99 with 1,000. It still never matches the baseline, whose error is exactly zero: with no measurement noise in these series, the last value is the answer key. With drift the story turns around. The last value can't see a slope, so its error stays at 2.04 however much history it gets, while Ridge, with 1,000 steps, learns the drift and beats it.
What this doesn't show. The scorecard judges point forecasts only; how good a model's uncertainty is (intervals, quantiles, samples) has its own tutorials. Its series are made up and short, 120 steps of history and 24 ahead, so a good score is a check worth passing, not proof that a model works on your data. And ten draws per cell is a quick look, not a benchmark.
Change one thing¶
pipeline.run(noise_levels=3)adds a medium-noise column to the scorecard.- Give Ridge a longer window (
window_length=48): do the seasonal rows improve, or do the random walks get worse? - Swap in
MeanForecaster(), the average of the whole history, and find the rows where it beats the last value. - Put your own model in the
Pipeline: Write and test a custom model shows the two methods it needs.
How the score and the mistakes are worked out: Scorecards and the scenario grid.