Scenarios and references¶
In short. A Scenario is a recipe for a kind of series. generate(seed)
draws one Case from it: the past your model sees (case.task), the future
that then happened (case.observed), and the answer key (case.reference):
the expected value and the spread of every future step, given that past. Your
model never sees the future or the answer key; only the scorer does.
Synthetic scenarios describes each recipe in plain terms.
Scenario(kind, history_length=120, horizon=12, parameters=<factory>, n_targets=1,
seed=0).generate(seed=None) returns a Case(task, observed, reference, manifest).
Core kinds: white_noise, trend, seasonal, ar1, random_walk. Additional
joint-capable kinds: composite, merton_jump_diffusion, garch,
markov_switching. Parameters are
validated and serialized in their resolved form, including target-wise values
and the innovation correlation matrix. The four additional controlled families
resolve their parameters once at construction; create a new Scenario to change
them. Their scalar manifests retain scalar values, accepting a one-target
correlation without adding dependence fields. All random draws use local generators.
Case is defined in timegym.contracts and is also importable from timegym and
timegym.scenarios.
scenario.display_name provides the same parameter-aware name used in plots.
Configurations and reports record the identifiers, not the display names.
| Identifier | Display name | What a shock does |
|---|---|---|
white_noise |
Gaussian white noise (fixed mean) | A fresh deviation from a fixed mean; no carryover |
trend |
Linear trend + white noise | A fresh deviation from a deterministic line; no carryover |
seasonal |
Seasonality + white noise | A fresh deviation from a deterministic cycle; no carryover |
ar1 |
Stationary AR(1) | Its effect decays, possibly alternating in sign |
random_walk, drift=0 |
Random walk without drift | Its effect persists in the level |
random_walk, nonzero drift |
Random walk with drift | Its effect persists, alongside an expected change per step |
A random walk is not white noise in levels. It accumulates white-noise
innovations: Y[t] = Y[t-1] + drift + epsilon[t]. Its increments, after
subtracting the drift, are white noise. By contrast, the trend scenario is
Y[t] = intercept + slope*t + epsilon[t]: only its deterministic mean trends;
the noise does not accumulate. With known parameters, a scalar random walk's
conditional variance at horizon h is h*sigma**2, whereas white noise,
linear trend plus white noise and fixed seasonality plus white noise all have
variance sigma**2 at each horizon.
A walk with zero drift can still appear to trend in one realization.
drift defaults to zero and can differ across targets. Plot facets label each
target separately; a case combining zero and nonzero drifts is labeled
“Random walk (mixed drift across targets)” in aggregate views. The helper
timegym.scenarios.scenario_label(kind, parameters=None, *, target_index=None) also
formats recorded manifest parameters and leaves unknown custom kind names
unchanged.
Reference.mean and variance are H × D; covariance is (H·D) × (H·D) in
horizon-major C order. sample(n_samples, seed) returns S × H × D and
quantile(levels) returns H × D × Q. forecast(n_samples=256, seed=0, levels=DEFAULT_LEVELS) constructs
an explicitly privileged reference forecast for diagnostic calibration.
timegym.contracts.DEFAULT_LEVELS is (0.1, 0.5, 0.9); it also supplies the
default marginal levels for the Gaussian AR(1) model.
The five core families have exact known-parameter Gaussian reference laws. For AR(1), |phi| < 1 and the history starts in its stationary distribution. A random walk starts at its configured intercept at index zero. Future innovations are integrated out.
ar2 is a stationary AR(2), Y[t] - mean = phi1*(Y[t-1] - mean) +
phi2*(Y[t-2] - mean) + epsilon[t], defaulting to phi1=1.0, phi2=-0.5,
sigma=1.0. It requires phi1 + phi2 < 1, phi2 - phi1 < 1 and |phi2| < 1
and starts in its stationary distribution. With complex roots its shocks ring
and fade, giving irregular cycles with no fixed period. It is a known-parameter
kind but not one of CORE_KINDS, so the default suite is unchanged.
ar1, ar2 and random_walk accept an optional noise parameter: the
standard deviation of measurement noise added to each observation of the
hidden process. The noise is drawn after the process shocks, so changing it
keeps the hidden path. With noise set (and always for ar2) the reference is
the exact Kalman-filter prediction given the noisy history, and
reference.conditioning["reference_method"] is "kalman_filter". Without
noise, ar1 and random_walk keep their analytic references and manifests.
The five core families are listed by timegym.scenarios.CORE_KINDS, derived from
the scenario defaults. timegym.scenarios.default_scenarios(history_length=120,
horizon=12, *, n_targets=1, seed=0) creates fresh specifications for those families.
The old Pipeline.test() drew them when given no scenarios; Pipeline.run()
draws the scorecard's ten kinds instead.
Signatures¶
timegym.Scenario
dataclass
¶
Scenario(kind: str, history_length: int = 120, horizon: int = 12, parameters: dict[str, Any] = dict(), n_targets: int = 1, seed: int = 0)
A fully specified known-parameter data-generating process.
Vector-valued location/scale parameters are allowed, with one entry per
target. phi, phi1, phi2 and period are scalar.
correlation is either an equicorrelation coefficient or a
positive-semidefinite correlation matrix.
AR(1) starts from its stationary distribution and requires abs(phi)<1.
AR(2) uses two lags, phi1 and phi2; with phi1**2 + 4*phi2 < 0
its shocks ring as irregular cycles. It also starts stationary.
White noise fluctuates around a fixed mean; trend and seasonal processes
add noise independently over time to a deterministic mean. Those shocks
do not carry into future observations. A random walk instead accumulates
shocks, starts at intercept at index zero, and has optional drift
(zero by default). Its variance grows with the forecast horizon. Targets
may have correlated contemporaneous innovations in every family. Zero
sigma gives a degenerate deterministic component. AR(1), AR(2) and
random walks accept an optional measurement noise: an independent
Gaussian error with that standard deviation is added to each
observation, so the process's current state is hidden; the reference is
then the exact Kalman-filter conditional law. Parameters are exposed
to the evaluator only; a model receives just case.task. The
composite, Merton, GARCH and hidden-regime processes also support joint
targets, with explicit dependence laws and reference capabilities. These
four controlled families snapshot resolved parameters at construction;
create a new Scenario to change their parameters.
history_length is the number of steps of history a case holds and
horizon the number to forecast. context_length is the old name of
history_length; it still works and warns.
context_length
property
writable
¶
context_length: int
The old name of history_length; it still works and warns.
display_name
property
¶
display_name: str
Parameter-aware label; kind remains the stable scenario identifier.
generate
¶
generate(seed: int | None = None) -> Case
Generate the history and held-out observations without global RNG state.
timegym.Case
dataclass
¶
Case(task: ForecastTask, observed: DataFrame, reference: Reference | None, manifest: dict[str, Any])
One held-out forecast task and its evaluator-only ground truth.
timegym.Reference
dataclass
¶
Reference(mean: ndarray, variance: ndarray, covariance: ndarray, index: Index, target_names: tuple = ('y',), kind: str = 'analytic_conditional', functional: str = 'mean', conditioning: dict[str, Any] = dict())
A Gaussian conditional law given observed history and known parameters.
This is an analytical diagnostic reference. Knowing generator parameters is an information advantage over an estimated forecasting model and must not be interpreted as attainable real-world performance.
from_function
classmethod
¶
from_function(mean_function: Callable[[Index], ndarray | DataFrame], index: Index, *, covariance: ndarray, target_names: tuple = ('y',), conditioning: dict[str, Any] | None = None) -> Reference
Evaluate a user-supplied mean under an explicitly Gaussian noise law.
mean_function(index) returns H,D values in target order, or a
DataFrame with exactly matching labels. Covariance uses flattened
horizon-major, target-minor order. It is required: knowing a mean does
not imply zero noise or identify a conditional distribution.
The function is evaluated once and is not retained or serialized.
Supply only evaluator-known truth, not a fitted estimate presented as
ground truth. For non-Gaussian laws, use SimulationReference.
sample
¶
sample(n_samples: int, seed: int = 0) -> np.ndarray
Draw joint futures with an isolated random generator, shape S,H,D.
quantile
¶
quantile(levels: tuple = DEFAULT_LEVELS) -> np.ndarray
Return analytical marginal Gaussian quantiles, shape H,D,Q.
forecast
¶
forecast(n_samples: int = 256, seed: int = 0, levels: tuple = DEFAULT_LEVELS) -> Forecast
Construct a correctly aligned forecast from this reference law.
timegym.SimulationReference
dataclass
¶
SimulationReference(mean: ndarray, variance: ndarray, covariance: ndarray, index: Index, target_names: tuple = ('y',), kind: str = 'analytic_moments_simulation', functional: str = 'mean', conditioning: dict[str, Any] = dict(), sampler: Any = None, moments_kind: str = 'analytic', sampler_kind: str = 'exact_conditional', quantile_samples: int = 8192, quantile_seed: int = 0, moment_samples: int | None = None, moment_seed: int | None = None)
Conditional moments with an explicit joint future simulator.
Unlike Reference, this class never infers a Gaussian law from
moments. sampler(n_samples, seed) must return independent conditional
trajectories in S,H,D order, using its supplied seed without global
random state. Exactness is a declared generator capability, not something
this shape contract can establish. Approximate simulators remain useful
descriptively but cannot calibrate an exact-reference diagnostic.
Marginal quantiles are deterministic Monte Carlo estimates from a separate declared seed and sample count. They are not analytical quantiles. Means are analytical. Covariance may be analytical or explicitly marked as a reproducible Monte Carlo estimate with its own sample count and seed.
capabilities
property
¶
capabilities: dict[str, Any]
Fresh JSON-safe metadata, without serializing the sampler callable.
sample
¶
sample(n_samples: int, seed: int = 0) -> np.ndarray
Validate and draw joint futures from the supplied conditional law.
quantile
¶
quantile(levels: tuple = DEFAULT_LEVELS) -> np.ndarray
Estimate marginal quantiles from the declared reproducible ensemble.
timegym.scenarios.scenario_label
¶
scenario_label(kind: str, parameters=None, *, target_index=None) -> str
Describe a process without replacing its stable machine-readable kind.
Parameters may be raw scalar/vector values or a resolved case manifest's
parameter dictionary. A target index selects its drift for a plot facet;
otherwise a mixed zero/nonzero drift vector is described at case level.
Nonzero measurement noise is named in the label. This formats labels
rather than validating a full generator specification. Unknown custom
kinds are returned unchanged.
timegym.scenarios.default_scenarios
¶
default_scenarios(history_length=120, horizon=12, *, n_targets=1, seed=0)
Return fresh specifications for the five core families.
Call generate on each specification to draw a case. The same supplied
seed is recorded in each specification. Use independent replicate seeds
when aggregating experimental results. context_length is the old name
of history_length; it still works and warns.