hypertools.predict¶
- hypertools.predict(data, model='Kalman', t=10, return_model=False, holdout=None, metrics=None, per_column=False, return_forecasts=False, **kwargs)[source]¶
Forecast t new rows continuing each input dataset.
- Parameters:
- dataDataFrame/array or list/tuple of these
Dataset(s) to forecast from, each shaped (n_observations, n_features) with at least 2 observations (rows). A 1-D array, a flat list of numbers, or a pandas Series is treated as a UNIVARIATE timeseries – n observations of 1 feature, i.e. an (n, 1) column – matching hyp.plot/format_data’s convention; a tuple of datasets is treated exactly like a list. Degenerate inputs (None, a scalar, empty data, fewer than 2 rows) raise a clear error instead of returning meaningless forecasts.
HIERARCHICAL input (1.1). A BARE DataFrame carrying a MultiIndex on one axis is split into groups and forecast one group at a time (see
docs/hierarchy.rst):a COLUMN MultiIndex groups by every level ABOVE the innermost one; the innermost level is the FEATURE axis, so each group keeps all len(data) observations. A
(Market, Sector, Measure)frame gives one forecast per sector, each with the three Measure columns. Feature correspondence across groups is NOMINAL (the shared rule in hypertools.core.hierarchy.group_columns, which the plotting path needs so per-level means are meaningful): every group must carry the SAME innermost labels – duplicates matched by (label, occurrence) – so a frame whose groups name different features (different sensors per rig) or have different widths raises a ValueError instead of forecasting; if the groups really are incommensurable, slice them yourself and forecast one flat frame per group. When groups share labels in a DIFFERENT order, later groups are permuted into the first group’s order, so a group’s forecast columns follow that order rather than its own.a ROW MultiIndex groups by every level ABOVE the innermost one; the innermost level is the TIME axis and SURVIVES as each group’s index (it is dropped from the grouping levels, not reset), so a datetime innermost level keeps its DatetimeIndex and t may be a future Timestamp. Because the index survives, a group whose times are out of order raises the usual “not sorted in ascending order” warning with its group name prepended, and a group whose TIME index (DatetimeIndex/TimedeltaIndex/PeriodIndex) has DUPLICATED entries raises a ValueError naming it (the horizon is ill-defined when several observations share one position on the time axis). That rejection is resolve_t’s, so it applies to FLAT time-indexed input too – a change from 1.0, which forecast such frames. Integer-indexed panels are not affected, whether or not their index repeats (a stacked
pd.concat([run_a, run_b])still forecasts).
Each group is forecast by a RECURSIVE predict call. That terminates because grouping FLATTENS each group on the axis it grouped along, so no group can be re-detected as hierarchical (hypertools.core.hierarchy’s one invariant). Arguments that describe the WHOLE call – t and the model= spec – are checked ONCE before that loop, so a bad horizon or an unknown model name is reported plainly instead of being blamed on the first group. What the loop prefixes with the group’s key is a per-group ValueError (the type every data-shaped rejection raises: too short a history, duplicated times), so a group that is too short to forecast says which one it was. Other exception types propagate unchanged; a group’s WARNINGS, however, are always re-emitted with its key, whatever the group failed with.
A frame with a MultiIndex on BOTH axes raises (which hierarchy wins is undefined), and so does a hierarchical frame nested inside a list/tuple – the hierarchy determines the whole group list, which cannot be reconciled with a caller-supplied list of datasets.
- modelstr, dict, class, Forecaster instance, or a COLLECTION of these
Which forecaster to use (default: ‘Kalman’).
SEVERAL MODELS AT ONCE (1.1). A LIST or TUPLE of specs forecasts each of them and returns a
{name: forecast}dict in the order given – the shapehyp.plot(..., predict=['Kalman', 'ARIMA'])consumes. Names come from the specs (a string’s registry spelling, a dict spec’s inner model, a class/instance’s__name__) and repeats are numberedKalman,Kalman (2), …; pass a DICT MAPPING NAMES TO SPECS –model={'tiny Chronos': {'model': 'Chronos', 'kwargs': {...}}}– to name them yourself. (A dict carrying any ofmodel/args/kwargs/paramsis a single spec, not a mapping.)'truth'is reserved as a name. Withholdout=, the collection becomes one scored ROW per model instead.A string is one of FORECASTERS’ names (Kalman, GaussianProcess, AutoRegressor, ARIMA, Laplace, Chronos); the short alias ‘GP’ also resolves to GaussianProcess, and names are matched case-insensitively (‘kalman’ works too). A dict may be
{'model': ..., 'params': {...}}(deprecated) or{'model': ..., 'args': [...], 'kwargs': {...}}. A class or an already-constructed (unfitted) instance is used directly. An ALREADY-FITTED Forecaster instance (returned from a previousreturn_model=Truecall) is applied to data via predict_new (its learned parameters are reused – not re-estimated).Note that the models’ default configurations suit different signals: Kalman/AutoRegressor/GaussianProcess track oscillatory and trending data out of the box, while ARIMA(1, 1, 1) and Laplace defaults only suit drift/random-walk-like signals (see hypertools.predict.arima / hypertools.predict.laplace).
NaN policy: Kalman, ARIMA, and Chronos tolerate missing (NaN) entries; GaussianProcess, AutoRegressor, and Laplace raise a clear ValueError (fill missing values first, e.g. with hyp.impute).
Ownership on HIERARCHICAL input, where one model is needed per group. The caller’s instance is never mutated either way, and
return_model=Truereturns one distinct object per group:a name, a class, a dict spec, or an UNFITTED instance: one independent model is FITTED PER GROUP. An unfitted instance is deep-copied per group, so the caller’s object is never fitted and later groups do not fall onto the predict_new path just because an earlier group fitted the shared object.
an ALREADY-FITTED instance: its learned parameters are REUSED on every group (via predict_new), each through an independent deep copy – the reuse promised above, applied group-wise rather than refitting.
- tint or datetime-like
Forecast horizon (see hypertools.predict.common.resolve_t). A datetime-like t at or before the data’s last timestamp truncates the history up to t instead of forecasting; a t BEFORE the data’s first timestamp raises a ValueError (there is no data to truncate to and nothing to forecast – it used to silently return an empty frame).
- stepnumber, duration string, Timedelta, calendar offset, or None, optional
Constructor keyword for the selected model: one future step, inferred independently per dataset when omitted. A datetime index with a calendar frequency – stored in
index.freq, inferable withpd.infer_freq(business days, month starts, weeks, quarters, hours, tz-aware days across DST), or aPeriodIndex’s periods – steps on that calendar, so it is regular: fitted on its own rows and forecast onto the next business days / month starts / periods. Weekday-only sessions that skip a few weekdays (exchange holidays) step in business days. Any other index steps by the median positive gap. Pass e.g. ‘1h’ for datetime/duration indexes, a calendar frequency such as ‘B’ or ‘MS’ for datetime indexes, or 0.5 for numerical indexes. Timed observations are sorted before fitting. GaussianProcess uses the actual times; Kalman, ARIMA, AutoRegressor, Laplace and Chronos linearly interpolate irregular observations onto a regular grid ending at the latest observation (with a warning). No training values are extrapolated or missing values imputed. Fitted-model reuse keeps the training interval when the new index is of the same kind (a model fit on an array and reused on dated rows, or the reverse, steps in the new data’s own units). Period indexes are fitted on their start timestamps and forecast as periods of the same frequency; duplicate numeric row IDs remain positional. See the API guide’s observation-times section for the full policy.- return_modelbool
If True, also return the fitted (or reused) Forecaster instance, so it can be passed back as model= on future calls with new data (default: False). On hierarchical input this returns PARALLEL SEQUENCES –
([f0, f1, ...], [m0, m1, ...]), mirroring the flat(forecast, model)shape – rather than a list of pairs. With a COLLECTION of models it returns({name: forecast}, {name: model}); it is not supported withholdout=.- holdoutint, float, True, or None
BACKTEST instead of forecasting (1.1). Fit each model on the HEAD of the data, forecast the held-out TAIL, and return a scores frame comparing every model against the rows that actually happened. An int holds out that many rows; a float in (0, 1) holds out that FRACTION of them (rounded, at least 1);
Trueholds out exactly t rows. The head must keep at least 2 rows.Pass a name, class, or unfitted instance. Each dataset fits an independent copy; the caller’s instance is unchanged. Already fitted instances are refused because they may have seen the held-out rows.
t is not consulted for an int/float holdout. The number of held-out observations is reported in the frame’s
horizoncolumn. (Useholdout=Trueto say “hold out t rows”.)Timed rows are sorted before splitting. Models and their step sizes are fitted on TRAINING rows only. GaussianProcess evaluates the actual held-out times; regular-grid models forecast a covering grid and linearly interpolate predictions to those times (with a warning when interpolation is needed). Before the first full forecast step, the last observed training value anchors interpolation. Missing endpoints remain missing; no held-out values enter the model or the interpolation. Returned predictions carry the held-out index. Arrays/categorical labels/repeated numeric IDs use row positions.
Not available on HIERARCHICAL input (which group is scored would have to become a fourth axis of the frame); slice the groups and backtest them one at a time.
- metricsstr or sequence of str
Which metrics to score, from
'mae','rmse','mape'(default: all three, in that order). Column labels are the upper-cased names. MAPE is a PERCENTAGE and is nan-safe on zeros: entries whose actual value is exactly 0 are dropped from its average (all-zero truth gives NaN) rather than turning the column intoinf. The FIRST metric is the RANKING metric behindattrs['best'].- per_columnbool
False (default) averages each metric over the columns (and, for a list of datasets, over the datasets), giving ONE row per model. True returns the LONG form instead: one row per model x (dataset x) column, indexed by a MultiIndex –
.reset_index()for a fully tidy frame. The verdict inattrsis computed from the averaged form either way.- return_forecastsbool
With
holdout=, also return the forecasts that were scored:(scores, {name: forecast, 'naive': baseline, 'truth': held_out})(default: False). For a LIST of datasets each value is a list of frames, one per dataset, in input order.- **kwargs
Passed through to the forecaster’s constructor when model resolves to a name, class, or dict spec (merged into a dict spec’s own
kwargs, with these outer values winning). When model is already a constructed instance they cannot be applied, and a warning is raised. Unknown parameter names raise TypeError (typos used to be swallowed silently for some models).
- Returns:
- forecasts
The forecasts (and the fitted Forecaster if
return_model=True). Lists in, lists out: a single input dataset returns a single forecast DataFrame. A hierarchical DataFrame (see data) returns a LIST of forecasts, one per group in input order – or, withreturn_model=True, the parallel([f0, f1, ...], [m0, m1, ...])pair described there.A COLLECTION of models (see model) returns a
{name: forecast}dict whose values are exactly what a single-model call would have returned (a DataFrame, or a list of them for list/hierarchical input).With
holdout=, a scores DataFrame instead (see Notes) – or(scores, forecasts)withreturn_forecasts=True.
Notes
Backtesting (
holdout=). The returned frame has one ROW per model, in the order the models were given, plus an always-present'naive'row: the last-value-carried-forward baseline (each column’s last OBSERVED training value, repeated over the horizon), which is the textbook random-walk benchmark for a timeseries. Its COLUMNS are the requested metrics (MAE,RMSE,MAPE),n(how many predicted/actual pairs were scored),unscored(held-out values the model failed to produce – returned as NaN – which are counted, and warned about, rather than silently dropped, since a model scored on fewer entries is not comparable to one scored on all of them) andhorizon(the number of held-out rows). Multi-column data is scored per column and averaged;per_column=Truekeeps the per-column rows.HOW TO READ IT.
scores.attrscarries the verdict:attrs['best'](the row with the lowest value of the ranking metric – the FIRST entry of metrics – among the real models, EXCLUDING the baseline, so what it names can always be handed back to predict),attrs['best_score'],attrs['baseline']('naive'),attrs['baseline_score'], andattrs['beats_baseline']– True only when the best model’s score is strictly BELOW the baseline’s. A model that does not beat the naive baseline has not earned its complexity, whatever its absolute error looks like. TIES on the ranking metric go to the model listed FIRST (the comparison is stable, so re-running with the same specs gives the same verdict); models whose ranking metric is NaN (nothing scoreable) are never chosen as best.ONLY COMPLETE MODELS ARE RANKED. A model with
unscored > 0(summed over every dataset and column) was scored on fewer held-out values than the others, so it keeps its descriptive row but can never beattrs['best']; it is named inattrs['incomplete'](a list, empty when every row is complete) and a warning says so. If NO model is complete (or none scored at all),attrs['best']is None,attrs['best_score']is NaN andattrs['beats_baseline']is None – there is no verdict, which is not the same as “did not beat the baseline”.attrs['beats_baseline']is likewise None if the naive baseline is itself incomplete (a column with no observed training value gives it nothing to carry forward; it is then listed inattrs['incomplete']too). Testis True/is Nonerather than truthiness when the distinction matters.Forecast and held-out COLUMNS are paired by label: a custom forecaster that returns the training columns in another order is reordered, and one that returns different column labels raises a ValueError.
The verdict lives in
attrsrather than in abestcolumn on purpose: it is one fact about the whole comparison, and a column would repeat it on every row, force a non-numeric column into an otherwise all-numeric frame (breakingscores.mean(),.plot.bar()and the describe-style bar chart), and become meaningless on a per-column slice. Note that pandas does not propagateattrsthrough every operation – read the verdict from the frame predict returned, not from a slice of it.Forecasts are not scale-invariant, so normalize heterogeneous features first. These are fitted statistical models, not scale-free transforms: their priors, initial covariances and convergence criteria are expressed in the units you supply, so multiplying an input column by a constant does not simply multiply its forecast by the same constant. Measured on a 60x2 seasonal series, scaling the input by 100 and dividing the one-step forecast change back by 100 moves it by 41% on one column for
Kalmanand 32% forARIMA– and raisingn_iterfrom 1 to 100 does not close the gap, because pykalman’s EM starts from identity covariances and settles on a different optimum. Columns measured in wildly different units (millimeters beside percentages, say) will therefore not be weighted the way you expect. Passnormalize=upstream, or hypertools.normalize the data, when the features are not already comparable.Examples
>>> import numpy as np >>> import hypertools as hyp >>> x = np.cumsum(np.random.default_rng(0).standard_normal((40, 3)), ... axis=0) >>> forecast = hyp.predict(x, model='Kalman', t=5) >>> forecast.shape (5, 3)
One forecast per group of a column hierarchy (the innermost level is the feature axis, so every group keeps all 3 measures):
>>> import pandas as pd >>> columns = pd.MultiIndex.from_tuples( ... [(sector, measure) for sector in ('Tech', 'Energy') ... for measure in ('open', 'close', 'volume')], ... names=['Sector', 'Measure']) >>> df = pd.DataFrame(np.cumsum( ... np.random.default_rng(0).standard_normal((40, 6)), axis=0), ... columns=columns) >>> [f.shape for f in hyp.predict(df, model='Kalman', t=5)] [(5, 3), (5, 3)]
Several models at once – one forecast per model, keyed by name:
>>> forecasts = hyp.predict(x, model=['Kalman', 'AutoRegressor'], t=5) >>> {name: f.shape for name, f in forecasts.items()} {'Kalman': (5, 3), 'AutoRegressor': (5, 3)}
Backtest them against the last 5 rows, naive baseline included:
>>> scores = hyp.predict(x, model=['Kalman', 'AutoRegressor'], holdout=5) >>> list(scores.index) ['Kalman', 'AutoRegressor', 'naive'] >>> list(scores.columns) ['MAE', 'RMSE', 'MAPE', 'n', 'unscored', 'horizon'] >>> scores.attrs['best'] in ('Kalman', 'AutoRegressor') True >>> isinstance(scores.attrs['beats_baseline'], bool) True