Skip to main content

TimeGym

A gym for time series forecasting algorithms.

Documentation Checks PyPI License: MIT

OpenAI Gym gave reinforcement-learning agents a standard set of environments to train and be tested in. TimeGym does the same for forecasters. It generates time series whose future it already knows the odds of: noise, trends, seasons, sudden shifts, cycles, levels pulled back to their mean, random walks, each at low and at high noise. It hands your forecaster the past, asks for the future, and scores the answer against the truth. One picture shows what your algorithm nails, where it struggles and where it fails.

Documentation · Quick start · Examples · Tutorials · API · Changelog

Sixty seconds

pip install timegym

Python 3.11–3.15 (>=3.11,<3.16), following pandas support.

Wrap your forecaster in a Pipeline and ask for its scorecard. The built-in LastValueForecaster, which repeats the last value it saw, stands in for yours here:

from timegym import LastValueForecaster, Pipeline

pipeline = Pipeline(LastValueForecaster())   # put your own forecaster here
card = pipeline.scorecard()
card.save("scorecard.png")

The scorecard of the last-value forecaster: a score per kind of series and noise level, with example forecasts

Each row is a kind of series and each column a noise level. The left column says what can and cannot be predicted for that kind of series, and the right column names the mistakes the model made there. A score of 100 means the forecasts were as close as those of a forecaster that knows exactly how the series was made; 50 means the model's avoidable error is as large as the noise nobody could avoid. The bands read "Nails it" from 90, "Good" from 70, "Struggles" from 40 and "Fails" below that. The last-value forecaster scores 51: it nails the random walk and fails trends and seasons. The short line beside each score is its 95% interval on a 0 to 100 scale, and a question mark means that interval reaches into another band; pipeline.scorecard(instances=30) narrows it, and interval_level=0.99 asks for a wider, more cautious one. The small triangle above that line is what the right kind of model, fitted to the same history, would score: the distance from the score up to the triangle is what your model loses beyond estimating the parameters. In a notebook, card on its own shows the picture.

Scorecard, test and report

A scorecard is a test on TimeGym's ten kinds of series, drawn as one picture. "Test" is what TimeGym does; the report is the record it hands back. Three calls give you three views of the same work:

You call You get Use it to
pipeline.scorecard() A Scorecard: the picture and its table See what the model is good and bad at
pipeline.test(scenarios) A TestReport: every case's scores and output checks Test series you choose, save them as JSON, fail a CI build
pipeline.run(scenarios) A ForecastRun: the report plus every series and forecast Plot the forecasts behind the scores

A scorecard carries the other two: card.report and card.run.

More things to do with a scorecard

Print it as Markdown, for a pull request or a log:

print(card)
## LastValueForecaster: 51/100

| Pattern | Low noise | High noise | Mistakes |
|---|---|---|---|
| Pure noise | 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 |
| Random walk: shocks never fade | 99 Nails it | 87 Good? | none found |
…

14 of 20 verdicts are not settled at 10 instances. Run scorecard(instances=30) to narrow them.

Zoom in on one row:

trend = pipeline.scorecard(["trend"], instances=3)   # one row, both noise levels

Plot every draw behind that row, with the answer key and the forecast:

trend.run.plot_forecasts()

The three draws of the trend row at each noise level, with the answer key and the last-value forecast

See how the error spreads over 20 draws per noise level:

pipeline.scorecard(["trend"], instances=20).run.plot_errors(metric="mse")

Histograms of the error against what happened, 20 draws at low and at high noise

mse is the error against what actually happened. The default, mean_reference_mse, is the error against the answer key: the part your model could have avoided.

For CI and for later:

card.report.assert_passed()          # fail a CI build on a malformed forecast or a crash
card.report.to_json("report.json")   # every case, enough to replay one on another machine

To catch a change that makes the model worse, save the scorecard of the version you trust and compare each later version with it on the same series. A paired test says, cell by cell, whether the new version is further from the answer key:

pipeline.scorecard(instances=30).save_baseline("scorecard-baseline.json")  # once
diff = pipeline.scorecard(instances=30).compare("scorecard-baseline.json")
diff.assert_no_regression()          # fail a CI build on a cell that got worse

On your own data, which has no answer key, timegym.compare_reports pairs two reports case by case and says whether the candidate is better, worse, or shows no clear difference, by group if you ask (Scores and diagnostics). Checks of your own join the built-in ones with checks=, such as within(0, None) for rainfall or sales, which can't go below zero (Your own output checks). A kind of series you can simulate, with its answer key, becomes a scorecard row of your own: pass a Pattern in patterns= beside the built-in keys (Your own kind of series).

The Quick start shows the rest: the scorecard as a DataFrame (card.table), how many draws to use and what seed=None does, and pipeline.test on series you choose. Scorecards and the scenario grid lists every attribute.

Why not just backtest?

A backtest compares your forecast with the one future that happened. That future is noisy, so a lucky model looks good and a sound one can look bad. TimeGym made the data, so it holds the answer key: the expected value and the spread of every future step. It scores your forecast against that key, which measures skill rather than luck.

A score can also hide a bug. Put the right numbers on the wrong dates and any scorer that compares arrays gives them exactly the same error. TimeGym checks the dates, the series and the shape first, and fails the forecast with the reason before it scores anything.

A forecast with the right values on the wrong dates: the same error, a different diagnosis

Bring your own model

A forecaster is any object with two methods. fit(context) gets the series so far. predict(future_index) gets the dates to forecast, the steps right after the context, and returns one value per date: a Forecast, or simply a list or NumPy array. This one repeats the last value it saw:

from timegym import Forecast, Pipeline

class RepeatLast:
    def fit(self, context):            # the series so far, one column per series
        self.last = context.iloc[-1]   # the last row seen
        return self

    def predict(self, future_index):   # the dates to forecast
        return Forecast(future_index, [self.last] * len(future_index))

card = Pipeline(RepeatLast()).scorecard()

It scores 51, like the built-in LastValueForecaster. Write and test a custom model adds several series, quantiles and a nearest-analogues forecaster.

scikit-learn regressors plug in directly, fed the last window_length values:

from sklearn.linear_model import Ridge

card = Pipeline(Ridge(), window_length=12).scorecard()

What TimeGym checks

Every forecast goes through three questions, in this order.

1. Is the forecast well-formed? These output checks run on every forecast (in the code, the forecast contract):

  • Forecasts the requested dates; a failure says how many steps they are off
  • Returns every series, in order
  • Right number of steps and series
  • No missing or infinite values
  • Quantiles in order, when the forecast has quantiles
  • Runs without errors

A forecast that fails a check fails the test with the reason and is never scored, so a bug cannot pass as a slightly worse error.

2. How far is it from the answer key? Because TimeGym generated the series, it knows the expected value and the spread of every future step (in the code, the reference), so your forecast is scored against both the key and what actually happened.

3. Does it do what you declared? Optional checks for specific properties: a model that claims to shift its forecast when the data shift can be tested for it, and sample paths can be tested for the right correlation between series.

Each check returns one of five verdicts (PASS, FAIL, INCONCLUSIVE, UNSUPPORTED, ERROR) and the numbers that led to it. Scores are always INCONCLUSIVE: TimeGym tells you how far off you are and leaves the pass mark to you. How TimeGym decides explains each verdict, and Scores and diagnostics each score.

Scenarios

The scorecard's rows are ten kinds of series, from pure noise to random walks with drift, each drawn at low noise (standard deviation 0.5) and high noise (2.0). For each one TimeGym knows what a forecast can get right and what nobody can predict; the scorecard prints both, and Scorecards and the scenario grid lists all ten. The scenario guide explains each kind in plain terms, why mean reversion and the random walk are the same equation, and the composed and financial ones beyond the scorecard: price jumps, volatility clusters (GARCH) and hidden regime switches, alone or across several correlated series.

Examples

Forecasting jobs on real public data, from the first model to a decision, with TimeGym in the loop. The examples page shows them with their results and says how to run them.

Example What TimeGym showed
Weekly shop sales: from forecast to stock order Why the usual regression loses to a plain average on a gift shop's products, and which simpler forecaster leaves fewer units out of stock
Spare parts: the best score goes to a forecast of zero The lowest average error belongs to a forecast of zero; a score in the parts counter's terms names the forecaster that keeps parts on the shelf
The Christmas order: five Decembers cannot pick the forecaster A shop with five Decembers to test on: one argument fixes a forecast that came in at half, two forecasters tie, and generated shops with a known answer show what each choice costs
Call center staffing: forecast again at ten o'clock What a newer forecast is worth to a staffing plan: yesterday's surprise 15%, the calls taken by 10:00 another 12%, and trusting the morning in full makes it worse
Train station riders: what is the weather worth, at best? Is a weather feed worth building? Told the real weather, a ridership forecast gains under 2% on weekdays and 8% on weekends, and nothing at some stations
Daily births: how much history should a forecast learn from? Each part of a forecast has its own best look-back: all the history makes the week 28% worse, one year makes the season 12% worse, and a generated series with a known change shows why
Tomorrow's electricity demand: let the worst days say what is missing Which days a day-ahead forecast gets wrong, round by round: the weekday, then public holidays, then weather the data lacks
Solar farm output: a range for every half hour is not a range for the day Two forecasts with the same range for every half hour: one range for the day's energy holds on 84% of days, the other on 33%, and only a score for the whole day sees the difference
River flow: checking the range, not only the forecast A 90% range that holds on average but not month by month, the one argument that repairs it, and how far it fails when the river rises
Will it rain tomorrow? Score the forecast you already have A yes/no forecast scored as a probability: our best forecaster gains 11% on the long-run share, the weather service's published forecast 53%
Tomorrow's temperature: which city should Sydney watch? Forecasting several series together: Melbourne's record cuts the miss on Sydney's high by 14%, and Darwin's makes it worse
Tomorrow's air in London: the gaps someone filled in for you Scores earned against filled-in readings: a table with no gaps makes every forecast look a fifth better than it is, and the silent monitors look easiest
Flu season: the calendar knows the rhythm, not the peak A forecaster that learns the season from earlier winters: ahead when the peak keeps its week, the worst of four when it comes late, and far below every peak four weeks before
The sunspot cycle: how far ahead is a forecast worth making? A regression that leads for two years ahead and adds nothing after
El Niño: how far ahead depends on the month you ask A backtest's "seven months ahead" split by the month each forecast was made: nothing gets across April, and the rest is still ahead at nine months
The forest that cannot follow growth A random forest that passes its backtest cannot forecast a trend, and the textbook fix makes it worse elsewhere
You tried 50 models: is the winner real? The winner of a 50-setting backtest leads by 0.2%; nine others cannot be told apart from it, and the next year it comes tenth
Ready-made model or your own? Five products decide A pretrained model far ahead on the scorecard and 22% behind on the backtest average: five products carry the gap, and generated series with a known answer show when the error happens
A traffic jump: is this the new normal? The forecaster that is as good as any on ordinary days is the worst three days into a jump, and the usual backtest cannot show it
Site capacity: which forecast still works four weeks ahead? Two forecasters that are level for next week are far apart four weeks ahead, where capacity is booked, and a one-day slip shows up on a generated weekly cycle before any real data
Bitcoin: finding out you have nothing A 79% hit rate that came from one input reaching into the future
The S&P 500 next week: the direction and the size are different questions The direction cannot be forecast and the size can: a range that follows recent weeks holds in crashes, checked year by year

Tutorials

Group Notebook What it shows
Start Quick start Two scorecards, last value against Ridge: each is blind where the other sees
Write and test a custom model The six-line RepeatLast model, nearest analogues, real data
Find what breaks Faults, repairs and replay Four ways to break a correct forecast, a bug caught by a broken promise, replay
Shape the forecast Target transforms Why logs help when the swing grows with the level, and why exp(mean log) is too low
Reductions Recursive, direct and multioutput: when recursive errors compound
Multivariate forecasting Right numbers under the wrong series name; when extra history doesn't help
Real-data forecasts No answer key: four origins, three baselines, a leakage check
Measure uncertainty Univariate uncertainty Same predictions, overconfident spread: which scores notice
Multivariate uncertainty Scrambled pairings: every series right, joint risk gone
Stress-test Capability sweeps Three simple bets, and where each breaks as history and noise change
Composed and financial stresses A ladder of mechanisms, bad luck vs a bad model, a conversion bug
Joint financial uncertainty Assets that crash together, and the check that notices a lost link

The tutorials run on CPU with local data; Run the notebooks gives the two commands, and the tutorials guide describes the folder.

Scope and development

TimeGym tests forecasters; it does not fix them. It does not find the root cause of a bug, repair a model, detect data leakage in general, or work out an answer key for data you bring yourself: real data is scored against what happened, and the checks that need a key say UNSUPPORTED. To score your own data, cut a series into cases with cases_from_series and pass them to pipeline.test(cases=...); forecasts made elsewhere are scored with ForecastRun.from_forecasts. Panels, hierarchies and missing observations are out of scope for now; Data preparation shows how to put readings taken at irregular times on a regular grid without letting the future in. What TimeGym tests, and what it does not draws the line in more detail, and Extend TimeGym lists every place to plug in your own code and data.

The package is written in notebooks: the source notebooks in source/ generate every module in timegym/. Contributing describes that cycle, and releasing the version numbers and how a merged pull request becomes a PyPI release.

Cite

Cite the software by version; GitHub's "Cite this repository" reads the same metadata from CITATION.cff. When a release is archived on Zenodo, cite that release's DOI.

@software{seca2026timegym,
  author = {Seca, Diogo},
  title = {{TimeGym: verification and diagnosis for forecasting pipelines}},
  year = {2026},
  version = {1.13.1},
  url = {https://github.com/diogoseca/timegym},
}

Seca, D. (2026). TimeGym: verification and diagnosis for forecasting pipelines (Version 1.13.1) [Computer software]. https://github.com/diogoseca/timegym

The 2021 preprint (arXiv version 1, the original prototype):

@article{seca2021timegym,
  author = {Seca, Diogo},
  title = {{TimeGym: Debugging for Time Series Modeling in Python}},
  year = {2021},
  doi = {10.48550/arXiv.2105.01404},
  url = {https://arxiv.org/abs/2105.01404v1},
}

MIT license. Datasets and cited works keep their own attribution; see data provenance.

Metadata

Release files for timegym 1.13.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for timegym 1.13.1
File Size Uploaded Provenance Actions
timegym-1.13.1.tar.gz 22.8 MB With provenance Details for timegym-1.13.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for timegym 1.13.1
File Interpreter ABI Platform Actions
timegym-1.13.1-py3-none-any.whl Python 3 none any Details for timegym-1.13.1-py3-none-any.whl

Total release size: 23.0 MB

Release files / timegym-1.13.1.tar.gz

Download URL timegym-1.13.1.tar.gz
Size 22.8 MB
Tags Source
SHA-256 checksum
How to use checksums
c5041b93ecc8c5c5bcd6d3ef6f40bda7887bc396cdf1be8dc4b1157e9bf150a5
BLAKE2b-256 checksum
How to use checksums
03c2c6d5a2df8f99d76c7b44f53e74d80d285350ed45735a69862c9f885e5fb4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

Release files / timegym-1.13.1-py3-none-any.whl

Download URL timegym-1.13.1-py3-none-any.whl
Size 146.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
acda6e35843afb90c91a66918e82f0fb65c605646fb574768b6900cff69894cc
BLAKE2b-256 checksum
How to use checksums
97e623e1eaa56a1a66a97498fb23bfc4dfaada60c5f79a310d5f50c8fda63af9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

Security for timegym 1.13.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for timegym-1.13.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page