Scorecards and the scenario grid¶
One call that tells you what a forecaster can and cannot do:
Pipeline.run() and its result.scorecard, a Scorecard from timegym, the grid itself
(PATTERNS, Pattern, GridCell, scenario_grid) from timegym, and the
lower-level verdict, VERDICTS, ScorecardComparison, noise_levels,
NOISE_LOW and NOISE_HIGH from timegym.scorecard and timegym.grid.
from timegym import LastValueForecaster, Pipeline
result = Pipeline(LastValueForecaster()).run()
card = result.scorecard
card # in a notebook: the image
card.plot() # the same image, as a Matplotlib figure
print(card) # Markdown summary and table
card.save("scorecard.png") # or .svg / .pdf
The grid¶
PATTERNS is ten kinds of series, in plain words. Each Pattern carries a
title, an aka (the textbook name), and two sentences: predictable, what a
forecaster that knew the process could get right, and unpredictable, what no
forecaster can get right by design. build(noise, history_length, horizon)
returns the row's Scenario, and attainable_by holds a model of the
generator's own family (see What a fitted model could score).
| Key | Title | What can be predicted | What cannot, by design |
|---|---|---|---|
noise |
Pure noise | Only the average, zero: the best forecast is a flat line at zero. | Every individual value. Any pattern a model finds here is invented. |
level |
Noise around a fixed level | The level, estimated from the whole history. | Each wiggle around the level. |
trend |
Straight-line trend | The line, extended any number of steps ahead. | The noise around the line. |
seasonal |
Repeating seasonal cycle | The repeating shape, any number of steps ahead. | The noise around the cycle. |
trend_seasonal |
Trend + seasonal cycle | Both the line and the repeating shape. | The noise around them. |
level_shift |
Sudden level shift | The new level, from the history since the jump. | The noise. Older history sits at the old level and misleads. |
mean_reverting |
Mean reversion (AR(1)): shocks fade | The pull back to the average: a gap halves in about three steps. | New shocks. After about ten steps only the average is left; measurement noise hides where the series is now. |
cycles |
Irregular cycles (AR(2)) | The rest of the current swing, fading over the next cycles. | When the next swings come and how big they are; noise hides the current phase. |
random_walk |
Random walk: shocks never fade | Where it is now: the best forecast is flat at the current level, smoothed when noisy. | The direction of the next move. Uncertainty grows without limit with the horizon. |
random_walk_drift |
Random walk with drift | The current level plus the steady drift. | The wandering around the drift line, which grows with the horizon. |
The last four rows are autoregressive; Synthetic scenarios explains how mean reversion, irregular cycles and the random walk differ.
noise_levels(levels=2) returns (name, sd) pairs from low to high: two
levels by default, ("Low noise", 0.5) and ("High noise", 2.0).
An integer n >= 2 spaces n levels geometrically between NOISE_LOW = 0.5
and NOISE_HIGH = 2.0, so every grid keeps both extremes; three levels are
named Low, Medium and High. A list of standard deviations is used as given.
The noise is the standard deviation of an error added to each observation. For
the AR and random-walk rows it is measurement noise on top of the hidden
process, so the answer key comes from an exact Kalman filter.
scenario_grid(patterns=None, noise_levels=2, *, history_length=120,
horizon=24) returns one GridCell(pattern, title, noise, noise_sd, scenario,
definition) per pattern and noise level, rows first. Each scenario is an
ordinary Scenario that can also be passed to Pipeline.run or
Pipeline.test, and definition is the Pattern the row comes from.
patterns takes keys of PATTERNS and Patterns of your own
(Your own kind of series).
The score¶
Every forecast error splits into two parts. The unavoidable part is the error a forecaster that knows the process exactly still makes, because the future noise has not happened yet. The avoidable part is the distance from the forecast to that forecaster's answer (the answer key). A cell's score is
score = 100 * unavoidable / (unavoidable + avoidable)
pooled over its instances. 100 matches the answer key; 50 means the avoidable
error equals the unavoidable noise. Instances that crash or fail an output
check score zero, so a broken forecast cannot score well. The overall score is
the mean of the cell scores. VERDICTS names the bands on the rounded score:
90 or more "Nails it", 70 "Good", 40 "Struggles", below 40 "Fails";
verdict(score) returns the band.
How sure a score is¶
Ten series per cell are a small sample, so every score comes with a confidence
interval. card.table has three columns for it:
score_lowandscore_high: the interval around the score. With other series of the same kind the score would come out a little different, and the interval shows by how much. Its confidence level isinterval_level, 95% by default. The interval always contains the score. With fewer than two series there is no interval (NaN).settled: True when both ends of the interval fall in the band printed for the score.
card.table[["title", "noise", "score", "score_low", "score_high", "verdict", "settled"]]
card.unsettled # the rows whose interval crosses 90, 70 or 40
The printed card adds a question mark to a verdict that is not settled
(56 Struggles?) and ends with a line such as 12 of 20 verdicts are not
settled at 10 instances. Run pipeline.run(instances=30) to narrow them. On the
image, a short line beside each score draws its interval on a 0 to 100 scale,
ticked at 40, 70 and 90; a verdict that is not settled gets a question mark
and a paler badge.
A higher confidence level gives a wider, more cautious interval. Pass
interval_level for another level, for example
pipeline.run(interval_level=0.99).scorecard. The card keeps it as card.interval_level, and the printed
card and the image name it. It is a number between 0 and 1, so 95 raises
ValueError.
With ten series the interval is wide. Raise instances to tighten it.
The interval reaches further below the score than above it. A few series usually carry most of a model's error, so a card of ten more often flatters a model than it wrongs it, and the low end allows for that.
The interval only knows the series the card drew. It cannot see a model that fails on a kind of series that the card did not happen to draw, and it says nothing about data that the patterns do not resemble (What TimeGym tests, and what it does not).
How the interval is computed¶
This part is for readers who want the statistics.
Each series is left out in turn and the rest are scored as the cell is scored. How far those scores spread, times a Student t quantile with one degree of freedom fewer than the series, gives how far the interval reaches above the score (a jackknife). Below the score it reaches 1 + 1/√n times as far, where n is the number of series: about a third more at ten series, a fifth more at thirty. Both distances are taken on the log-odds of the score, so both ends stay between 0 and 100. When the score, or a score with one series left out, is exactly 0 or 100 (every instance failed, a perfect forecaster, one instance that passed among failed ones), the same is done on the score itself and cut to 0 to 100. An instance that crashed or failed an output check scores zero wherever it is kept. Nothing is drawn at random, so a cell's interval depends only on its own series and the level, whichever other patterns were scored.
The low end reaches further because squared errors are skewed. A card that happens to draw none of the few series with a large error scores too high, and its series also look alike, so an interval that reached equally far both ways would lie above the long-run score too often. The factor 1 + 1/√n puts the low end within a few percent of where simulation says it has to be for the interval to lie above the long-run score no more often than its level allows, when each series' avoidable error is a squared normal draw (a chi-square distribution with one degree of freedom), as it is for a forecast that is off by the same random amount at every step.
The interval was checked on the 20 default cells with five forecasters of different kinds, against the score from 6,000 series per cell, on cards of 5 to 100 series. Averaged over the cells, it held that score about as often as its level says, or more often, for four of the five. For the fifth, a Ridge regression on lagged values, it fell up to two points short. In a single cell it can be several points off either way. It holds less often than its level for a model whose error comes mostly from a few very bad series, because a small card rarely draws one of them.
What a fitted model could score¶
The answer key knows the true parameters; a model fitted to the history has to
estimate them, so even one of exactly the right kind falls short of 100 on
average. card.table has a column
attainable for that: the score that the pattern's own model family, fitted to
each history, reaches on 200 fresh series of the row, with seeds 1,000,000 to
1,000,199, pooled as a cell is pooled:
attainable = 100 * mean unavoidable / (mean unavoidable + mean avoidable)
over those 200 series. Every numeric parameter is estimated; everything structural is given: the period, that there is exactly one break, the number of lags, that there is measurement noise. The value belongs to the row (pattern, noise level, history length and horizon), not to the series a card happens to draw, so on ten series a model of the right kind can land a little above it. The value is itself an estimate from 200 series, good to about a point: across blocks of 200 series it moves with a standard deviation of 0.1 to 0.7 points on most rows and 1.1 on the random walk with drift at low noise.
| Pattern | Model family fitted to each history | Low noise | High noise |
|---|---|---|---|
noise |
sample mean | 99.1 | 99.1 |
level |
sample mean | 99.1 | 99.1 |
trend |
least-squares line | 95.3 | 95.3 |
seasonal |
constant + sine wave of period 12, least squares | 97.5 | 97.5 |
trend_seasonal |
line + sine wave of period 12, least squares | 93.9 | 93.9 |
level_shift |
mean after one break, dated by least squares | 96.7 | 96.7 |
mean_reverting |
AR(1) + measurement noise, maximum likelihood | 93.0 | 95.8 |
cycles |
AR(2) + measurement noise, maximum likelihood | 92.6 | 92.9 |
random_walk |
random walk + measurement noise, maximum likelihood | 99.8 | 98.9 |
random_walk_drift |
random walk with drift + measurement noise, maximum likelihood | 87.3 | 90.2 |
Read it beside the score. 100 minus the attainable score is what the row's own model family loses to estimating its parameters from the history. The attainable score minus the model's score is what this model loses beyond that, and that is the part worth investigating.
table = card.table
table.assign(lost_on_top=table["attainable"] - table["score"])[
["title", "noise", "score", "attainable", "lost_on_top"]]
Each Pattern carries the model as attainable_by, copied fresh for each
series. It is an ordinary model with fit(history) and predict(future_index),
so it can be scored like any other:
from timegym import PATTERNS, Pipeline
Pipeline(PATTERNS["trend"].attainable_by).run(["trend"]).scorecard
The four maximum-likelihood fits run a Kalman filter with the scale and the
mean (or the drift) solved for in closed form. A Pattern without
attainable_by (None) has no attainable score (NaN). fitted, its old name,
still works with a warning: Pattern(fitted=...) as an argument, and
Pattern.fitted() returning a fresh model. On the image the attainable score is a
small triangle above each score's line.
The 20 values of the default grid are stored; tools/attainable_table.py
recomputes them. Any other noise level, history length or horizon gets NaN and
no triangle, unless you ask for it:
card = pipeline.run(noise_levels=3, simulate_attainable=True).scorecard
simulate_attainable=True simulates each missing value once and keeps it for the
session. Each autoregressive or random-walk cell takes about 3 to 5 seconds,
the others well under a second; nothing is simulated without it. Its old name
on pipeline.scorecard(...) and timegym.scorecard.scorecard(...),
attainable=True, still works and warns.
Your own kind of series¶
The answer key is what makes a scorecard possible, and you can bring your own:
a kind of series you can simulate, such as a rainfall-runoff model, an outbreak
model or a queue. Write a function that draws one series and says what a
forecaster that knows the process would forecast, wrap it in a Pattern, and
pass it in patterns= beside the keys of PATTERNS. Here is a yes/no row:
rain (1) or no rain (0) at each step, with a chance of rain that rises and
falls over a 12-step cycle.
import numpy as np
from timegym import Pattern, Pipeline, SeasonalMeanForecaster
def simulate_rain(rng, history, horizon, noise):
"""Rain (1) or no rain (0) at each step; the chance of rain follows a 12-step cycle."""
steps = np.arange(history + horizon)
swing = 0.45 / (1 + noise) # 0.30 at low noise (sd 0.5), 0.15 at high (sd 2)
chance = 0.5 + swing * np.sin(2 * np.pi * steps / 12)
rained = rng.random(len(steps)) < chance
ahead = chance[history:] # the chance at each step to forecast
return dict(values=rained, mean=ahead, variance=ahead * (1 - ahead))
rain = Pattern(
key="rain",
title="Rain or no rain",
aka="a yes/no outcome with a chance of rain that follows a cycle",
predictable="The chance of rain at each point of the cycle.",
unpredictable="Whether it actually rains.",
simulate=simulate_rain,
attainable_by=SeasonalMeanForecaster(period=12),
)
model = SeasonalMeanForecaster(period=12)
card = Pipeline(model).run(
["seasonal", rain], # a built-in row beside yours
simulate_attainable=True, # also score each row's own model, fitted to each history
).scorecard
For each series the scorecard calls simulate(rng, history, horizon, noise):
rng is a NumPy random generator seeded by the card, history and horizon
are the lengths the card asks for (120 and 24 by default), and noise is the
column's standard deviation. It is called by position, so the names are
yours. The function returns a dict:
values: every step, history and horizon together. For a yes/no outcome, True and False or 1 and 0. For several series, one column each.meanandvariance: the true mean and variance of each step to forecast, given the history. This is the answer key.covariance(optional): for steps to forecast that move together. Only the dependence check reads it; without it the steps count as independent.
TimeGym cuts the history from the future and builds the case and its answer
key. Before anything runs, the grid draws one series per cell and says what is
missing or has the wrong length. A kind of series that needs more, such as
dates or inputs known in advance, can give build(noise, history_length,
horizon) instead, returning an object with generate(seed), kind,
history_length and horizon, as Scenario has, whose cases carry an answer
key. A Pattern takes simulate or build, not both.
noise is there to use or ignore. The rain row turns higher noise into a
weaker cycle: at low noise (sd 0.5) the chance of rain goes from 20% to 80%
over the cycle, at high noise (sd 2) from 35% to 65%.
For a yes/no outcome the answer key's mean is the chance of rain p and its
variance p(1 − p), so the score needs no change: the unavoidable error is the
expected Brier score of a forecaster that knows p, and the score is the share
of the expected Brier score that no forecaster could avoid. On the rain row,
with the default ten series:
| Forecaster | Low noise | High noise |
|---|---|---|
Seasonal mean, the row's own model, SeasonalMeanForecaster(period=12) |
92 Nails it | 92 Nails it |
Historical mean, MeanForecaster() |
82 Good | 95 Nails it |
Last cycle repeated, SeasonalLastValueForecaster(period=12) |
52 Struggles | 53 Struggles |
The attainable score is 91 in both columns: the seasonal mean, the share of rainy steps at each point of the cycle, learned from ten cycles of history. The historical mean ignores the cycle, which costs about ten points at low noise but wins at high noise: there the chance moves only 15 points either side of 50%, and twelve shares learned from ten steps each are noisier than one share learned from 120. Repeating the last cycle is worse than either, because it copies each step's outcome along with the cycle; the card lists that as a mistake ("Cycle out of step" at low noise, "Too wiggly" at high).
attainable_by takes the row's own model, copied fresh for each series, or a
class or function that returns one. With it and simulate_attainable=True, a pattern of
your own gets an attainable score simulated as for the built-in rows; otherwise
it is NaN, since only the default grid's values are stored. The table,
save_baseline and compare know the row by its key, so keep the key, and the
pattern, the same between two cards you compare. A key of a built-in pattern is
refused, unless you pass that built-in Pattern itself, such as
PATTERNS["trend"].
Mistakes and checks¶
Cells that struggle or fail (a shown score below 70) name up to two mistakes. Each instance's error against the answer key splits exactly into a constant offset (Forecasts too high, Forecasts too low, or Misreads the current level when it is too high in some instances and too low in others), a straight-line drift (Trend too steep, Trend too flat, Misjudges the trend, Invents a trend) and the remaining shape (Misses the cycle, Cycle out of step, Exaggerates the cycle, Too wiggly). A forecast that matches the answer key one step later or earlier is called Values one step late or Values one step early. Failed output checks are mistakes too, for example Wrong dates: shifted 1 step early.
card.checks (and report.checks on any TestReport) lists the output checks
in plain words with how many cases passed and failed:
| Check | Title |
|---|---|
runs |
Runs without errors |
dates |
Forecasts the requested dates |
series |
Returns every series, in order |
shape |
Right number of steps and series |
finite |
No missing or infinite values |
quantiles |
Quantiles in order |
dependence |
Joint spread matches the answer key (only with checks=[dependence()]) |
report.assert_passed() raises with one line per failed check, for example
Forecasts the requested dates: failed in 4 of 4 cases, followed by the
underlying diagnostics.
Seeds and instances¶
instances=10 independent series per cell use seeds seed, seed + 1, ....
The same seeds are used in every cell and the hidden path is drawn before the
measurement noise, so the noise columns are a paired comparison. seed=None
draws a fresh seed and keeps it on card.seed and in the report metadata, so
an interesting run can be repeated. Raise instances (20 or 30) when comparing
close models.
Compare with a saved baseline¶
This is a regression test for forecast quality. The reference is the version of your model that you last trusted. Checking that a new version gives exactly the same forecasts is not a useful test, because every change you make on purpose changes the forecasts too. The answer key makes the comparison mean something: on the same series, is the new version further from the best possible forecast?
# once, on the version you trust
Pipeline(model).run(instances=30).scorecard.save_baseline("scorecard-baseline.json")
# in the test suite, on every change
card = Pipeline(model).run(instances=30).scorecard
diff = card.compare("scorecard-baseline.json") # same seed, so the same series
print(diff)
diff.assert_no_regression()
save_baseline(path) writes a small JSON file and returns path. It holds a
format name and version, the TimeGym version, the card's title, the grid
(pattern keys, noise standard deviations, history length and horizon), the
seed, the number of instances and, for each cell, its score and each series'
avoidable error in instance order, with null for a series that crashed or
failed an output check. Floats are written so that they read back exactly,
and keys are sorted, so the same card always writes the same file. For the
default grid at 30 instances that is 600 avoidable errors, about 17 kB, small
enough to commit beside the tests.
compare(baseline, *, alpha=0.05) takes such a file or another Scorecard
and returns a ScorecardComparison; both give the same result. The two cards
must have the same grid, seed and number of instances, so that they drew the
same series: otherwise compare raises ValueError and says what differs. A
file that is not a baseline, or one written in a newer format than this
TimeGym reads, raises ValueError too. Series come from the seed and from
TimeGym's generators, so if a TimeGym release draws other series for the same
seed, save a new baseline from the version you trust.
Each cell gets one of three outcomes in the change column:
"unchanged": every series came out the same as in the baseline. Each has the same status (scored, or crashed or failed an output check), and its avoidable error agrees with the baseline's up to roundoff: they differ by at most1e-9, or by1e-8times the largest avoidable error in the cell (in either version) if that is larger."changed and worse": on the same series, the new version is further from the answer key by more than chance would explain, or a series that was scored in the baseline now crashes or fails an output check. Only this outcome failsassert_no_regression()."changed, no worse": the forecasts differ, and the test did not find the new version worse.
Four things to keep in mind when you read the result:
- "Changed, no worse" does not mean better. It only means the test did not find the new version worse.
- A small worsening can pass. With few series only large ones are found, so
comparewarns below 20 instances. Use 30. - A very small worsening can fail when it shows up on almost every series. Adding a ridge penalty of 1 to a least-squares regression on six lags raised one cell's mean avoidable error by 0.04% on the default grid at 30 instances, and the comparison called that cell changed and worse. The table and the printed comparison show how far each cell moved, so you can judge whether a worse cell matters. When a change is intended, save a new baseline.
- The test counts each series as separate evidence. That is right when the model handles each series on its own. A model that draws its random numbers from one fixed seed adds the same noise to every series, so with another seed it is a different model, and the comparison can find it worse.
How the test works¶
This part is for readers who want the statistics.
The test is paired: it takes the series scored in both cards and their
differences d = new avoidable error - baseline avoidable error. Its
statistic is the mean of d. It flips the sign of each difference at random
9,999 times and ranks the observed mean among the flipped means with
rank_alarm, a
one-sided p-value for a mean above zero:
p = (1 + number of flipped means >= observed mean) / 10,000
The flips are seeded from the card's seed and the number of pairs, so a
cell's p-value repeats exactly and does not depend on which other patterns
were scored. Because several cells are tested at once, Holm's step-down
correction at alpha runs across the cells that changed, the cells with at
least one difference beyond roundoff. The sign-flip test conditions on the
sizes of the differences, and whether a cell changed depends only on those
sizes and on how large the errors are, which swapping the two values of a
pair does not change, so restricting the correction to the changed cells
keeps the test valid. A series that was broken in the baseline and is scored
now is left out of the test and counted as newly passing.
The test assumes that, when the new version is no worse, the paired differences are not shifted upward: symmetric about zero, or below it. It also assumes that the series' differences are independent.
The same sign flips and Holm's correction compare any two reports in
result.compare,
which asks the two-sided question, better or worse, on your own data too.
ScorecardComparison.table has one row per cell: pattern, title,
noise, noise_sd, change, baseline_score, score,
baseline_avoidable_mse and avoidable_mse (each card's mean avoidable error over
the series it scored), p_value (before Holm's correction; NaN where no
series moved beyond roundoff), and newly_failing and newly_passing, the
numbers of series that crash or fail an output check now but did not in the
baseline, and the reverse. worse holds the rows that are changed and worse.
assert_no_regression() raises AssertionError naming each of them with its
numbers. baseline_version is the TimeGym version that wrote the baseline
and card_version this card's. print(diff) gives a plain summary, and names
the baseline's version when the two differ. This one, from
source notebook 13, compares a lag
regression with an off-by-one bug against the baseline of the correct model,
with 15 of its "changed, no worse" rows left out:
Compared with scorecard-baseline.json (30 series per cell)
17 cells changed, no worse
Pure noise, low noise avoidable error 0.0175 -> 0.0177 (+1.1%)
...
Random walk with drift, high noise avoidable error 5.10 -> 5.02 (-1.6%)
3 cells changed and worse
Repeating seasonal cycle, low noise avoidable error 0.164 -> 1.21 (+635%), p = 0.0001
Mean reversion (AR(1)): shocks fade, low noise avoidable error 0.299 -> 0.358 (+20%), p = 0.0004
Mean reversion (AR(1)): shocks fade, high noise avoidable error 0.497 -> 0.546 (+9.9%), p = 0.0002
The Scorecard¶
Scorecard keeps title, table (one row per pattern and noise level with
score, score_low, score_high, verdict, settled, attainable, mistakes,
unavoidable_mse, avoidable_mse, mse, instances and failed_checks),
run (the ForecastRun with every series and forecast), cells, seed,
instances and interval_level. good_at lists patterns scoring at least 70 at every noise level,
fails_at those below 40 at some level and noise_sensitive those that lose
25 points or more from low to high noise. unsettled holds the table rows
whose verdict is not settled.
report is the JSON-ready TestReport. plot(compact=False) returns the
Matplotlib figure; compact=True draws only the colored scores.
save_baseline(path) writes the card's baseline file and compare(baseline,
*, alpha=0.05) compares the card with one
(Compare with a saved baseline).
Signatures¶
timegym.Scorecard
dataclass
¶
Scorecard(title: str, table: DataFrame, run: ForecastRun, cells: list[GridCell], seed: int | None, instances: int, interval_level: float = 0.95)
What a forecaster gets right and wrong across kinds of series and noise.
table has one row per pattern and noise level: the 0-100 score,
score_low and score_high around it, its verdict, whether that
verdict is settled, the row's attainable score, named
mistakes, the unavoidable and avoidable mean squared errors behind the
score, and the mean squared error against what happened (mse).
pipeline.run(...).scorecard makes it. run is that run, which holds
every series and forecast only if it was made with keep_data=True; the
card keeps the example forecasts it draws either way. report is the
JSON-ready TestReport. In a notebook a Scorecard shows as its image;
plot() returns that picture, print gives Markdown and save
writes the image. A card made from scenarios you built has one row per
scenario and one column, "As built"; it cannot be saved as a baseline.
score_low to score_high is the interval around the score: with
other series of the same kind the score would come out a little
different, and the interval shows by how much. interval_level says
how cautious it is, 0.95 unless the card was made with another. With ten
series it is wide; raise instances to tighten it. It reaches further
below the score than above it: a few series usually carry most of the
error, so a small card more often flatters a model than it wrongs it. It
only knows the series the card drew, so it cannot see a model that fails
on a kind of series the card did not draw. Fewer than two series give no
interval (NaN). A verdict is settled when both ends of the interval
fall in its band; unsettled lists the rows that are not. For the
statistics: each series is left out in turn, the rest are scored, and the
spread of those scores on the log-odds scale, times a Student t quantile,
gives how far the interval reaches above the score; below it reaches
1 + 1/sqrt(n) times as far, with n the number of series.
attainable is what the pattern's own model family (Pattern.attainable_by),
fitted to each history, scores on 200 fresh series of the row: 100 minus
it is what that family loses to estimating its parameters from the
history. It belongs to the row, not to the series this card drew, and is
itself an estimate, good to about a point; a model can land above it on a
given card. The default grid's values are stored. Other noise levels,
history lengths and horizons get NaN unless the card was made with
simulate_attainable=True, which simulates them once per session: about 3 to 5
seconds for each autoregressive or random-walk cell, well under a second
for the others. A pattern of your own gets one only with
Pattern.attainable_by and simulate_attainable=True.
save_baseline(path) writes each series' avoidable error to a small
JSON file, and compare(baseline) compares a later card on the same
series with it, cell by cell; see ScorecardComparison.
report
property
¶
report: TestReport
The structured report of every case, for JSON or assert_passed.
noise_sensitive
property
¶
noise_sensitive
Patterns whose score drops by 25 points or more from low to high noise.
unsettled
property
¶
unsettled
The rows whose interval crosses 90, 70 or 40, or that have too few series for one.
plot
¶
plot(*, compact=False)
Draw the scorecard and return the matplotlib Figure.
The full figure has one row per pattern: what can and cannot be
predicted, an example forecast with its score at each noise level, and
the mistakes found. compact=True draws only the colored scores.
save
¶
save(path, *, compact=False, dpi=150)
Save the image; the file extension picks the format (png, svg, pdf).
save_baseline
¶
save_baseline(path)
Write this card's baseline to a JSON file at path and return path.
The file holds the package version, the title, the grid (pattern
keys, noise standard deviations, history length and horizon), the
seed, the number of instances and, for each cell, its score and each
series' avoidable error in instance order, with null for a series
that crashed or failed an output check. Floats are written so that
they read back exactly and keys are sorted, so the same card always
writes the same file. At 30 instances the default grid stores 600
avoidable errors, small enough to commit beside the tests.
compare
¶
compare(baseline, *, alpha=0.05)
Compare this card with a baseline on the same series; returns a ScorecardComparison.
baseline is a path written by save_baseline or another
Scorecard. Both must use the same grid, seed and number of instances,
so that they drew the same series; otherwise ValueError says what
differs. Each cell is "unchanged", "changed, no worse" or
"changed and worse": worse when, on the same series, the new
version is further from the answer key by more than chance would
explain, or when a series scored in the baseline now crashes or fails
an output check. alpha sets how strict the test is: when nothing
got worse, it calls some cell worse in at most about that share of
comparisons. Below 20 instances it warns, because so few series find
only large regressions; use 30.
timegym.scenario_grid
¶
scenario_grid(patterns=None, noise_levels=2, *, history_length=120, horizon=24)
Return one GridCell per pattern and noise level, rows first.
patterns lists keys of PATTERNS (all ten by default, in their
order) and Pattern objects of your own. noise_levels is as in
noise_levels(): two by default, low and high. Scenarios carry no seed
of their own; the run supplies it.
Your own pattern needs a key that no built-in pattern has, a title, and
one of two functions. simulate(rng, history_length, horizon, noise)
returns one series and the true mean and variance of each step to
forecast, as Pattern says. build(noise, history_length, horizon)
returns an object with generate(seed), kind, history_length
and horizon, as Scenario has, whose cases carry an answer key: a
reference holding the true mean and variance of what happens. The grid
draws one case per cell before anything runs and says what is missing.
noise is the noise level's standard deviation; a pattern may use it
or ignore it. The old keyword context_length= still works and warns.
timegym.GridCell
dataclass
¶
GridCell(pattern: str, title: str, noise: str, noise_sd: float, scenario: Scenario, definition: Pattern | None = None)
One pattern at one noise level: its labels and its Scenario.
definition is the Pattern the row comes from: one of PATTERNS, or
your own.
timegym.scorecard.verdict
¶
verdict(score)
Name the band of a 0-100 score; None (nothing scorable) stays None.
timegym.scorecard.ScorecardComparison
dataclass
¶
ScorecardComparison(table: DataFrame, baseline: str, baseline_version: str | None, card_version: str | None, instances: int, seed: int, alpha: float)
A scorecard compared, cell by cell, with a saved baseline on the same series.
table has one row per pattern and noise level: change (one of
"unchanged", "changed, no worse" and "changed and worse"),
the baseline's and this card's score and mean avoidable error over the
series each scored (baseline_score, score,
baseline_avoidable_mse, avoidable_mse), the paired test's p_value
before Holm's correction (NaN where no series moved), and the number of
series that newly_failing crash or fail an output check and that are
newly_passing. worse holds the rows that are changed and worse,
and assert_no_regression() raises when there are any. baseline
names the baseline: the file's name, or the baseline card's title.
baseline_version is the TimeGym version that wrote it and
card_version this card's; the printed comparison names the baseline's
version when the two differ.
A row is unchanged when every series has the same status and its avoidable error agrees with the baseline's within roundoff. It is changed and worse when, on the series scored in both, the new version is further from the answer key by more than chance would explain, or when a series scored in the baseline now crashes or fails an output check. Otherwise it is changed, no worse. That does not mean better, and a worsening too small for the number of series passes.
The statistics: the paired differences of avoidable error get a one-sided
sign-flip test with 9,999 flips, and Holm's correction at alpha runs
across the rows where a series moved. The test assumes that, under "no
worse", the paired differences are not shifted upward (symmetric about
zero, or below it), and that the differences of different series are
independent, as they are when the model treats each series on its own.
timegym.Pattern
dataclass
¶
Pattern(key, title, aka, predictable, unpredictable, build=None, attainable_by=None, *, simulate=None, fitted=None)
One row of the scorecard: a kind of series, in plain words.
predictable says what a perfect forecaster could get right;
unpredictable what no forecaster can, by design.
The row's series come from one of two functions. simulate(rng,
history_length, horizon, noise) draws one series and returns a dict:
values for all history_length + horizon steps (one column per series
when there are several), and the mean and variance of each step to
forecast, given the history. An optional covariance is for future steps
that move together; without it they count as independent. rng is a
NumPy random generator seeded by the scorecard and noise the column's
standard deviation, which a pattern may use or ignore. TimeGym builds the
case and its answer key from these. build(noise, history_length,
horizon) instead returns a whole Scenario for one noise level, as the
built-in rows do: the noise is the standard deviation of the random error
on each observation. TimeGym passes these arguments by position, so your
function may name them as it likes.
attainable_by is a model of the generator's own family with every
numeric parameter unknown, with fit(history) and predict(future_index):
a model object, copied fresh for each series, or a class or function that
returns a fresh one. Its score on the row is the row's attainable score; a
pattern without one (None) has none. fitted is its old name and still
works, with a warning.
You can make your own Pattern and pass it to scenario_grid or
Pipeline.scorecard beside the keys of PATTERNS: a kind of series you
can simulate, with its own answer key.
fitted
property
¶
fitted
The old name of attainable_by: a function that returns a fresh model, or None.
timegym.grid.noise_levels
¶
noise_levels(levels=2)
Return (name, sd) pairs from low to high noise.
An integer n >= 2 spaces n levels geometrically between
NOISE_LOW and NOISE_HIGH, so every grid keeps both extremes and
fills the range between them. A sequence of positive standard deviations
is used as given, sorted.