Skip to content

FoundationModel

skforecast.foundation._foundation_model.FoundationModel

FoundationModel(model_id, **kwargs)

Scikit-learn compatible interface for foundation time-series models.

Currently supports Amazon Chronos-2, Google TimesFM 2.5, Salesforce Moirai-2 and TabICLv2. For full skforecast ecosystem integration (backtesting, model selection, etc.) use ForecasterFoundation instead.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID. The adapter is resolved automatically from the model_id prefix. Available model IDs:

Amazon Chronos-2 (supports exog):

  • 'amazon/chronos-2'
  • 'autogluon/chronos-2-small'
  • 'autogluon/chronos-2-synth'

Google TimesFM 2.5 (does not support exog):

  • 'google/timesfm-2.5-200m-pytorch'

Salesforce Moirai-2 (does not support exog):

  • 'Salesforce/moirai-2.0-R-small'

TabICLv2 (supports exog):

  • 'soda-inria/tabicl'
required
**kwargs Any

Additional keyword arguments forwarded to the underlying adapter. Valid keys depend on the adapter selected by model_id. See the corresponding adapter class (ChronosAdapter, TimesFMAdapter, MoiraiAdapter, TabICLAdapter) for the full parameter list, or refer to the model documentation linked in the References section below.

{}

Attributes:

Name Type Description
adapter object

The underlying adapter instance, instantiated automatically based on the model_id prefix. The concrete type depends on the model — e.g. ChronosAdapter for autogluon/chronos-* models.

model_id str

HuggingFace model ID. Mirrors adapter.model_id.

context_ dict[str, pandas Series]

Per-series dict of pandas Series containing the last context_length observations from the training data, stored during fit. Mirrors adapter.context_.

context_exog_ dict

Per-series dict of pandas DataFrame containing the last context_length exog variables from the training data, stored during fit. None if the adapter does not support exogenous variables or no exog was provided. Mirrors adapter.context_exog_.

context_length int

Maximum number of historical observations used as context. Mirrors adapter.context_length.

allow_exog bool

Whether the underlying adapter supports exogenous variables.

index_type_ type

Type of index of the input used in training.

index_freq_ pandas DateOffset, int

Frequency of the index of the input used in training. A pandas DateOffset for DatetimeIndex or an int step for RangeIndex.

context_range_ dict[str, pandas Index]

First and last values of the index of the data used during training for each series.

series_names_in_ list

Names of the series (levels) provided by the user during training.

is_multiple_series_ bool

Whether the model was fitted with multiple series.

exog_in_ bool

If the model has been trained using exogenous variable/s.

exog_names_in_ list

Names of the exogenous variables used during training. None if no exog was provided.

exog_names_in_per_series_ dict

Names of the exogenous variables used during training for each series. None if no exog was provided.

exog_type_in_ type

Type of exogenous variable/s used in training. None if no exog was provided.

creation_date str

Date of creation.

is_fitted bool

Tag to identify if the model has been fitted (trained).

fit_date str

Date of last fit.

skforecast_version str

Version of skforecast library used to create the model.

python_version str

Version of python used to create the model.

Notes

Each adapter imports its own backend library lazily (i.e. inside the method that first needs it) rather than at module level. This means that only the library required by the adapter you actually use needs to be installed, other foundation-model backends remain optional.

References

.. [1] Amazon Chronos - GitHub repository. https://github.com/amazon-science/chronos-forecasting

.. [2] Amazon Chronos - HuggingFace collection. https://huggingface.co/collections/amazon/chronos-models-65f1791d630a8d57cb718444

.. [3] Google TimesFM - GitHub repository. https://github.com/google-research/timesfm

.. [4] Google TimesFM - HuggingFace collection. https://huggingface.co/collections/google/timesfm-release-66e4be5fdb56e960c1e482a6

.. [5] Salesforce Moirai (uni2ts) - GitHub repository. https://github.com/SalesforceAIResearch/uni2ts

.. [6] Salesforce Moirai-R - HuggingFace collection. https://huggingface.co/collections/Salesforce/moirai-r-models-65c8d3a94c51428c300e0742

.. [7] TabICL - GitHub repository. https://github.com/soda-inria/tabicl

.. [8] TabICL - Documentation. https://tabicl.readthedocs.io/en/latest/

Methods:

Name Description
fit

Fit the model by storing the training series and optional exog.

predict

Predict n steps ahead.

get_params

Get parameters for this estimator (sklearn-compatible).

set_params

Set parameters for this estimator (sklearn-compatible).

Source code in skforecast/foundation/_foundation_model.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def __init__(
    self,
    model_id: str,
    **kwargs: Any,
) -> None:

    adapter_cls                    = _resolve_adapter(model_id)
    self.adapter                   = adapter_cls(model_id=model_id, **kwargs)
    self.index_type_               = None
    self.index_freq_               = None
    self.context_range_            = None
    self.series_names_in_          = None
    self.is_multiple_series_       = False
    self.exog_in_                  = False
    self.exog_names_in_            = None
    self.exog_names_in_per_series_ = None
    self.exog_type_in_             = None
    self.creation_date             = pd.Timestamp.today().strftime('%Y-%m-%d %H:%M:%S')
    self.fit_date                  = None
    self.skforecast_version        = __version__
    self.python_version            = sys.version.split(" ")[0]

Attributes

adapter instance-attribute

adapter = adapter_cls(model_id=model_id, **kwargs)

index_type_ instance-attribute

index_type_ = None

index_freq_ instance-attribute

index_freq_ = None

context_range_ instance-attribute

context_range_ = None

series_names_in_ instance-attribute

series_names_in_ = None

is_multiple_series_ instance-attribute

is_multiple_series_ = False

exog_in_ instance-attribute

exog_in_ = False

exog_names_in_ instance-attribute

exog_names_in_ = None

exog_names_in_per_series_ instance-attribute

exog_names_in_per_series_ = None

exog_type_in_ instance-attribute

exog_type_in_ = None

creation_date instance-attribute

creation_date = strftime('%Y-%m-%d %H:%M:%S')

fit_date instance-attribute

fit_date = None

skforecast_version instance-attribute

skforecast_version = __version__

python_version instance-attribute

python_version = split(' ')[0]

model_id property

model_id

HuggingFace model ID.

Returns:

Name Type Description
model_id str

HuggingFace model ID. Mirrors adapter.model_id.

context_ property

context_

Context stored during fit, used as default context for predict if no override is provided.

Returns:

Name Type Description
context_ dict[str, Series]

Per-series dict of pandas Series containing the last context_length observations from the training data, stored during fit. Mirrors adapter.context_.

context_exog_ property

context_exog_

Context stored during fit, used as default context for predict if no override is provided.

Returns:

Name Type Description
context_exog_ (dict[str, DataFrame], None)

Per-series dict of pandas DataFrame containing the last context_length exog variables from the training data, stored during fit. None if the adapter does not support exogenous variables or no exog was provided. Mirrors adapter.context_exog_.

context_length property

context_length

Maximum number of historical observations used as context.

Returns:

Name Type Description
context_length int

Maximum context length. Mirrors adapter.context_length.

allow_exog property

allow_exog

Whether the underlying adapter supports exogenous variables.

Returns:

Name Type Description
allow_exog bool

True if the adapter accepts and uses exog; False if it ignores covariates (e.g. TimesFM 2.5, Moirai-2).

is_fitted property

is_fitted

Whether the model has been fitted.

Returns:

Name Type Description
is_fitted bool

True after fit has been called at least once, False otherwise.

Functions

_repr_html_

_repr_html_()

HTML representation of the object. The "General Information" section is expanded by default.

Source code in skforecast/foundation/_foundation_model.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
def _repr_html_(self) -> str:
    """
    HTML representation of the object.
    The "General Information" section is expanded by default.
    """

    style, unique_id = get_style_repr_html(self.is_fitted)

    params_html = "".join(
        f"<li><strong>{html.escape(str(k))}:</strong> {html.escape(str(v))}</li>"
        for k, v in self.adapter.get_params().items()
        if k != "model_id"
    )

    content = f"""
    <div class="container-{unique_id}">
        <p style="font-size: 1.5em; font-weight: bold; margin-block-start: 0.83em; margin-block-end: 0.83em;">{type(self).__name__}</p>
        <details open>
            <summary>General Information</summary>
            <ul>
                <li><strong>Model ID:</strong> {self.model_id}</li>
                <li><strong>Context length:</strong> {self.context_length}</li>
                <li><strong>Creation date:</strong> {self.creation_date}</li>
                <li><strong>Last fit date:</strong> {self.fit_date}</li>
                <li><strong>Skforecast version:</strong> {self.skforecast_version}</li>
                <li><strong>Python version:</strong> {self.python_version}</li>
            </ul>
        </details>
        <details>
            <summary>Model Parameters</summary>
            <ul>
                {params_html}
            </ul>
        </details>
        <p>
            <a href="https://skforecast.org/{__version__}/api/foundationmodel.html">&#128214; <strong>API Reference</strong></a>
            &nbsp;&nbsp;
            <a href="https://skforecast.org/{__version__}/user_guides/foundation-forecasting-models.html">&#128221; <strong>User Guide</strong></a>
        </p>
    </div>
    """

    return style + content

_check_preprocess_context

_check_preprocess_context(series, exog=None)

Normalize and validate context input to a per-series dict.

Parameters:

Name Type Description Default
series pandas Series, pandas DataFrame, dict

Time series to normalize and validate.

  • If pandas Series: single-series mode.
  • If wide pandas DataFrame or dict[str, pandas Series]: multi-series mode.
required
exog pandas Series, pandas DataFrame, dict

Exogenous variables aligned to series.

  • If pandas Series or pandas DataFrame: broadcast to all series.
  • If dict: per-series exogenous variables.
None

Returns:

Name Type Description
context dict

Per-series dict of pandas Series, trimmed to the last context_length observations.

series_indexes dict

Index of each series before trimming.

series_names_in_ list

Names of the series.

context_exog dict or None

Per-series dict of exogenous DataFrames trimmed to the last context_length observations. None if exog is None.

exog_names_in_ list or None

Names of the exogenous variables. None if exog is None.

Source code in skforecast/foundation/_foundation_model.py
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
def _check_preprocess_context(
    self,
    series: pd.Series | pd.DataFrame | dict[str, pd.Series],
    exog: (
        pd.Series
        | pd.DataFrame
        | dict[str, pd.DataFrame | pd.Series | None]
        | None
    ) = None,
) -> tuple[dict[str, pd.Series], dict[str, pd.Index], list[str], dict[str, pd.DataFrame | None] | None, list[str] | None]:
    """
    Normalize and validate context input to a per-series dict.

    Parameters
    ----------
    series : pandas Series, pandas DataFrame, dict
        Time series to normalize and validate.

        - If `pandas Series`: single-series mode.
        - If wide `pandas DataFrame` or `dict[str, pandas Series]`:
        multi-series mode.
    exog : pandas Series, pandas DataFrame, dict, default None
        Exogenous variables aligned to `series`.

        - If `pandas Series` or `pandas DataFrame`: broadcast to all
        series.
        - If `dict`: per-series exogenous variables.

    Returns
    -------
    context : dict
        Per-series dict of pandas Series, trimmed to the last
        `context_length` observations.
    series_indexes : dict
        Index of each series before trimming.
    series_names_in_ : list
        Names of the series.
    context_exog : dict or None
        Per-series dict of exogenous DataFrames trimmed to the last
        `context_length` observations. `None` if `exog` is `None`.
    exog_names_in_ : list or None
        Names of the exogenous variables. `None` if `exog` is `None`.

    """

    series_dict, series_indexes = check_preprocess_series_foundation(series)
    series_names_in_ = list(series_dict.keys())

    if exog is not None:
        exog_dict, exog_names_in_ = check_preprocess_exog_multiseries(
            series_names_in_  = series_names_in_,
            series_index_type = type(series_indexes[series_names_in_[0]]),
            exog              = exog,
            exog_dict         = {name: None for name in series_names_in_},
        )

        # NOTE: As no trim is applied to the series, it is only needed to 
        # align exog.
        series_dict, exog_dict = align_series_and_exog_multiseries(
                                     series_dict      = series_dict,
                                     exog_dict        = exog_dict,
                                     trim_series_nan  = False,
                                 )

    context = {
        name: s.iloc[-self.context_length :]
        for name, s in series_dict.items()
    }
    if exog is not None:
        context_exog = {
            name: (
                e.iloc[-self.context_length :]
                if e is not None
                else None
            )
            for name, e in exog_dict.items()
        }
    else:
        context_exog = None
        exog_names_in_ = None

    return context, series_indexes, series_names_in_, context_exog, exog_names_in_

fit

fit(series, exog=None)

Fit the model by storing the training series and optional exog.

Parameters:

Name Type Description Default
series pandas Series, pandas DataFrame, dict

Training time series.

  • If pandas Series: single-series mode.
  • If wide pandas DataFrame (each column = one series): multi-series mode.
  • If dict[str, pandas Series]: multi-series mode; keys are series names.
required
exog pandas Series, pandas DataFrame, dict

Historical exogenous variables aligned to series.

  • If pandas Series or pandas DataFrame: broadcast to all series.
  • If dict: per-series exogenous variables.
None

Returns:

Name Type Description
self FoundationModel
Source code in skforecast/foundation/_foundation_model.py
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
def fit(
    self,
    series: pd.Series | pd.DataFrame | dict[str, pd.Series],
    exog: (
        pd.Series
        | pd.DataFrame
        | dict[str, pd.DataFrame | pd.Series | None]
        | None
    ) = None,
) -> FoundationModel:
    """
    Fit the model by storing the training series and optional exog.

    Parameters
    ----------
    series : pandas Series, pandas DataFrame, dict
        Training time series.

        - If `pandas Series`: single-series mode.
        - If wide `pandas DataFrame` (each column = one series):
        multi-series mode.
        - If `dict[str, pandas Series]`: multi-series mode; keys are
        series names.
    exog : pandas Series, pandas DataFrame, dict, default None
        Historical exogenous variables aligned to `series`.

        - If `pandas Series` or `pandas DataFrame`: broadcast to all
        series.
        - If `dict`: per-series exogenous variables.

    Returns
    -------
    self : FoundationModel

    """

    self.index_type_                = None
    self.index_freq_                = None
    self.context_range_             = None
    self.series_names_in_           = None
    self.is_multiple_series_        = False
    self.exog_in_                   = False
    self.exog_names_in_             = None
    self.exog_names_in_per_series_  = None
    self.exog_type_in_              = None
    self.fit_date                   = None

    context, series_indexes, series_names_in_, context_exog, exog_names_in_ = (
        self._check_preprocess_context(
            series = series,
            exog   = exog,
        )
    )

    self.adapter.fit(
        context      = context,
        context_exog = context_exog,
    )

    self.series_names_in_    = series_names_in_
    self.is_multiple_series_ = len(series_names_in_) > 1

    if context_exog is not None and len(exog_names_in_) > 0:
        self.exog_in_ = True
        self.exog_names_in_ = exog_names_in_
        self.exog_names_in_per_series_ = {
            k: list(v.columns) if v is not None else None
            for k, v in context_exog.items()
        }
        self.exog_type_in_ = type(exog)

    self.fit_date = pd.Timestamp.today().strftime('%Y-%m-%d %H:%M:%S')
    self.context_range_ = {k: v[[0, -1]] for k, v in series_indexes.items()}
    self.index_type_ = type(series_indexes[series_names_in_[0]])
    if isinstance(series_indexes[series_names_in_[0]], pd.DatetimeIndex):
        self.index_freq_ = series_indexes[series_names_in_[0]].freq
    else:
        self.index_freq_ = series_indexes[series_names_in_[0]].step

    return self

_exog_to_dict staticmethod

_exog_to_dict(exog, series_names_in)

Normalize any supported exog format into a per-series dict.

Parameters:

Name Type Description Default
exog pandas Series, pandas DataFrame, dict

Future exogenous variables in any supported format.

  • If pandas Series (flat index): broadcast to all series.
  • If pandas Series (MultiIndex): converted to dict, then keyed per series.
  • If pandas DataFrame (flat index): broadcast to all series.
  • If pandas DataFrame (MultiIndex / long-format): converted to dict per series ID.
  • If dict: used directly, missing series keys filled as None.
required
series_names_in list[str]

Series names that define the output dict keys.

required

Returns:

Name Type Description
exog_dict dict

Per-series dict with exactly the keys in series_names_in.

Source code in skforecast/foundation/_foundation_model.py
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
@staticmethod
def _exog_to_dict(
    exog: pd.Series | pd.DataFrame | dict[str, pd.DataFrame | pd.Series | None],
    series_names_in: list[str],
) -> dict[str, pd.DataFrame | pd.Series | None]:
    """
    Normalize any supported exog format into a per-series dict.

    Parameters
    ----------
    exog : pandas Series, pandas DataFrame, dict
        Future exogenous variables in any supported format.

        - If `pandas Series` (flat index): broadcast to all series.
        - If `pandas Series` (MultiIndex): converted to dict, then
          keyed per series.
        - If `pandas DataFrame` (flat index): broadcast to all series.
        - If `pandas DataFrame` (MultiIndex / long-format): converted
          to dict per series ID.
        - If `dict`: used directly, missing series keys filled as
          `None`.
    series_names_in : list[str]
        Series names that define the output dict keys.

    Returns
    -------
    exog_dict : dict
        Per-series dict with exactly the keys in `series_names_in`.

    """

    if isinstance(exog, dict):
        return {name: exog.get(name, None) for name in series_names_in}

    if isinstance(exog, pd.Series):
        if isinstance(exog.index, pd.MultiIndex):
            exog = exog.to_frame()
        else:
            return {name: exog for name in series_names_in}

    # At this point exog is always a DataFrame (original or coerced)
    if isinstance(exog.index, pd.MultiIndex):
        if not isinstance(exog.index.levels[1], pd.DatetimeIndex):
            raise TypeError(
                "The second level of the MultiIndex in `exog` must be a "
                "pandas DatetimeIndex. "
                f"Found {type(exog.index.levels[1])}."
            )
        per_series = {
            sid: group.droplevel(0)
            for sid, group in exog.groupby(level=0, sort=False)
        }
        warnings.warn(
            "Passing a long-format DataFrame as `exog` requires "
            "additional internal transformations, which can increase "
            "computational time. It is recommended to use a dictionary "
            "of pandas Series or DataFrames instead.",
            InputTypeWarning,
            stacklevel=5,
        )
        return {name: per_series.get(name, None) for name in series_names_in}

    return {name: exog for name in series_names_in}

_prepare_future_exog

_prepare_future_exog(steps, context, exog, series_names_in)

Normalize, broadcast, and align future exogenous variables to the forecast horizon in a single pass.

Performs the full pipeline for future exog:

  1. Type coercion: long-format MultiIndex Series/DataFrame is converted to a dict keyed by series ID.
  2. Broadcast / dict normalisation: flat Series or DataFrame is broadcast to every series; a dict is filled with None for missing keys; None input produces an all-None dict.
  3. Temporal alignment: each per-series exog is aligned to the forecast horizon using the resolved context. For DatetimeIndex data, exog is reindexed to the exact expected range (NaN-filling gaps). For other index types a length check and optional RangeIndex start verification are applied.

This function is self-contained — it does not depend on any metadata stored at fit time. Alignment is driven entirely by the context that will be used for prediction.

Parameters:

Name Type Description Default
steps int

Number of steps ahead to forecast.

required
context dict[str, pandas Series]

Per-series resolved context. Each value is a pandas Series whose index provides the reference end-point and frequency for alignment.

required
exog pandas Series, pandas DataFrame, dict

Future exogenous variables in any supported format.

  • If None: returns {name: None ...} for every series.
  • If pandas Series (flat index): broadcast to all series.
  • If pandas Series (MultiIndex): converted to dict, then keyed per series.
  • If pandas DataFrame (flat index): broadcast to all series.
  • If pandas DataFrame (MultiIndex / long-format): converted to dict per series ID.
  • If dict: used directly, missing series keys filled as None.
None
series_names_in list[str]

Series names that define the output dict keys.

required

Returns:

Name Type Description
exog_aligned dict

Per-series dict with exactly the keys in series_names_in. Each non-None value is a pandas DataFrame with exactly steps rows aligned to the forecast horizon. Series inputs are coerced to single-column DataFrames.

Raises:

Type Description
TypeError

If exog is a long-format DataFrame whose second MultiIndex level is not a DatetimeIndex, or if exog is an unsupported type.

ValueError

If a non-DatetimeIndex exog has fewer than steps rows, or if a RangeIndex exog does not start at the expected position.

Source code in skforecast/foundation/_foundation_model.py
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
def _prepare_future_exog(
    self,
    steps: int,
    context: dict[str, pd.Series],
    exog: (
        pd.Series
        | pd.DataFrame
        | dict[str, pd.DataFrame | pd.Series | None]
        | None
    ),
    series_names_in: list[str],
) -> dict[str, pd.DataFrame | None]:
    """
    Normalize, broadcast, and align future exogenous variables to the
    forecast horizon in a single pass.

    Performs the full pipeline for future exog:

    1. **Type coercion**: long-format MultiIndex Series/DataFrame is
    converted to a dict keyed by series ID.
    2. **Broadcast / dict normalisation**: flat Series or DataFrame is
    broadcast to every series; a dict is filled with `None` for
    missing keys; `None` input produces an all-None dict.
    3. **Temporal alignment**: each per-series exog is aligned to the
    forecast horizon using the resolved context. For `DatetimeIndex`
    data, exog is reindexed to the exact expected range (NaN-filling
    gaps). For other index types a length check and optional
    `RangeIndex` start verification are applied.

    This function is self-contained — it does not depend on any
    metadata stored at `fit` time. Alignment is driven entirely by the
    context that will be used for prediction.

    Parameters
    ----------
    steps : int
        Number of steps ahead to forecast.
    context : dict[str, pandas Series]
        Per-series resolved context. Each value is a pandas Series whose
        index provides the reference end-point and frequency for
        alignment.
    exog : pandas Series, pandas DataFrame, dict, default None
        Future exogenous variables in any supported format.

        - If `None`: returns `{name: None ...}` for every series.
        - If `pandas Series` (flat index): broadcast to all series.
        - If `pandas Series` (MultiIndex): converted to dict, then
        keyed per series.
        - If `pandas DataFrame` (flat index): broadcast to all series.
        - If `pandas DataFrame` (MultiIndex / long-format): converted
        to dict per series ID.
        - If `dict`: used directly, missing series keys filled as
        `None`.
    series_names_in : list[str]
        Series names that define the output dict keys.

    Returns
    -------
    exog_aligned : dict
        Per-series dict with exactly the keys in `series_names_in`. Each
        non-None value is a pandas DataFrame with exactly `steps` rows
        aligned to the forecast horizon. Series inputs are coerced to
        single-column DataFrames.

    Raises
    ------
    TypeError
        If `exog` is a long-format DataFrame whose second MultiIndex
        level is not a `DatetimeIndex`, or if `exog` is an unsupported
        type.
    ValueError
        If a non-DatetimeIndex exog has fewer than `steps` rows, or if
        a `RangeIndex` exog does not start at the expected position.

    """

    # Early return: no exog provided
    if exog is None:
        return {name: None for name in series_names_in}

    # Type guard
    if not isinstance(exog, (pd.Series, pd.DataFrame, dict)):
        raise TypeError(
            f"`exog` must be a pandas Series, DataFrame, dict, or None. "
            f"Got {type(exog)}."
        )

    # Normalize any input format (Series, DataFrame, dict) into a
    # per-series dict keyed by series name.
    exog_dict = self._exog_to_dict(exog, series_names_in)

    # Determine index type and freq once from the first context series.
    # All series share the same type and freq, and are non-empty with a
    # valid freq/step (guaranteed by check_preprocess_series upstream).
    first_ctx = next(iter(context.values()))
    is_datetime_ctx = isinstance(first_ctx.index, pd.DatetimeIndex)
    freq = first_ctx.index.freq if is_datetime_ctx else first_ctx.index.step

    # Align each series' exog to its forecast horizon
    exog_aligned = {}
    nan_filled_series = []
    for name in series_names_in:
        e = exog_dict.get(name)
        if e is None:
            exog_aligned[name] = None
            continue

        if isinstance(e, pd.Series):
            e = e.to_frame()

        ctx = context[name]
        ref_end = ctx.index[-1]
        label = f"`exog` for series '{name}'"

        # DatetimeIndex: reindex to the exact expected date range,
        # filling gaps with NaN.
        if is_datetime_ctx and isinstance(e.index, pd.DatetimeIndex):
            expected_idx = pd.date_range(
                start=ref_end + freq, periods=steps, freq=freq
            )
            e_aligned = e.reindex(expected_idx)
            if e_aligned.isnull().any(axis=None):
                nan_filled_series.append(name)
            exog_aligned[name] = e_aligned
        else:
            # RangeIndex / other: length check + optional start validation,
            # then truncate to the forecast horizon.
            if len(e) < steps:
                raise ValueError(
                    f"{label} must have at least {steps} values. "
                    f"Got {len(e)}."
                )
            if isinstance(e.index, pd.RangeIndex):
                expected_start = ref_end + freq
                if e.index[0] != expected_start:
                    raise ValueError(
                        f"To make predictions {label} must start one step "
                        f"ahead of `context`.\n"
                        f"    `context` ends at: {ref_end}.\n"
                        f"    {label} starts at: {e.index[0]}.\n"
                        f"    Expected index: {expected_start}."
                    )
            exog_aligned[name] = e.iloc[:steps]

    # Batch warning for all series whose exog had missing timestamps
    if nan_filled_series:
        warnings.warn(
            f"`exog` for series {nan_filled_series} has been reindexed "
            f"to match the expected forecast horizon. Missing timestamps "
            f"were filled with NaN.",
            MissingValuesWarning,
            stacklevel=4,
        )

    return exog_aligned

predict

predict(
    steps,
    levels=None,
    context=None,
    context_exog=None,
    exog=None,
    quantiles=None,
    check_inputs=True,
)

Predict n steps ahead.

Parameters:

Name Type Description Default
steps int

Number of steps ahead to forecast.

required
levels (str, list)

Subset of series to predict. If None, all series in context are predicted.

None
context pandas Series, pandas DataFrame, dict

Override the stored context with this window.

  • If pandas Series: single-series override.
  • If wide pandas DataFrame or dict[str, pandas Series]: multi-series override.
None
context_exog pandas Series, pandas DataFrame, dict

Historical exog corresponding to context.

None
exog pandas Series, pandas DataFrame, dict

Future known exogenous variables for the forecast horizon.

  • If pandas Series or pandas DataFrame: broadcast to all series.
  • If dict: per-series exogenous variables.
None
quantiles (list, tuple)

Quantile levels to return, e.g. [0.1, 0.5, 0.9]. If None, returns a point forecast (median).

None
check_inputs bool

If True, the context and context_exog inputs are validated and normalized via _check_preprocess_context. If False, context must already be a dict[str, pandas Series] and context_exog must be a dict[str, pandas DataFrame | None] or None. This argument is created for internal use and is not recommended to be changed.

True

Returns:

Name Type Description
predictions pandas DataFrame

Value of predictions. The DataFrame includes the following columns:

  • level: Name of the series.
  • pred: Predicted values (point forecast, median).

If quantiles is not None, the pred column is replaced by one column per quantile level (e.g., q_0.1, q_0.5, q_0.9).

Notes

Foundation models are pre-trained and do not learn from the data passed to fit. The fit method only stores context (the last context_length observations) and metadata. This leads to four distinct behaviors depending on the combination of is_fitted and context:

  • Not fitted, context=None: raises ValueError. There is no context available for prediction.
  • Fitted, context=None: uses the context and context_exog_ stored during fit. If the user supplies context_exog, it is ignored with a warning.
  • Not fitted, context provided (zero-shot mode): The model uses context and context_exog (if provided) as context for prediction.
  • Fitted, context provided: Stored context is ignored, the provided context and context_exog (if provided) are used for prediction.
Source code in skforecast/foundation/_foundation_model.py
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
def predict(
    self,
    steps: int,
    levels: str | list[str] | None = None,
    context: pd.Series | pd.DataFrame | dict[str, pd.Series] | None = None,
    context_exog: (
        pd.Series
        | pd.DataFrame
        | dict[str, pd.DataFrame | pd.Series | None]
        | None
    ) = None,
    exog: (
        pd.Series
        | pd.DataFrame
        | dict[str, pd.DataFrame | pd.Series | None]
        | None
    ) = None,
    quantiles: list[float] | tuple[float] | None = None,
    check_inputs: bool = True,
) -> pd.DataFrame:
    """
    Predict n steps ahead.

    Parameters
    ----------
    steps : int
        Number of steps ahead to forecast.
    levels : str, list, default None
        Subset of series to predict. If `None`, all series in `context` are 
        predicted. 
    context : pandas Series, pandas DataFrame, dict, default None
        Override the stored context with this window.

        - If `pandas Series`: single-series override.
        - If wide `pandas DataFrame` or `dict[str, pandas Series]`:
        multi-series override.
    context_exog : pandas Series, pandas DataFrame, dict, default None
        Historical exog corresponding to `context`.
    exog : pandas Series, pandas DataFrame, dict, default None
        Future known exogenous variables for the forecast horizon.

        - If `pandas Series` or `pandas DataFrame`: broadcast to all
        series.
        - If `dict`: per-series exogenous variables.
    quantiles : list, tuple, default None
        Quantile levels to return, e.g. `[0.1, 0.5, 0.9]`. If `None`,
        returns a point forecast (median).
    check_inputs : bool, default True
        If `True`, the `context` and `context_exog` inputs are validated
        and normalized via `_check_preprocess_context`. If `False`,
        `context` must already be a `dict[str, pandas Series]` and
        `context_exog` must be a `dict[str, pandas DataFrame | None]`
        or `None`. This argument is created for internal use and is not
        recommended to be changed.

    Returns
    -------
    predictions : pandas DataFrame
        Value of predictions. The DataFrame includes the following columns:

        - level: Name of the series.
        - pred: Predicted values (point forecast, median).

        If `quantiles` is not `None`, the `pred` column is replaced by
        one column per quantile level (e.g., `q_0.1`, `q_0.5`, `q_0.9`).

    Notes
    -----
    Foundation models are pre-trained and do not learn from the data passed 
    to `fit`. The `fit` method only stores context (the last `context_length` 
    observations) and metadata. This leads to four distinct behaviors 
    depending on the combination of `is_fitted` and `context`:

    - **Not fitted, `context=None`**: raises `ValueError`. There is no context 
    available for prediction.
    - **Fitted, `context=None`**: uses the context and `context_exog_` stored 
    during `fit`. If the user supplies `context_exog`, it is ignored with a 
    warning.
    - **Not fitted, `context` provided (zero-shot mode)**: The model uses 
    `context` and `context_exog` (if provided) as context for prediction.
    - **Fitted, `context` provided**: Stored context is ignored, the 
    provided `context` and `context_exog` (if provided) are used for 
    prediction.

    """

    if not self.is_fitted and context is None:
        raise ValueError(
            "Call `fit` before `predict`, or pass `context`."
        )

    if not isinstance(steps, (int, np.integer)) or steps < 1:
        raise ValueError("`steps` must be a positive integer.")

    if quantiles is not None:
        if not isinstance(quantiles, (list, tuple)):
            raise TypeError(
                "`quantiles` must be a `list` or `tuple`. For example, quantiles "
                "0.1, 0.5, and 0.9 should be as `quantiles = [0.1, 0.5, 0.9]`."
            )
        for q in quantiles:
            if not 0.0 <= q <= 1.0:
                raise ValueError(
                    f"All quantiles must be between 0 and 1. Got {q}."
                )

    # Context (past data)
    if context is None:
        if context_exog is not None:
            warnings.warn(
                "`context_exog` is ignored when `context` is not provided. "
                "The stored `context_exog_` from `fit` is used instead.",
                IgnoredArgumentWarning,
                stacklevel=3,
            )
        context = self.adapter.context_
        series_names_in = self.series_names_in_
        context_exog = self.adapter.context_exog_
    elif check_inputs:
        context, _, series_names_in, context_exog, _ = self._check_preprocess_context(
            series = context,
            exog   = context_exog,
        )
    else:
        series_names_in = list(context.keys())

    if levels is not None:
        requested_levels = [levels] if isinstance(levels, str) else list(levels)
        unknown = [lv for lv in requested_levels if lv not in series_names_in]
        if unknown:
            raise ValueError(
                f"`levels` {unknown} not found in available series "
                f"{list(series_names_in)}."
            )
        series_names_in = requested_levels
        context = {name: context[name] for name in requested_levels}
        if context_exog is not None:
            context_exog = {
                name: context_exog.get(name) for name in requested_levels
            }

    # Future exog
    if not self.allow_exog:
        has_exog = (exog is not None) or (context_exog is not None)
        if has_exog:
            warnings.warn(
                f"{type(self.adapter).__name__} does not currently "
                "support covariates. `exog` and `context_exog` "
                "are ignored.",
                IgnoredArgumentWarning,
                stacklevel=3,
            )
            exog = None
            context_exog = None
    else:
        if check_inputs:
            exog = self._prepare_future_exog(
                       steps           = steps,
                       context         = context,
                       exog            = exog,
                       series_names_in = series_names_in,
                   )

    # Adapter returns dict[str, np.ndarray] with shape (steps, n_q)
    raw_predictions = self.adapter.predict(
                          steps        = steps,
                          context      = context,
                          context_exog = context_exog,
                          exog         = exog,
                          quantiles    = quantiles,
                      )

    # Build long-format DataFrame from raw predictions
    n_series = len(series_names_in)
    per_series_indices = [
        expand_index(context[name].index, steps=steps)
        for name in series_names_in
    ]

    if n_series == 1:
        long_index = per_series_indices[0]
    else:
        idx_arr = np.column_stack(
            [idx.to_numpy() for idx in per_series_indices]
        ).ravel()
        long_index = (
            pd.DatetimeIndex(idx_arr)
            if isinstance(per_series_indices[0], pd.DatetimeIndex)
            else pd.Index(idx_arr)
        )
    level_col = np.tile(series_names_in, steps)

    col_names = ["pred"] if quantiles is None else [f"q_{q}" for q in quantiles]
    n_cols = len(col_names)
    # Pre-allocate (steps, n_series, n_cols), fill per series, then reshape
    # to step-major (steps*n_series, n_cols) — one allocation instead of one
    # per quantile, and the ravel order matches level_col / long_index.
    pred_matrix = np.empty((steps, n_series, n_cols), dtype=np.float64)
    for i, name in enumerate(series_names_in):
        pred_matrix[:, i, :] = raw_predictions[name]
    pred_matrix = pred_matrix.reshape(steps * n_series, n_cols)
    predictions: dict[str, np.ndarray] = {"level": level_col}
    for j, col in enumerate(col_names):
        predictions[col] = pred_matrix[:, j]

    predictions = pd.DataFrame(predictions, index=long_index)

    return predictions

get_params

get_params(deep=None)

Get parameters for this estimator (sklearn-compatible).

Parameters:

Name Type Description Default
deep Any

Not used, present here for API consistency by convention.

None

Returns:

Name Type Description
params dict

Parameter names mapped to their current values.

Notes

Required so that sklearn.base.clone can create an unfitted copy of this object, which is used internally by deepcopy_forecaster during backtesting. The pre-loaded pipeline is intentionally excluded so that clones are created without copying heavy model weights; the pipeline is reloaded lazily on the first predict call.

Source code in skforecast/foundation/_foundation_model.py
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
def get_params(self, deep: Any = None) -> dict:
    """
    Get parameters for this estimator (sklearn-compatible).

    Parameters
    ----------
    deep : Any, default None
        Not used, present here for API consistency by convention.

    Returns
    -------
    params : dict
        Parameter names mapped to their current values.

    Notes
    -----
    Required so that `sklearn.base.clone` can create an unfitted copy
    of this object, which is used internally by `deepcopy_forecaster`
    during backtesting. The pre-loaded pipeline is intentionally excluded
    so that clones are created without copying heavy model weights; the
    pipeline is reloaded lazily on the first `predict` call.

    """

    return self.adapter.get_params()

set_params

set_params(**params)

Set parameters for this estimator (sklearn-compatible).

After calling this method, the FoundationModel is reset to an unfitted state.

Parameters:

Name Type Description Default
**params

Estimator parameters forwarded to the underlying adapter's set_params. Use model_id to change the model ID. All other keys are adapter-specific.

{}

Returns:

Name Type Description
self FoundationModel

The same object with updated parameters.

Source code in skforecast/foundation/_foundation_model.py
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
def set_params(self, **params) -> FoundationModel:
    """
    Set parameters for this estimator (sklearn-compatible).

    After calling this method, the FoundationModel is reset to an unfitted state.

    Parameters
    ----------
    **params :
        Estimator parameters forwarded to the underlying adapter's
        `set_params`. Use `model_id` to change the model ID. All
        other keys are adapter-specific.

    Returns
    -------
    self : FoundationModel
        The same object with updated parameters.

    """

    try:
        self.adapter.set_params(**params)
    except ValueError as exc:
        raise ValueError(
            str(exc).replace(type(self.adapter).__name__, "FoundationModel")
        ) from exc

    self.index_type_               = None
    self.index_freq_               = None
    self.context_range_            = None
    self.series_names_in_          = None
    self.is_multiple_series_       = False
    self.exog_in_                  = False
    self.exog_names_in_            = None
    self.exog_names_in_per_series_ = None
    self.exog_type_in_             = None
    self.fit_date                  = None
    self.adapter.context_          = None
    self.adapter.context_exog_     = None
    self.adapter.is_fitted         = False

    return self

skforecast.foundation._adapters.ChronosAdapter

ChronosAdapter(
    model_id,
    *,
    pipeline=None,
    context_length=8192,
    predict_kwargs=None,
    device_map="auto",
    torch_dtype=None,
    cross_learning=False
)

Adapter for Amazon Chronos foundation models.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "autogluon/chronos-2-small".

required
pipeline BaseChronosPipeline

Pre-loaded pipeline instance. If None, the pipeline is loaded lazily on the first call to predict.

None
context_length int

Maximum number of historical observations to use as context. At fit time only the last context_length observations are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are used as-is. Defaults to 8192, which matches the maximum context window of Chronos. Must be a positive integer.

8192
predict_kwargs dict

Additional keyword arguments forwarded to the pipeline's predict_quantiles method.

None
device_map str

Device placement for the model. "auto" selects the best available accelerator (CUDA > MPS > CPU). Also accepts explicit values such as "cuda", "mps", or "cpu", forwarded to BaseChronosPipeline.from_pretrained.

'auto'
torch_dtype object

Torch dtype forwarded to BaseChronosPipeline.from_pretrained.

None
cross_learning bool

If True, Chronos shares information across all series in the batch when predicting in multi-series mode. Forwarded directly to predict_quantiles. Ignored in single-series mode.

False

Attributes:

Name Type Description
model_id str

HuggingFace model ID.

context_ dict

Stored training series after fitting.

context_exog_ dict

Stored historical exogenous variables after fitting.

context_length int

Maximum number of historical observations used as context.

predict_kwargs dict

Additional keyword arguments forwarded to predict_quantiles.

device_map str

Device map string for model loading.

torch_dtype object

Torch dtype for model loading.

cross_learning bool

Whether cross-series learning is enabled.

is_fitted bool

Whether the adapter has been fitted.

References

.. [1] https://github.com/amazon-science/chronos-forecasting .. [2] https://huggingface.co/amazon/chronos-2

Initialise the adapter.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "autogluon/chronos-2-small".

required
pipeline BaseChronosPipeline

Pre-loaded pipeline instance. If None, the pipeline is loaded lazily on the first call to predict.

None
context_length int

Maximum number of historical observations to retain as context. At fit time only the last context_length observations of series (and exog) are stored. At predict time, if context is longer than context_length it is trimmed to this length before inference; if it is shorter, all available observations are passed as-is and the model handles reduced context gracefully. Defaults to 8192, which matches the maximum context window of Chronos. Must be a positive integer.

8192
predict_kwargs dict

Additional keyword arguments forwarded verbatim to the pipeline's predict_quantiles method.

None
device_map str

Device placement for the model. "auto" selects the best available accelerator (CUDA > MPS > CPU). Also accepts explicit values such as "cuda", "mps", or "cpu", forwarded to BaseChronosPipeline.from_pretrained.

'auto'
torch_dtype object

Torch dtype forwarded to BaseChronosPipeline.from_pretrained (e.g. torch.bfloat16).

None
cross_learning bool

If True, Chronos shares information across all series in the batch when predicting in multi-series mode. Forwarded directly to predict_quantiles. Ignored in single-series mode.

False

Methods:

Name Description
get_params

Return the adapter's constructor parameters.

set_params

Set adapter parameters. Resets the pipeline when a device or dtype

fit

Store the training series and optional historical exogenous variables.

predict

Generate predictions using the Chronos pipeline.

Source code in skforecast/foundation/_adapters.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def __init__(
    self,
    model_id: str,
    *,
    pipeline: Any | None = None,
    context_length: int = 8192,
    predict_kwargs: dict[str, Any] | None = None,
    device_map: str = "auto",
    torch_dtype: Any | None = None,
    cross_learning: bool = False,
) -> None:
    """
    Initialise the adapter.

    Parameters
    ----------
    model_id : str
        HuggingFace model ID, e.g. "autogluon/chronos-2-small".
    pipeline : BaseChronosPipeline, default None
        Pre-loaded pipeline instance. If `None`, the pipeline is
        loaded lazily on the first call to `predict`.
    context_length : int, default 8192
        Maximum number of historical observations to retain as context.
        At `fit` time only the last `context_length` observations of
        `series` (and `exog`) are stored. At `predict` time, if
        `context` is longer than `context_length` it is trimmed to
        this length before inference; if it is shorter, all available
        observations are passed as-is and the model handles reduced
        context gracefully. Defaults to 8192, which matches the
        maximum context window of Chronos. Must be a positive
        integer.
    predict_kwargs : dict, default None
        Additional keyword arguments forwarded verbatim to the
        pipeline's `predict_quantiles` method.
    device_map : str, default 'auto'
        Device placement for the model. `"auto"` selects the best
        available accelerator (CUDA > MPS > CPU). Also accepts
        explicit values such as `"cuda"`, `"mps"`, or `"cpu"`,
        forwarded to `BaseChronosPipeline.from_pretrained`.
    torch_dtype : object, default None
        Torch dtype forwarded to `BaseChronosPipeline.from_pretrained`
        (e.g. `torch.bfloat16`).
    cross_learning : bool, default False
        If `True`, Chronos shares information across all series in
        the batch when predicting in multi-series mode. Forwarded
        directly to `predict_quantiles`. Ignored in single-series mode.

    """

    if not isinstance(context_length, int) or context_length < 1:
        raise ValueError(
            f"`context_length` must be a positive integer. Got {context_length!r}."
        )

    self.model_id       = model_id
    self._pipeline      = pipeline
    self.context_       = None
    self.context_exog_  = None
    self.context_length = context_length
    self.predict_kwargs = predict_kwargs or {}
    self.device_map     = device_map
    self.torch_dtype    = torch_dtype
    self.cross_learning = cross_learning
    self.is_fitted      = False

Attributes

allow_exog class-attribute instance-attribute

allow_exog = True

model_id instance-attribute

model_id = model_id

_pipeline instance-attribute

_pipeline = pipeline

context_ instance-attribute

context_ = None

context_exog_ instance-attribute

context_exog_ = None

context_length instance-attribute

context_length = context_length

predict_kwargs instance-attribute

predict_kwargs = predict_kwargs or {}

device_map instance-attribute

device_map = device_map

torch_dtype instance-attribute

torch_dtype = torch_dtype

cross_learning instance-attribute

cross_learning = cross_learning

is_fitted instance-attribute

is_fitted = False

Functions

get_params

get_params()

Return the adapter's constructor parameters.

Returns:

Name Type Description
params dict

Keys: model_id, cross_learning, context_length, device_map, torch_dtype, predict_kwargs.

Source code in skforecast/foundation/_adapters.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
def get_params(self) -> dict:
    """
    Return the adapter's constructor parameters.

    Returns
    -------
    params : dict
        Keys: `model_id`, `cross_learning`, `context_length`,
        `device_map`, `torch_dtype`, `predict_kwargs`.

    """
    return {
        'model_id':       self.model_id,
        'cross_learning': self.cross_learning,
        'context_length': self.context_length,
        'device_map':     self.device_map,
        'torch_dtype':    self.torch_dtype,
        'predict_kwargs': self.predict_kwargs or None,
    }

set_params

set_params(**params)

Set adapter parameters. Resets the pipeline when a device or dtype param changes, since those are baked into the loaded pipeline.

Parameters:

Name Type Description Default
**params

Valid keys: model_id, cross_learning, context_length, device_map, torch_dtype, predict_kwargs.

{}

Returns:

Name Type Description
self ChronosAdapter
Source code in skforecast/foundation/_adapters.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def set_params(self, **params) -> ChronosAdapter:
    """
    Set adapter parameters. Resets the pipeline when a device or dtype
    param changes, since those are baked into the loaded pipeline.

    Parameters
    ----------
    **params :
        Valid keys: `model_id`, `cross_learning`, `context_length`,
        `device_map`, `torch_dtype`, `predict_kwargs`.

    Returns
    -------
    self : ChronosAdapter

    """

    valid = {
        'model_id', 'cross_learning', 'context_length',
        'device_map', 'torch_dtype', 'predict_kwargs',
    }
    invalid = set(params) - valid
    if invalid:
        raise ValueError(
            f"Invalid parameter(s) for ChronosAdapter: {sorted(invalid)}. "
            f"Valid parameters are: {sorted(valid)}."
        )

    pipeline_reset_keys = {'model_id', 'device_map', 'torch_dtype'}
    if params.keys() & pipeline_reset_keys:
        self._pipeline = None

    for key, value in params.items():
        if key == 'predict_kwargs':
            self.predict_kwargs = value or {}
        elif key == 'context_length':
            if not isinstance(value, int) or value < 1:
                raise ValueError(
                    f"`context_length` must be a positive integer. Got {value!r}."
                )
            self.context_length = value
        else:
            setattr(self, key, value)

    return self

fit

fit(context, context_exog)

Store the training series and optional historical exogenous variables. No model training occurs since Chronos is a zero-shot inference model.

All input normalization and validation is performed upstream by FoundationModel; this method receives canonical dicts only.

Parameters:

Name Type Description Default
context dict pandas Series

Normalized training series, one entry per series.

required
context_exog dict pandas DataFrame, pandas Series, or None

Per-series historical exogenous variables (past covariates).

required

Returns:

Name Type Description
self ChronosAdapter
Source code in skforecast/foundation/_adapters.py
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
def fit(
    self,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None],
) -> ChronosAdapter:
    """
    Store the training series and optional historical exogenous variables.
    No model training occurs since Chronos is a zero-shot inference model.

    All input normalization and validation is performed upstream by
    `FoundationModel`; this method receives canonical dicts only.

    Parameters
    ----------
    context : dict pandas Series
        Normalized training series, one entry per series.
    context_exog : dict pandas DataFrame, pandas Series, or None
        Per-series historical exogenous variables (past covariates).

    Returns
    -------
    self : ChronosAdapter

    """

    self.context_ = context
    self.context_exog_ = context_exog
    self.is_fitted = True

    return self

predict

predict(steps, context, context_exog, exog, quantiles)

Generate predictions using the Chronos pipeline.

All input normalization, validation, and context trimming is performed upstream by FoundationModel; this method receives pre-processed dicts only.

Parameters:

Name Type Description Default
steps int

Number of steps ahead to forecast.

required
context dict

Per-series context windows (already trimmed to context_length).

required
context_exog dict

Per-series past covariates (already trimmed).

required
exog dict

Per-series future covariates for the forecast horizon.

required
quantiles list of float or None

Quantile levels to return. If None, a point forecast (median, quantile 0.5) is produced.

required

Returns:

Name Type Description
predictions dict

Keys are series names. Each value is a 2-D array of shape (steps, n_quantiles).

Source code in skforecast/foundation/_adapters.py
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
def predict(
    self,
    steps: int,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None],
    exog: dict[str, pd.DataFrame | pd.Series | None],
    quantiles: list[float] | tuple[float] | None
) -> dict[str, np.ndarray]:
    """
    Generate predictions using the Chronos pipeline.

    All input normalization, validation, and context trimming is
    performed upstream by `FoundationModel`; this method receives
    pre-processed dicts only.

    Parameters
    ----------
    steps : int
        Number of steps ahead to forecast.
    context : dict
        Per-series context windows (already trimmed to
        `context_length`).
    context_exog : dict
        Per-series past covariates (already trimmed).
    exog : dict
        Per-series future covariates for the forecast horizon.
    quantiles : list of float or None
        Quantile levels to return. If `None`, a point forecast
        (median, quantile 0.5) is produced.

    Returns
    -------
    predictions : dict
        Keys are series names. Each value is a 2-D array of shape
        `(steps, n_quantiles)`.

    """

    # NOTE: the pipeline is loaded lazily here so that the adapter can be
    # instantiated and fitted without requiring Chronos to be installed.
    self._load_pipeline()

    series_names_in = list(context.keys())
    quantile_levels = list(quantiles) if quantiles is not None else [0.5]

    inputs_list = [
        self._build_chronos_input(
            context      = context[name].to_numpy(),
            context_exog = context_exog[name] if context_exog is not None else None,
            exog         = exog[name] if exog is not None else None,
        )
        for name in series_names_in
    ]

    quantile_preds, _ = self._pipeline.predict_quantiles(
        inputs            = inputs_list,
        prediction_length = steps,
        quantile_levels   = quantile_levels,
        cross_learning    = self.cross_learning if len(series_names_in) > 1 else False,
        **self.predict_kwargs,
    )

    predictions: dict[str, np.ndarray] = {}
    for i, name in enumerate(series_names_in):
        q_arr = quantile_preds[i].squeeze(0)
        if hasattr(q_arr, "detach"):
            q_arr = q_arr.detach().cpu().numpy()
        else:
            q_arr = np.asarray(q_arr)
        predictions[name] = q_arr

    return predictions

_load_pipeline

_load_pipeline()

Load the Chronos pipeline into self._pipeline if not already set.

Returns:

Type Description
None

Raises:

Type Description
ImportError

If chronos-forecasting >=2.0 is not installed.

Notes

The pipeline is imported lazily from chronos and instantiated via BaseChronosPipeline.from_pretrained, which auto-dispatches to the correct pipeline class based on the model config. Optional device_map and torch_dtype stored at initialisation are forwarded to the constructor. This method is a no-op when self._pipeline is already populated.

Source code in skforecast/foundation/_adapters.py
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
def _load_pipeline(self) -> None:
    """
    Load the Chronos pipeline into `self._pipeline` if not already set.

    Returns
    -------
    None

    Raises
    ------
    ImportError
        If `chronos-forecasting` >=2.0 is not installed.

    Notes
    -----
    The pipeline is imported lazily from `chronos` and instantiated via
    `BaseChronosPipeline.from_pretrained`, which auto-dispatches to the
    correct pipeline class based on the model config. Optional
    `device_map` and `torch_dtype` stored at initialisation are
    forwarded to the constructor. This method is a no-op when
    `self._pipeline` is already populated.

    """

    if self._pipeline is not None:
        return
    try:
        from chronos import BaseChronosPipeline
    except ImportError as exc:
        raise ImportError(
            "chronos-forecasting >=2.0 is required. "
            "Install it with `pip install chronos-forecasting`."
        ) from exc

    kwargs: dict[str, Any] = {}
    kwargs["device_map"] = self.device_map
    if self.torch_dtype is not None:
        kwargs["torch_dtype"] = self.torch_dtype

    self._pipeline = BaseChronosPipeline.from_pretrained(self.model_id, **kwargs)

_to_covariate_array staticmethod

_to_covariate_array(col_data)

Convert a covariate column to a numpy array.

Numeric columns (int, float) and boolean columns are cast to float32. All other dtypes (object, string, Categorical) are left as-is so that Chronos can handle them as categorical covariates natively.

Parameters:

Name Type Description Default
col_data array - like

A single covariate column (e.g. a pandas Series or 1-D array).

required

Returns:

Name Type Description
col_array numpy ndarray

A 1-D numpy array. Numeric/bool are cast to float32. Others keep their original dtype (typically object for string and categorical data).

Source code in skforecast/foundation/_adapters.py
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
@staticmethod
def _to_covariate_array(col_data: Any) -> np.ndarray:
    """
    Convert a covariate column to a numpy array.

    Numeric columns (int, float) and boolean columns are cast to
    `float32`. All other dtypes (object, string, Categorical) are left
    as-is so that Chronos can handle them as categorical covariates
    natively.

    Parameters
    ----------
    col_data : array-like
        A single covariate column (e.g. a pandas Series or 1-D array).

    Returns
    -------
    col_array : numpy ndarray
        A 1-D numpy array. Numeric/bool are cast to `float32`. Others
        keep their original dtype (typically `object` for string and
        categorical data).

    """

    # Handle pandas Series first to correctly process nullable extension
    # dtypes (pd.Int64Dtype, pd.Float64Dtype, pd.BooleanDtype): np.asarray()
    # on those produces dtype=object with pd.NA sentinels instead of float32.
    if isinstance(col_data, pd.Series):
        if pd.api.types.is_numeric_dtype(col_data) or pd.api.types.is_bool_dtype(col_data):
            return col_data.astype(np.float32).to_numpy()
        return col_data.to_numpy()

    # Fallback for numpy arrays, lists, etc.
    arr = np.asarray(col_data)
    if arr.dtype.kind in ("i", "u", "f", "b"):  # integer, unsigned int, float, bool
        return arr.astype(np.float32)

    return arr

_build_chronos_input

_build_chronos_input(context, context_exog=None, exog=None)

Build the input dict consumed by the pipeline's predict_quantiles method.

Parameters:

Name Type Description Default
context numpy ndarray

1-D array of observed time series values used as context. Must be castable to float32.

required
context_exog pandas DataFrame, pandas Series

Historical exogenous variables whose index is aligned to context. Each column (or the single Series, referenced by its name) becomes an entry in the returned "past_covariates" dict. Numeric and boolean columns are cast to float32; string and categorical columns are passed as-is and handled natively by Chronos.

None
exog pandas DataFrame, pandas Series

Future-known exogenous variables covering the forecast horizon. Must have exactly prediction_length rows. Each column becomes an entry in the returned "future_covariates" dict. Numeric and boolean columns are cast to float32; string and categorical columns are passed as-is.

None

Returns:

Name Type Description
input_dict dict

Dictionary with mandatory key "target" (1-D float32 numpy ndarray) and optional keys "past_covariates" and "future_covariates", each mapping column names to 1-D arrays (float32 for numeric/bool columns, object dtype for string/categorical columns).

Source code in skforecast/foundation/_adapters.py
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
def _build_chronos_input(
    self,
    context: np.ndarray,
    context_exog: pd.DataFrame | pd.Series | None = None,
    exog: pd.DataFrame | pd.Series | None = None,
) -> dict[str, Any]:
    """
    Build the input dict consumed by the pipeline's `predict_quantiles` method.

    Parameters
    ----------
    context : numpy ndarray
        1-D array of observed time series values used as context. Must be
        castable to `float32`.
    context_exog : pandas DataFrame, pandas Series, default None
        Historical exogenous variables whose index is aligned to
        `context`. Each column (or the single Series, referenced by
        its name) becomes an entry in the returned
        "past_covariates" dict. Numeric and boolean columns are
        cast to `float32`; string and categorical columns are passed
        as-is and handled natively by Chronos.
    exog : pandas DataFrame, pandas Series, default None
        Future-known exogenous variables covering the forecast horizon.
        Must have exactly `prediction_length` rows. Each column
        becomes an entry in the returned "future_covariates" dict.
        Numeric and boolean columns are cast to `float32`; string and
        categorical columns are passed as-is.

    Returns
    -------
    input_dict : dict
        Dictionary with mandatory key "target" (1-D `float32`
        `numpy ndarray`) and optional keys "past_covariates" and
        "future_covariates", each mapping column names to 1-D
        arrays (`float32` for numeric/bool columns, `object` dtype
        for string/categorical columns).

    """

    input_dict = {"target": np.asarray(context, dtype=np.float32)}
    if context_exog is not None:
        df = (
            context_exog
            if isinstance(context_exog, pd.DataFrame)
            else context_exog.to_frame()
        )
        input_dict["past_covariates"] = {
            col: ChronosAdapter._to_covariate_array(df[col]) for col in df.columns
        }
    if exog is not None:
        df = (
            exog
            if isinstance(exog, pd.DataFrame)
            else exog.to_frame()
        )
        input_dict["future_covariates"] = {
            col: ChronosAdapter._to_covariate_array(df[col]) for col in df.columns
        }

    return input_dict

skforecast.foundation._adapters.TimesFMAdapter

TimesFMAdapter(
    model_id,
    *,
    model=None,
    context_length=512,
    max_horizon=512,
    forecast_config_kwargs=None
)

Adapter for Google TimesFM foundation models.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "google/timesfm-2.5-200m-pytorch".

required
model object

Pre-loaded and compiled TimesFM model instance. If None, the model is loaded and compiled lazily on the first predict call.

None
context_length int

Maximum number of historical observations to use as context. At fit time only the last context_length observations are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are used as-is. Must be a positive integer. Defaults to 512. TimesFM supports up to 16_384.

512
max_horizon int

Maximum forecast horizon. If predict is called with steps > max_horizon, a ValueError is raised. The model is compiled lazily for the exact requested steps (up to this ceiling) to avoid unnecessary decode iterations. Must be a positive integer.

512
forecast_config_kwargs dict

Additional keyword arguments forwarded verbatim to timesfm.ForecastConfig at compile time. Supported keys: normalize_inputs, use_continuous_quantile_head, force_flip_invariance, infer_is_positive, fix_quantile_crossing. Do not include max_context or max_horizon here — those are controlled by the corresponding adapter parameters.

None

Attributes:

Name Type Description
model_id str

HuggingFace model ID.

context_ dict

Stored training series after fitting.

context_exog_ dict

Not used, present here for API consistency by convention.

context_length int

Maximum number of historical observations used as context.

max_horizon int

Maximum forecast horizon.

forecast_config_kwargs dict

Additional keyword arguments forwarded to ForecastConfig.

is_fitted bool

Whether the adapter has been fitted.

Notes

TimesFM supports only the fixed quantile levels [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]. Requesting any other level raises a ValueError.

Covariate support (via TimesFM's forecast_with_covariates) is not yet implemented. Passing exog or context_exog issues an IgnoredArgumentWarning and the values are discarded.

References

.. [1] https://github.com/google-research/timesfm .. [2] https://huggingface.co/google/timesfm-2.5-200m-pytorch

Initialise the adapter.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "google/timesfm-2.5-200m-pytorch".

required
model object

Pre-loaded and compiled TimesFM model instance. If None, the model is loaded and compiled lazily on the first predict call.

None
context_length int

Maximum number of historical observations to retain as context. At fit time only the last context_length observations of series are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are passed as-is. Must be a positive integer.

512
max_horizon int

Maximum forecast horizon. If predict is called with steps > max_horizon, a ValueError is raised. The model is compiled lazily for the exact requested steps (up to this ceiling) to avoid unnecessary decode iterations. Must be a positive integer.

512
forecast_config_kwargs dict

Additional keyword arguments forwarded verbatim to timesfm.ForecastConfig at compile time.

None

Methods:

Name Description
get_params

Return the adapter's constructor parameters.

set_params

Set adapter parameters. Resets the model when parameters that affect

fit

Store the training series.

predict

Generate predictions using the TimesFM model.

Source code in skforecast/foundation/_adapters.py
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
def __init__(
    self,
    model_id: str,
    *,
    model: Any | None = None,
    context_length: int = 512,
    max_horizon: int = 512,
    forecast_config_kwargs: dict[str, Any] | None = None,
) -> None:
    """
    Initialise the adapter.

    Parameters
    ----------
    model_id : str
        HuggingFace model ID, e.g. "google/timesfm-2.5-200m-pytorch".
    model : object, default None
        Pre-loaded and compiled TimesFM model instance. If `None`, the
        model is loaded and compiled lazily on the first `predict` call.
    context_length : int, default 512
        Maximum number of historical observations to retain as context.
        At `fit` time only the last `context_length` observations of
        `series` are stored. At `predict` time, if `context` is
        longer than `context_length` it is trimmed to this length;
        if it is shorter, all available observations are passed as-is.
        Must be a positive integer.
    max_horizon : int, default 512
        Maximum forecast horizon. If `predict` is called with
        `steps > max_horizon`, a `ValueError` is raised. The model
        is compiled lazily for the exact requested `steps` (up to
        this ceiling) to avoid unnecessary decode iterations. Must
        be a positive integer.
    forecast_config_kwargs : dict, default None
        Additional keyword arguments forwarded verbatim to
        `timesfm.ForecastConfig` at compile time.

    """

    if not isinstance(context_length, int) or context_length < 1:
        raise ValueError(
            f"`context_length` must be a positive integer. Got {context_length!r}."
        )
    if not isinstance(max_horizon, int) or max_horizon < 1:
        raise ValueError(
            f"`max_horizon` must be a positive integer. Got {max_horizon!r}."
        )

    self.model_id               = model_id
    self._model                 = model
    self.context_               = None
    self.context_exog_          = None
    self.context_length         = context_length
    self.max_horizon            = max_horizon
    self.forecast_config_kwargs = dict(forecast_config_kwargs) if forecast_config_kwargs else {}
    self.is_fitted              = False

Attributes

SUPPORTED_QUANTILES class-attribute instance-attribute

SUPPORTED_QUANTILES = [
    0.1,
    0.2,
    0.3,
    0.4,
    0.5,
    0.6,
    0.7,
    0.8,
    0.9,
]

allow_exog class-attribute instance-attribute

allow_exog = False

model_id instance-attribute

model_id = model_id

_model instance-attribute

_model = model

context_ instance-attribute

context_ = None

context_exog_ instance-attribute

context_exog_ = None

context_length instance-attribute

context_length = context_length

max_horizon instance-attribute

max_horizon = max_horizon

forecast_config_kwargs instance-attribute

forecast_config_kwargs = (
    dict(forecast_config_kwargs)
    if forecast_config_kwargs
    else {}
)

is_fitted instance-attribute

is_fitted = False

Functions

get_params

get_params()

Return the adapter's constructor parameters.

Returns:

Name Type Description
params dict

Keys: model_id, context_length, max_horizon, forecast_config_kwargs.

Source code in skforecast/foundation/_adapters.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
def get_params(self) -> dict:
    """
    Return the adapter's constructor parameters.

    Returns
    -------
    params : dict
        Keys: `model_id`, `context_length`, `max_horizon`,
        `forecast_config_kwargs`.

    """
    return {
        'model_id':               self.model_id,
        'context_length':         self.context_length,
        'max_horizon':            self.max_horizon,
        'forecast_config_kwargs': self.forecast_config_kwargs or None,
    }

set_params

set_params(**params)

Set adapter parameters. Resets the model when parameters that affect compilation change (model_id, context_length, max_horizon, forecast_config_kwargs).

Parameters:

Name Type Description Default
**params

Valid keys: model_id, context_length, max_horizon, forecast_config_kwargs.

{}

Returns:

Name Type Description
self TimesFMAdapter
Source code in skforecast/foundation/_adapters.py
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
def set_params(self, **params) -> TimesFMAdapter:
    """
    Set adapter parameters. Resets the model when parameters that affect
    compilation change (`model_id`, `context_length`, `max_horizon`,
    `forecast_config_kwargs`).

    Parameters
    ----------
    **params :
        Valid keys: `model_id`, `context_length`, `max_horizon`,
        `forecast_config_kwargs`.

    Returns
    -------
    self : TimesFMAdapter

    """

    valid = {'model_id', 'context_length', 'max_horizon', 'forecast_config_kwargs'}
    invalid = set(params) - valid
    if invalid:
        raise ValueError(
            f"Invalid parameter(s) for TimesFMAdapter: {sorted(invalid)}. "
            f"Valid parameters are: {sorted(valid)}."
        )
    model_reset_keys = {'model_id', 'context_length', 'max_horizon', 'forecast_config_kwargs'}
    if params.keys() & model_reset_keys:
        self._model = None
    for key, value in params.items():
        if key == 'context_length':
            if not isinstance(value, int) or value < 1:
                raise ValueError(
                    f"`context_length` must be a positive integer. Got {value!r}."
                )
            self.context_length = value
        elif key == 'max_horizon':
            if not isinstance(value, int) or value < 1:
                raise ValueError(
                    f"`max_horizon` must be a positive integer. Got {value!r}."
                )
            self.max_horizon = value
        elif key == 'forecast_config_kwargs':
            self.forecast_config_kwargs = dict(value) if value else {}
        else:
            setattr(self, key, value)

    return self

fit

fit(context, context_exog)

Store the training series. No model training occurs since TimesFM is a zero-shot inference model.

All input normalization and validation is performed upstream by FoundationModel; this method receives canonical dicts only.

Parameters:

Name Type Description Default
context dict pandas Series

Normalized training series, one entry per series.

required
context_exog Any

Not used, present here for API consistency by convention.

required

Returns:

Name Type Description
self TimesFMAdapter
Source code in skforecast/foundation/_adapters.py
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
def fit(
    self,
    context: dict[str, pd.Series],
    context_exog: Any,
) -> TimesFMAdapter:
    """
    Store the training series.
    No model training occurs since TimesFM is a zero-shot inference model.

    All input normalization and validation is performed upstream by
    `FoundationModel`; this method receives canonical dicts only.

    Parameters
    ----------
    context : dict pandas Series
        Normalized training series, one entry per series.
    context_exog : Any
        Not used, present here for API consistency by convention.

    Returns
    -------
    self : TimesFMAdapter

    """

    self.context_ = context
    self.is_fitted = True

    return self

predict

predict(steps, context, context_exog, exog, quantiles)

Generate predictions using the TimesFM model.

All input normalization, validation, and context trimming is performed upstream by FoundationModel; this method receives pre-processed dicts only.

Parameters:

Name Type Description Default
steps int

Number of steps ahead to forecast.

required
context dict

Per-series context windows (already trimmed to context_length).

required
context_exog Any

Not used, present here for API consistency by convention.

required
exog Any

Not used, present here for API consistency by convention.

required
quantiles list of float or None

Quantile levels. Must be a subset of SUPPORTED_QUANTILES.

required

Returns:

Name Type Description
predictions dict

Keys are series names. Each value is a 2-D array of shape (steps, n_quantiles).

Raises:

Type Description
ValueError

If a requested quantile level is not in SUPPORTED_QUANTILES or steps exceeds max_horizon.

Source code in skforecast/foundation/_adapters.py
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
def predict(
    self,
    steps: int,
    context: dict[str, pd.Series],
    context_exog: Any,
    exog: Any,
    quantiles: list[float] | tuple[float] | None,
) -> dict[str, np.ndarray]:
    """
    Generate predictions using the TimesFM model.

    All input normalization, validation, and context trimming is
    performed upstream by `FoundationModel`; this method receives
    pre-processed dicts only.

    Parameters
    ----------
    steps : int
        Number of steps ahead to forecast.
    context : dict
        Per-series context windows (already trimmed to
        `context_length`).
    context_exog : Any
        Not used, present here for API consistency by convention.
    exog : Any
        Not used, present here for API consistency by convention.
    quantiles : list of float or None
        Quantile levels. Must be a subset of `SUPPORTED_QUANTILES`.

    Returns
    -------
    predictions : dict
        Keys are series names. Each value is a 2-D array of shape
        `(steps, n_quantiles)`.

    Raises
    ------
    ValueError
        If a requested quantile level is not in `SUPPORTED_QUANTILES`
        or `steps` exceeds `max_horizon`.

    """

    if quantiles is not None:
        quantile_list = list(quantiles)
        for q in quantile_list:
            if not any(abs(q - sq) < 1e-9 for sq in self.SUPPORTED_QUANTILES):
                raise ValueError(
                    f"TimesFM only supports quantile levels "
                    f"{self.SUPPORTED_QUANTILES}. Got {q!r}. "
                    f"Quantile interpolation is not supported."
                )
    else:
        quantile_list = None

    if steps > self.max_horizon:
        raise ValueError(
            f"`steps` ({steps}) exceeds `max_horizon` ({self.max_horizon})."
        )

    self._load_model()
    self._ensure_compiled(steps)

    series_names_in = list(context.keys())
    inputs_list = [
        context[name].to_numpy() for name in series_names_in
    ]

    point_forecast, quantile_forecast = self._model.forecast(
        horizon=steps,
        inputs=inputs_list,
    )
    # point_forecast  : (n_series, steps)
    # quantile_forecast: (n_series, steps, 10)  — idx 0 = mean, 1-9 = q0.1-q0.9

    predictions: dict[str, np.ndarray] = {}
    for i, name in enumerate(series_names_in):
        if quantile_list is None:
            # Point forecast: shape (steps, 1)
            predictions[name] = np.asarray(point_forecast[i]).reshape(-1, 1)
        else:
            q_indices = [round(q * 10) for q in quantile_list]
            qf = np.asarray(quantile_forecast[i])
            predictions[name] = qf[:, q_indices]  # (steps, n_quantiles)

    return predictions

_load_model

_load_model()

Load (but do not compile) the TimesFM model into self._model if not already set.

Returns:

Type Description
None

Raises:

Type Description
ImportError

If timesfm[torch] is not installed.

Notes

The model is imported lazily from timesfm and loaded via TimesFM_2p5_200M_torch.from_pretrained. Compilation is deferred to _ensure_compiled, which is called from predict with the actual forecast horizon so that the compiled decode graph is sized exactly for the requested number of steps rather than the (much larger) max_horizon ceiling. This method is a no-op when self._model is already populated.

Source code in skforecast/foundation/_adapters.py
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
def _load_model(self) -> None:
    """
    Load (but do not compile) the TimesFM model into `self._model`
    if not already set.

    Returns
    -------
    None

    Raises
    ------
    ImportError
        If `timesfm[torch]` is not installed.

    Notes
    -----
    The model is imported lazily from `timesfm` and loaded via
    `TimesFM_2p5_200M_torch.from_pretrained`. Compilation is deferred to
    `_ensure_compiled`, which is called from `predict` with the actual
    forecast horizon so that the compiled decode graph is sized exactly
    for the requested number of steps rather than the (much larger)
    `max_horizon` ceiling. This method is a no-op when `self._model` is
    already populated.
    """

    if self._model is not None:
        return
    try:
        import timesfm
    except ImportError as exc:
        raise ImportError(
            "timesfm is required for TimesFMAdapter. "
            "Install it with `pip install git+https://github.com/google-research/timesfm.git`."
        ) from exc

    # Workaround for a compatibility issue between huggingface_hub and
    # timesfm: huggingface_hub's `from_pretrained` passes `proxies` and
    # `resume_download` to `_from_pretrained`, but timesfm's
    # `_from_pretrained` does not declare them as explicit parameters, so
    # they fall into **model_kwargs and are forwarded to __init__, raising
    # a TypeError. A local subclass overrides `_from_pretrained` to absorb
    # those kwargs without modifying any global state.
    class _TimesFMCompat(timesfm.TimesFM_2p5_200M_torch):
        @classmethod
        def _from_pretrained(cls, *, proxies=None, resume_download=None, **kwargs):  # type: ignore[override]
            return super()._from_pretrained(**kwargs)

    self._model = _TimesFMCompat.from_pretrained(self.model_id)

_ensure_compiled

_ensure_compiled(steps)

Compile the model for the given forecast horizon if not already compiled for at least steps steps.

Parameters:

Name Type Description Default
steps int

The forecast horizon that the model must support.

required

Returns:

Type Description
None
Notes

This is separated from _load_model so that compilation uses the actual number of requested forecast steps rather than max_horizon. TimesFM's compiled decode always runs forecast_config.max_horizon autoregressive decode iterations regardless of the requested horizon; the true horizon is only used to slice the output afterwards. When the compiled max_horizon is large (e.g. the default 512) but steps is small (e.g. 12), the model performs up to (max_horizon - 1) // output_patch_len unnecessary extra transformer forward passes per inference call. Compiling here with max_horizon = steps reduces those wasted passes to zero for the typical backtesting case where steps is constant across folds.

If the model was already compiled for a horizon >= steps (e.g. a pre-compiled model passed via the model constructor argument), this method is a no-op.

Source code in skforecast/foundation/_adapters.py
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
def _ensure_compiled(self, steps: int) -> None:
    """
    Compile the model for the given forecast horizon if not already
    compiled for at least `steps` steps.

    Parameters
    ----------
    steps : int
        The forecast horizon that the model must support.

    Returns
    -------
    None

    Notes
    -----
    This is separated from `_load_model` so that compilation uses the
    *actual* number of requested forecast steps rather than `max_horizon`.
    TimesFM's compiled decode always runs `forecast_config.max_horizon`
    autoregressive decode iterations regardless of the requested horizon;
    the true horizon is only used to *slice* the output afterwards. When
    the compiled `max_horizon` is large (e.g. the default 512) but
    `steps` is small (e.g. 12), the model performs up to
    `(max_horizon - 1) // output_patch_len` unnecessary extra transformer
    forward passes per inference call. Compiling here with
    `max_horizon = steps` reduces those wasted passes to zero for the
    typical backtesting case where `steps` is constant across folds.

    If the model was already compiled for a horizon `>= steps` (e.g. a
    pre-compiled model passed via the `model` constructor argument), this
    method is a no-op.
    """

    fc = getattr(self._model, 'forecast_config', None)
    if fc is not None and steps <= fc.max_horizon:
        return

    import timesfm
    self._model.compile(
        timesfm.ForecastConfig(
            max_context = self.context_length,
            max_horizon = steps,
            **self.forecast_config_kwargs,
        )
    )

skforecast.foundation._adapters.MoiraiAdapter

MoiraiAdapter(
    model_id,
    *,
    module=None,
    context_length=2048,
    device="auto"
)

Adapter for Salesforce Moirai foundation models.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "Salesforce/moirai-2.0-R-small". Must be a Salesforce/moirai-2.0-R-{small,base,large} variant.

required
module object

Pre-loaded Moirai2Module instance. If None, the module is loaded lazily on the first call to predict.

None
context_length int

Maximum number of historical observations to use as context. At fit time only the last context_length observations are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are used as-is. Must be a positive integer.

2048
device str

Device placement for the model. "auto" selects the best available accelerator (CUDA > MPS > CPU). Also accepts explicit values such as "cuda", "mps", or "cpu".

'auto'

Attributes:

Name Type Description
model_id str

HuggingFace model ID.

context_ dict

Stored training series after fitting.

context_exog_ dict

Not used, present here for API consistency by convention.

context_length int

Maximum number of historical observations used as context.

device str

Device placement for the model.

_forecast_obj object

Internal Moirai forecast object, populated at the first call to predict.

is_fitted bool

Whether the adapter has been fitted.

Notes

Moirai supports only the fixed quantile levels [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]. Requesting any other level raises a ValueError.

Covariate support via the high-level Moirai2Forecast.predict() API is not functional: the padding/truncation loop inside predict() clips every list-valued field — including feat_dynamic_real — to context_length, discarding the future portion that future covariates require. Passing exog or context_exog issues an IgnoredArgumentWarning and the values are discarded.

References

.. [1] https://github.com/SalesforceAIResearch/uni2ts .. [2] https://huggingface.co/Salesforce/moirai-2.0-R-small

Initialise the adapter.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "Salesforce/moirai-2.0-R-small".

required
module object

Pre-loaded Moirai2Module instance. If None, the module is loaded lazily on the first call to predict.

None
context_length int

Maximum number of historical observations to retain as context. At fit time only the last context_length observations of series are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are passed as-is. Must be a positive integer.

2048
device str

Device placement for the model. "auto" selects the best available accelerator (CUDA > MPS > CPU). Also accepts explicit values such as "cuda", "mps", or "cpu".

'auto'

Methods:

Name Description
get_params

Return the adapter's constructor parameters.

set_params

Set adapter parameters. Resets the module and forecast object when

fit

Store the training series.

predict

Generate predictions using Moirai.

Source code in skforecast/foundation/_adapters.py
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
def __init__(
    self,
    model_id: str,
    *,
    module: Any | None = None,
    context_length: int = 2048,
    device: str = "auto",
) -> None:
    """
    Initialise the adapter.

    Parameters
    ----------
    model_id : str
        HuggingFace model ID, e.g. `"Salesforce/moirai-2.0-R-small"`.
    module : object, default None
        Pre-loaded `Moirai2Module` instance. If `None`, the module
        is loaded lazily on the first call to `predict`.
    context_length : int, default 2048
        Maximum number of historical observations to retain as context.
        At `fit` time only the last `context_length` observations of
        `series` are stored. At `predict` time, if `context`
        is longer than `context_length` it is trimmed to this length;
        if it is shorter, all available observations are passed as-is.
        Must be a positive integer.
    device : str, default 'auto'
        Device placement for the model. `"auto"` selects the best
        available accelerator (CUDA > MPS > CPU). Also accepts
        explicit values such as `"cuda"`, `"mps"`, or `"cpu"`.

    """

    if not isinstance(context_length, int) or context_length < 1:
        raise ValueError(
            f"`context_length` must be a positive integer. "
            f"Got {context_length!r}."
        )

    self.model_id       = model_id
    self._module        = module
    self.context_       = None
    self.context_exog_  = None
    self.context_length = context_length
    self.device         = device
    self._forecast_obj  = None
    self.is_fitted      = False

Attributes

SUPPORTED_QUANTILES class-attribute instance-attribute

SUPPORTED_QUANTILES = [
    0.1,
    0.2,
    0.3,
    0.4,
    0.5,
    0.6,
    0.7,
    0.8,
    0.9,
]

allow_exog class-attribute instance-attribute

allow_exog = False

model_id instance-attribute

model_id = model_id

_module instance-attribute

_module = module

context_ instance-attribute

context_ = None

context_exog_ instance-attribute

context_exog_ = None

context_length instance-attribute

context_length = context_length

device instance-attribute

device = device

_forecast_obj instance-attribute

_forecast_obj = None

is_fitted instance-attribute

is_fitted = False

Functions

get_params

get_params()

Return the adapter's constructor parameters.

Returns:

Name Type Description
params dict

Keys: model_id, context_length, device.

Source code in skforecast/foundation/_adapters.py
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
def get_params(self) -> dict:
    """
    Return the adapter's constructor parameters.

    Returns
    -------
    params : dict
        Keys: `model_id`, `context_length`, `device`.
    """
    return {
        'model_id':       self.model_id,
        'context_length': self.context_length,
        'device':         self.device,
    }

set_params

set_params(**params)

Set adapter parameters. Resets the module and forecast object when model_id or context_length changes.

Parameters:

Name Type Description Default
**params

Valid keys: model_id, context_length, device.

{}

Returns:

Name Type Description
self MoiraiAdapter
Source code in skforecast/foundation/_adapters.py
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
def set_params(self, **params) -> MoiraiAdapter:
    """
    Set adapter parameters. Resets the module and forecast object when
    `model_id` or `context_length` changes.

    Parameters
    ----------
    **params :
        Valid keys: `model_id`, `context_length`, `device`.

    Returns
    -------
    self : MoiraiAdapter

    """

    valid = {'model_id', 'context_length', 'device'}
    invalid = set(params) - valid
    if invalid:
        raise ValueError(
            f"Invalid parameter(s) for MoiraiAdapter: {sorted(invalid)}. "
            f"Valid parameters are: {sorted(valid)}."
        )
    if params.keys() & {'model_id', 'context_length', 'device'}:
        self._module = None
        self._forecast_obj = None
    for key, value in params.items():
        if key == 'context_length':
            if not isinstance(value, int) or value < 1:
                raise ValueError(
                    f"`context_length` must be a positive integer. "
                    f"Got {value!r}."
                )
            self.context_length = value
        else:
            setattr(self, key, value)

    return self

fit

fit(context, context_exog)

Store the training series. No model training occurs since Moirai is a zero-shot inference model.

All input normalization and validation is performed upstream by FoundationModel; this method receives canonical dicts only.

Parameters:

Name Type Description Default
context dict pandas Series

Normalized training series, one entry per series.

required
context_exog Any

Not used, present here for API consistency by convention.

required

Returns:

Name Type Description
self MoiraiAdapter
Source code in skforecast/foundation/_adapters.py
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
def fit(
    self,
    context: dict[str, pd.Series],
    context_exog: Any,
) -> MoiraiAdapter:
    """
    Store the training series.
    No model training occurs since Moirai is a zero-shot inference model.

    All input normalization and validation is performed upstream by
    `FoundationModel`; this method receives canonical dicts only.

    Parameters
    ----------
    context : dict pandas Series
        Normalized training series, one entry per series.
    context_exog : Any
        Not used, present here for API consistency by convention.

    Returns
    -------
    self : MoiraiAdapter

    """

    self.context_ = context
    self.is_fitted = True

    return self

predict

predict(steps, context, context_exog, exog, quantiles)

Generate predictions using Moirai.

All input normalization, validation, and context trimming is performed upstream by FoundationModel; this method receives pre-processed dicts only.

Parameters:

Name Type Description Default
steps int

Number of steps ahead to forecast.

required
context dict pandas Series

Per-series context windows (already trimmed to context_length).

required
context_exog Any

Not used, present here for API consistency by convention.

required
exog Any

Not used, present here for API consistency by convention.

required
quantiles list of float or None

Quantile levels. Must be a subset of SUPPORTED_QUANTILES.

required

Returns:

Name Type Description
predictions dict

Keys are series names. Each value is a 2-D array of shape (steps, n_quantiles).

Raises:

Type Description
ValueError

If a requested quantile level is not in SUPPORTED_QUANTILES.

Source code in skforecast/foundation/_adapters.py
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
def predict(
    self,
    steps: int,
    context: dict[str, pd.Series],
    context_exog: Any,
    exog: Any,
    quantiles: list[float] | tuple[float] | None,
) -> dict[str, np.ndarray]:
    """
    Generate predictions using Moirai.

    All input normalization, validation, and context trimming is
    performed upstream by `FoundationModel`; this method receives
    pre-processed dicts only.

    Parameters
    ----------
    steps : int
        Number of steps ahead to forecast.
    context : dict pandas Series
        Per-series context windows (already trimmed to
        `context_length`).
    context_exog : Any
        Not used, present here for API consistency by convention.
    exog : Any
        Not used, present here for API consistency by convention.
    quantiles : list of float or None
        Quantile levels. Must be a subset of `SUPPORTED_QUANTILES`.

    Returns
    -------
    predictions : dict
        Keys are series names. Each value is a 2-D array of shape
        `(steps, n_quantiles)`.

    Raises
    ------
    ValueError
        If a requested quantile level is not in `SUPPORTED_QUANTILES`.

    """

    if quantiles is not None:
        quantile_list = list(quantiles)
        for q in quantile_list:
            if not any(abs(q - sq) < 1e-9 for sq in self.SUPPORTED_QUANTILES):
                raise ValueError(
                    f"Moirai only supports quantile levels "
                    f"{self.SUPPORTED_QUANTILES}. Got {q!r}. "
                    f"Quantile interpolation is not supported."
                )
    else:
        quantile_list = None

    quantile_levels = quantile_list if quantile_list is not None else [0.5]
    q_indices = [
        next(
            i for i, sq in enumerate(self.SUPPORTED_QUANTILES)
            if abs(q - sq) < 1e-9
        )
        for q in quantile_levels
    ]

    series_names_in = list(context.keys())
    inputs_list = [
        context[name].to_numpy(dtype=np.float32).reshape(-1, 1)
        for name in series_names_in
    ]

    raw = self._run_inference(inputs_list, steps)

    predictions: dict[str, np.ndarray] = {}
    for i, name in enumerate(series_names_in):
        predictions[name] = raw[i][q_indices, :].T  # (steps, n_quantiles)

    return predictions

_load_module

_load_module()

Load the Moirai2Module into self._module if not already set.

Returns:

Type Description
None

Raises:

Type Description
ImportError

If uni2ts is not installed.

Notes

The module is imported lazily from uni2ts and instantiated via Moirai2Module.from_pretrained, then set to evaluation mode. This method is a no-op when self._module is already populated.

Source code in skforecast/foundation/_adapters.py
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
def _load_module(self) -> None:
    """
    Load the `Moirai2Module` into `self._module` if not already set.

    Returns
    -------
    None

    Raises
    ------
    ImportError
        If `uni2ts` is not installed.

    Notes
    -----
    The module is imported lazily from `uni2ts` and instantiated via
    `Moirai2Module.from_pretrained`, then set to evaluation mode.
    This method is a no-op when `self._module` is already populated.
    """

    if self._module is not None:
        return
    try:
        from uni2ts.model.moirai2 import Moirai2Module
    except ImportError as exc:
        raise ImportError(
            "uni2ts is required for MoiraiAdapter. "
            "Install it with `pip install uni2ts`."
        ) from exc
    self._module = Moirai2Module.from_pretrained(self.model_id)
    self._module.eval()

_ensure_forecast_obj

_ensure_forecast_obj()

Build the Moirai2Forecast inference wrapper if not already set.

Returns:

Type Description
None

Raises:

Type Description
ImportError

If uni2ts is not installed.

Notes

Calls _load_module then wraps self._module in a Moirai2Forecast with prediction_length=1 (overridden per-call via hparams_context), sets it to evaluation mode, and moves it to the device specified by self.device. This method is a no-op when self._forecast_obj is already populated.

Source code in skforecast/foundation/_adapters.py
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
def _ensure_forecast_obj(self) -> None:
    """
    Build the `Moirai2Forecast` inference wrapper if not already set.

    Returns
    -------
    None

    Raises
    ------
    ImportError
        If `uni2ts` is not installed.

    Notes
    -----
    Calls `_load_module` then wraps `self._module` in a
    `Moirai2Forecast` with `prediction_length=1` (overridden
    per-call via `hparams_context`), sets it to evaluation mode,
    and moves it to the device specified by `self.device`.
    This method is a no-op when `self._forecast_obj` is already
    populated.
    """

    if self._forecast_obj is not None:
        return

    self._load_module()
    from uni2ts.model.moirai2 import Moirai2Forecast

    self._forecast_obj = Moirai2Forecast(
        module                     = self._module,
        prediction_length          = 1,
        context_length             = self.context_length,
        target_dim                 = 1,
        feat_dynamic_real_dim      = 0,
        past_feat_dynamic_real_dim = 0,
    ).eval()

    resolved_device = _resolve_torch_device(self.device)
    if resolved_device == "mps":
        warnings.warn(
            "MPS device is not supported by Moirai because the uni2ts "
            "library uses float64 operations internally. Falling back "
            "to CPU.",
            stacklevel=6,
        )
        resolved_device = "cpu"
    self._forecast_obj.to(resolved_device)

_run_inference

_run_inference(inputs_list, steps)

Run batched inference with Moirai2Forecast.

Parameters:

Name Type Description Default
inputs_list list of numpy ndarray

List of 2-D arrays with shape (T, 1), one per series. Each array holds float32 values.

required
steps int

Forecast horizon.

required

Returns:

Name Type Description
raw numpy ndarray

Array of shape (n_series, 9, steps) containing quantile forecasts for the 9 fixed levels in SUPPORTED_QUANTILES order.

Source code in skforecast/foundation/_adapters.py
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
def _run_inference(
    self,
    inputs_list: list[np.ndarray],
    steps: int,
) -> np.ndarray:
    """
    Run batched inference with `Moirai2Forecast`.

    Parameters
    ----------
    inputs_list : list of numpy ndarray
        List of 2-D arrays with shape `(T, 1)`, one per series.
        Each array holds `float32` values.
    steps : int
        Forecast horizon.

    Returns
    -------
    raw : numpy ndarray
        Array of shape `(n_series, 9, steps)` containing quantile
        forecasts for the 9 fixed levels in `SUPPORTED_QUANTILES`
        order.

    """

    self._ensure_forecast_obj()
    with self._forecast_obj.hparams_context(prediction_length=steps):
        raw = self._forecast_obj.predict(inputs_list)

    return raw

skforecast.foundation._adapters.TabICLAdapter

TabICLAdapter(
    model_id,
    *,
    model=None,
    context_length=4096,
    point_estimate="mean",
    tabicl_config=None,
    temporal_features=None
)

Adapter for TabICL zero-shot time-series foundation models.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "soda-inria/tabicl".

required
model object

Pre-instantiated TabICLForecaster instance. If None, a new instance is created lazily on the first call to predict. Intended for testing only.

None
context_length int

Maximum number of historical observations to use as context. At fit time only the last context_length observations are stored. At predict time, if context is longer than context_length it is trimmed to this length; if it is shorter, all available observations are used as-is. Must be a positive integer.

4096
point_estimate str

Method used to derive the point forecast from the TabICL output. Accepted values: 'mean', 'median'.

'mean'
tabicl_config dict

Additional keyword arguments forwarded verbatim to TabICLRegressor at inference time. If None, defaults to empty dict (TabICL's own defaults).

None
temporal_features list

List of TimeTransform instances applied to the time series before inference. If None, TabICL uses its default transforms: [IndexEncoder(), DatetimeEncoder(), AutoPeriodicEncoder()]. Pass an empty list to disable all temporal feature engineering.

None

Attributes:

Name Type Description
model_id str

HuggingFace model ID.

context_ dict

Stored training series after fitting.

context_exog_ dict

Stored historical exogenous variables after fitting.

context_length int

Maximum number of historical observations used as context.

point_estimate str

Point forecast method.

tabicl_config dict

Additional configuration forwarded to TabICLRegressor.

temporal_features list

Temporal feature transforms applied to the series.

is_fitted bool

Whether the adapter has been fitted.

_model object

Internal TabICLForecaster instance. None until the first call to predict, after which it is cached for reuse.

Notes

TabICL supports arbitrary quantile levels (any float in [0, 1]), unlike models with fixed quantile sets such as TimesFM or Moirai.

Covariate support is available: extra columns in context and exog are forwarded as covariates. TabICL uses only the intersection of columns present in both context and future data (missing values are filled with NaN).

Series with a RangeIndex are accepted. Internally, TabICL requires datetime timestamps, so a synthetic daily DatetimeIndex (starting 2000-01-01) is used. Calendar-based transforms (DatetimeEncoder, AutoPeriodicEncoder) will not be meaningful for such series; consider passing temporal_features=[] or temporal_features=[IndexEncoder()] in that case.

References

.. [1] https://github.com/soda-inria/tabicl .. [2] https://tabicl.readthedocs.io/en/latest/

Initialise the adapter.

Parameters:

Name Type Description Default
model_id str

HuggingFace model ID, e.g. "soda-inria/tabicl".

required
model object

Pre-instantiated TabICLForecaster instance. If None, a new instance is created lazily on the first call to predict. Intended for testing only.

None
context_length int

Maximum number of historical observations to retain as context. At fit time only the last context_length observations of series (and exog) are stored. At predict time, if context is longer than context_length it is trimmed to this length before inference; if it is shorter, all available observations are passed as-is. Must be a positive integer.

4096
point_estimate str

Method used to derive the point forecast. Accepted values: 'mean', 'median'.

'mean'
tabicl_config dict

Additional keyword arguments forwarded verbatim to TabICLRegressor at inference time.

None
temporal_features list

List of TimeTransform instances applied before inference. If None, TabICL uses its defaults. Pass [] to disable all temporal feature engineering.

None

Methods:

Name Description
get_params

Return the adapter's constructor parameters.

set_params

Set adapter parameters. Resets the model when any parameter changes,

fit

Store the training series and optional historical exogenous variables.

predict

Generate predictions using TabICL.

Source code in skforecast/foundation/_adapters.py
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
def __init__(
    self,
    model_id: str,
    *,
    model: Any | None = None,
    context_length: int = 4096,
    point_estimate: str = "mean",
    tabicl_config: dict[str, Any] | None = None,
    temporal_features: list[Any] | None = None,
) -> None:
    """
    Initialise the adapter.

    Parameters
    ----------
    model_id : str
        HuggingFace model ID, e.g. `"soda-inria/tabicl"`.
    model : object, default None
        Pre-instantiated `TabICLForecaster` instance. If `None`, a new
        instance is created lazily on the first call to `predict`.
        Intended for testing only.
    context_length : int, default 4096
        Maximum number of historical observations to retain as context.
        At `fit` time only the last `context_length` observations of
        `series` (and `exog`) are stored. At `predict` time, if
        `context` is longer than `context_length` it is trimmed to
        this length before inference; if it is shorter, all available
        observations are passed as-is. Must be a positive integer.
    point_estimate : str, default 'mean'
        Method used to derive the point forecast. Accepted values:
        `'mean'`, `'median'`.
    tabicl_config : dict, default None
        Additional keyword arguments forwarded verbatim to
        `TabICLRegressor` at inference time.
    temporal_features : list, default None
        List of `TimeTransform` instances applied before inference. If
        `None`, TabICL uses its defaults. Pass `[]` to disable all
        temporal feature engineering.

    """

    if not isinstance(context_length, int) or context_length < 1:
        raise ValueError(
            f"`context_length` must be a positive integer. Got {context_length!r}."
        )
    if point_estimate not in ("mean", "median"):
        raise ValueError(
            f"`point_estimate` must be 'mean' or 'median'. Got {point_estimate!r}."
        )

    self.model_id          = model_id
    self._model            = model
    self.context_          = None
    self.context_exog_     = None
    self.context_length    = context_length
    self.point_estimate    = point_estimate
    self.tabicl_config     = dict(tabicl_config) if tabicl_config else {}
    self.temporal_features = temporal_features
    self.is_fitted         = False

Attributes

allow_exog class-attribute instance-attribute

allow_exog = True

model_id instance-attribute

model_id = model_id

_model instance-attribute

_model = model

context_ instance-attribute

context_ = None

context_exog_ instance-attribute

context_exog_ = None

context_length instance-attribute

context_length = context_length

point_estimate instance-attribute

point_estimate = point_estimate

tabicl_config instance-attribute

tabicl_config = dict(tabicl_config) if tabicl_config else {}

temporal_features instance-attribute

temporal_features = temporal_features

is_fitted instance-attribute

is_fitted = False

Functions

get_params

get_params()

Return the adapter's constructor parameters.

Returns:

Name Type Description
params dict

Keys: model_id, context_length, point_estimate, tabicl_config, temporal_features. tabicl_config is returned as None when no additional config was set (i.e. when the internal dict is empty).

Source code in skforecast/foundation/_adapters.py
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
def get_params(self) -> dict:
    """
    Return the adapter's constructor parameters.

    Returns
    -------
    params : dict
        Keys: `model_id`, `context_length`, `point_estimate`,
        `tabicl_config`, `temporal_features`. `tabicl_config` is
        returned as `None` when no additional config was set (i.e.
        when the internal dict is empty).

    """
    return {
        "model_id":          self.model_id,
        "context_length":    self.context_length,
        "point_estimate":    self.point_estimate,
        "tabicl_config":     self.tabicl_config or None,
        "temporal_features": self.temporal_features,
    }

set_params

set_params(**params)

Set adapter parameters. Resets the model when any parameter changes, since the TabICLForecaster is instantiated lazily on the first predict call using the current adapter state.

Parameters:

Name Type Description Default
**params

Valid keys: model_id, context_length, point_estimate, tabicl_config, temporal_features.

{}

Returns:

Name Type Description
self TabICLAdapter
Source code in skforecast/foundation/_adapters.py
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
def set_params(self, **params) -> TabICLAdapter:
    """
    Set adapter parameters. Resets the model when any parameter changes,
    since the `TabICLForecaster` is instantiated lazily on the first
    `predict` call using the current adapter state.

    Parameters
    ----------
    **params :
        Valid keys: `model_id`, `context_length`, `point_estimate`,
        `tabicl_config`, `temporal_features`.

    Returns
    -------
    self : TabICLAdapter

    """

    valid = {
        "model_id", "context_length", "point_estimate",
        "tabicl_config", "temporal_features",
    }
    invalid = set(params) - valid
    if invalid:
        raise ValueError(
            f"Invalid parameter(s) for TabICLAdapter: {sorted(invalid)}. "
            f"Valid parameters are: {sorted(valid)}."
        )

    validated = {}
    for key, value in params.items():
        if key == "context_length":
            if not isinstance(value, int) or value < 1:
                raise ValueError(
                    f"`context_length` must be a positive integer. Got {value!r}."
                )
            validated[key] = value
        elif key == "point_estimate":
            if value not in ("mean", "median"):
                raise ValueError(
                    f"`point_estimate` must be 'mean' or 'median'. Got {value!r}."
                )
            validated[key] = value
        elif key == "tabicl_config":
            validated[key] = dict(value) if value else {}
        else:
            validated[key] = value

    actually_changed = {
        k: v for k, v in validated.items()
        if getattr(self, k) != v
    }
    if actually_changed:
        self._model = None
        for key, value in actually_changed.items():
            setattr(self, key, value)

    return self

fit

fit(context, context_exog)

Store the training series and optional historical exogenous variables. No model training occurs since TabICL is a zero-shot inference model.

All input normalization and validation is performed upstream by FoundationModel; this method receives canonical dicts only.

Parameters:

Name Type Description Default
context dict pandas Series

Normalized training series, one entry per series.

required
context_exog dict pandas DataFrame, pandas Series, or None

Per-series historical exogenous variables (past covariates).

required

Returns:

Name Type Description
self TabICLAdapter
Source code in skforecast/foundation/_adapters.py
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
def fit(
    self,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None] | None,
) -> TabICLAdapter:
    """
    Store the training series and optional historical exogenous variables.
    No model training occurs since TabICL is a zero-shot inference model.

    All input normalization and validation is performed upstream by
    `FoundationModel`; this method receives canonical dicts only.

    Parameters
    ----------
    context : dict pandas Series
        Normalized training series, one entry per series.
    context_exog : dict pandas DataFrame, pandas Series, or None
        Per-series historical exogenous variables (past covariates).

    Returns
    -------
    self : TabICLAdapter

    """

    self.context_      = context
    self.context_exog_ = context_exog
    self.is_fitted     = True

    return self

predict

predict(steps, context, context_exog, exog, quantiles)

Generate predictions using TabICL.

All input normalization, validation, and context trimming is performed upstream by FoundationModel; this method receives pre-processed dicts only.

Parameters:

Name Type Description Default
steps int

Number of steps ahead to forecast.

required
context dict pandas Series

Per-series context windows (already trimmed to context_length).

required
context_exog dict pandas DataFrame, pandas Series, or None

Per-series past covariates (already trimmed).

required
exog dict pandas DataFrame, pandas Series, or None

Per-series future covariates for the forecast horizon.

required
quantiles list of float or None

Quantile levels to return. If None, a point forecast is produced (shape (steps, 1)). Accepts any float in [0, 1].

required

Returns:

Name Type Description
predictions dict

Keys are series names. Each value is a 2-D numpy ndarray of shape (steps, n_quantiles).

Source code in skforecast/foundation/_adapters.py
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
def predict(
    self,
    steps: int,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | pd.Series | None] | None,
    exog: dict[str, pd.DataFrame | pd.Series | None] | None,
    quantiles: list[float] | tuple[float] | None,
) -> dict[str, np.ndarray]:
    """
    Generate predictions using TabICL.

    All input normalization, validation, and context trimming is
    performed upstream by `FoundationModel`; this method receives
    pre-processed dicts only.

    Parameters
    ----------
    steps : int
        Number of steps ahead to forecast.
    context : dict pandas Series
        Per-series context windows (already trimmed to
        `context_length`).
    context_exog : dict pandas DataFrame, pandas Series, or None
        Per-series past covariates (already trimmed).
    exog : dict pandas DataFrame, pandas Series, or None
        Per-series future covariates for the forecast horizon.
    quantiles : list of float or None
        Quantile levels to return. If `None`, a point forecast is
        produced (shape `(steps, 1)`). Accepts any float in `[0, 1]`.

    Returns
    -------
    predictions : dict
        Keys are series names. Each value is a 2-D numpy ndarray of
        shape `(steps, n_quantiles)`.

    """

    self._load_model()

    quantile_list = list(quantiles) if quantiles is not None else None
    tabicl_quantiles = (
        quantile_list
        if quantile_list is not None
        else [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
    )

    series_names_in = list(context.keys())

    first_series = next(iter(context.values()))
    is_datetime = isinstance(first_series.index, pd.DatetimeIndex)

    if not is_datetime:
        warnings.warn(
            "TabICLAdapter received series with a non-DatetimeIndex. "
            "TabICL requires datetime timestamps internally; a synthetic "
            "daily DatetimeIndex (starting 2000-01-01) will be used. "
            "Calendar-based temporal features (DatetimeEncoder, "
            "AutoPeriodicEncoder) will not be meaningful for "
            "integer-indexed data. Consider passing "
            "`temporal_features=[]` to disable calendar feature "
            "transforms.",
            # stacklevel=3: TabICLAdapter.predict → FoundationModel.predict → user
            stacklevel=3,
        )

    context_df = self._build_context_df(
                     series_names = series_names_in, 
                     context      = context, 
                     context_exog = context_exog, 
                     is_datetime  = is_datetime
                 )

    future_df = self._build_future_df(
                    series_names = series_names_in, 
                    context      = context, 
                    exog         = exog, 
                    steps        = steps, 
                    is_datetime  = is_datetime
                )

    result_df = self._model.predict_df(
                    context_df = context_df,
                    future_df  = future_df,
                    quantiles  = tabicl_quantiles,
                )

    # result_df is a plain DataFrame with MultiIndex (item_id, timestamp).
    # columns: "target" (str) and quantile levels as float column names.
    predictions: dict[str, np.ndarray] = {}
    for name in series_names_in:
        group = result_df.loc[name]  # DataFrame indexed by timestamp
        if quantile_list is None:
            predictions[name] = group["target"].to_numpy().reshape(-1, 1)
        else:
            predictions[name] = group[quantile_list].to_numpy()

    return predictions

_load_model

_load_model()

Load the TabICLForecaster into self._model if not already set.

Returns:

Type Description
None

Raises:

Type Description
ImportError

If tabicl[forecast] is not installed.

Notes

The model is imported lazily from tabicl and instantiated with the current adapter parameters. This method is a no-op when self._model is already populated (either by a prior call or by the model test-injection parameter).

Source code in skforecast/foundation/_adapters.py
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
def _load_model(self) -> None:
    """
    Load the `TabICLForecaster` into `self._model` if not already set.

    Returns
    -------
    None

    Raises
    ------
    ImportError
        If `tabicl[forecast]` is not installed.

    Notes
    -----
    The model is imported lazily from `tabicl` and instantiated with
    the current adapter parameters. This method is a no-op when
    `self._model` is already populated (either by a prior call or by
    the `model` test-injection parameter).
    """

    if self._model is not None:
        return
    try:
        from tabicl.forecast import TabICLForecaster
    except ImportError as exc:
        raise ImportError(
            "tabicl[forecast] is required for TabICLAdapter. "
            "Install it with `pip install tabicl[forecast]`."
        ) from exc

    self._model = TabICLForecaster(
                      max_context_length = self.context_length,
                      temporal_features  = self.temporal_features,
                      point_estimate     = self.point_estimate,
                      tabicl_config      = self.tabicl_config or {},
                  )

_get_timestamps

_get_timestamps(series, is_datetime)

Return datetime timestamps for a context series.

For DatetimeIndex series the original index is returned. For RangeIndex series a synthetic daily DatetimeIndex starting at 2000-01-01 is created so that TabICL's requirement for datetime timestamps is satisfied.

Parameters:

Name Type Description Default
series pandas Series

The context series.

required
is_datetime bool

Whether the series has a DatetimeIndex.

required

Returns:

Name Type Description
timestamps pandas DatetimeIndex

Datetime timestamps aligned with the series values.

Source code in skforecast/foundation/_adapters.py
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
def _get_timestamps(
    self, series: pd.Series, is_datetime: bool
) -> pd.DatetimeIndex:
    """
    Return datetime timestamps for a context series.

    For `DatetimeIndex` series the original index is returned. For
    `RangeIndex` series a synthetic daily `DatetimeIndex` starting at
    2000-01-01 is created so that TabICL's requirement for datetime
    timestamps is satisfied.

    Parameters
    ----------
    series : pandas Series
        The context series.
    is_datetime : bool
        Whether the series has a `DatetimeIndex`.

    Returns
    -------
    timestamps : pandas DatetimeIndex
        Datetime timestamps aligned with the series values.

    """

    if is_datetime:
        return series.index

    return pd.date_range("2000-01-01", periods=len(series), freq="D")

_get_future_timestamps

_get_future_timestamps(series, steps, is_datetime)

Return datetime timestamps for the forecast horizon.

For DatetimeIndex series the horizon is appended at the inferred frequency. For RangeIndex series the synthetic daily timeline (2000-01-01 + len(context) days) is extended by steps days.

Parameters:

Name Type Description Default
series pandas Series

The context series (used to determine the end timestamp and frequency).

required
steps int

Number of steps ahead.

required
is_datetime bool

Whether the series has a DatetimeIndex.

required

Returns:

Name Type Description
timestamps pandas DatetimeIndex

Datetime timestamps for the steps forecast steps.

Source code in skforecast/foundation/_adapters.py
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
def _get_future_timestamps(
    self, series: pd.Series, steps: int, is_datetime: bool
) -> pd.DatetimeIndex:
    """
    Return datetime timestamps for the forecast horizon.

    For `DatetimeIndex` series the horizon is appended at the inferred
    frequency. For `RangeIndex` series the synthetic daily timeline
    (2000-01-01 + len(context) days) is extended by `steps` days.

    Parameters
    ----------
    series : pandas Series
        The context series (used to determine the end timestamp and
        frequency).
    steps : int
        Number of steps ahead.
    is_datetime : bool
        Whether the series has a `DatetimeIndex`.

    Returns
    -------
    timestamps : pandas DatetimeIndex
        Datetime timestamps for the `steps` forecast steps.

    """

    if is_datetime:
        freq = series.index.freq
        if freq is None:
            freq = pd.tseries.frequencies.to_offset(
                pd.infer_freq(series.index)
            )
        timestamps = pd.date_range(
                         start   = series.index[-1] + freq,
                         periods = steps,
                         freq    = freq,
                     )
    else:
        n = len(series)
        timestamps = pd.date_range(
                         start   = pd.Timestamp("2000-01-01") + pd.Timedelta(days=n),
                         periods = steps,
                         freq    = "D",
                     )

    return timestamps

_build_context_df

_build_context_df(
    series_names, context, context_exog, is_datetime
)

Build a long-format context DataFrame expected by TabICL.

Each series' observations become rows with item_id, timestamp, target, and optional exogenous covariate columns.

Parameters:

Name Type Description Default
series_names list

Ordered list of series names.

required
context dict pandas Series

Per-series context windows.

required
context_exog dict or None

Per-series historical exogenous variables.

required
is_datetime bool

Whether the series have a DatetimeIndex.

required

Returns:

Name Type Description
context_df pandas DataFrame

Long-format DataFrame with columns item_id, timestamp, target, and any exogenous columns.

Source code in skforecast/foundation/_adapters.py
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
def _build_context_df(
    self,
    series_names: list,
    context: dict[str, pd.Series],
    context_exog: dict[str, pd.DataFrame | None] | None,
    is_datetime: bool,
) -> pd.DataFrame:
    """
    Build a long-format context DataFrame expected by TabICL.

    Each series' observations become rows with `item_id`, `timestamp`,
    `target`, and optional exogenous covariate columns.

    Parameters
    ----------
    series_names : list
        Ordered list of series names.
    context : dict pandas Series
        Per-series context windows.
    context_exog : dict or None
        Per-series historical exogenous variables.
    is_datetime : bool
        Whether the series have a `DatetimeIndex`.

    Returns
    -------
    context_df : pandas DataFrame
        Long-format DataFrame with columns `item_id`, `timestamp`,
        `target`, and any exogenous columns.

    """

    context_df = []
    for name in series_names:
        series = context[name]
        n = len(series)
        part = pd.DataFrame({
            "item_id":   np.full(n, name),
            "timestamp": np.asarray(self._get_timestamps(series, is_datetime)),
            "target":    series.to_numpy(dtype=float),
        })
        exog_entry = (
            context_exog.get(name) if context_exog is not None else None
        )
        if exog_entry is not None:
            part = pd.concat(
                [part, exog_entry.reset_index(drop=True)], axis=1
            )
        context_df.append(part)

    context_df = pd.concat(context_df, ignore_index=True)

    return context_df

_build_future_df

_build_future_df(
    series_names, context, exog, steps, is_datetime
)

Build a long-format future DataFrame expected by TabICL.

Each series' forecast horizon becomes rows with item_id, timestamp, and optional future exogenous covariate columns.

Parameters:

Name Type Description Default
series_names list

Ordered list of series names.

required
context dict pandas Series

Per-series context windows (used to derive future timestamps).

required
exog dict or None

Per-series future exogenous variables covering the forecast horizon.

required
steps int

Number of steps ahead.

required
is_datetime bool

Whether the series have a DatetimeIndex.

required

Returns:

Name Type Description
future_df pandas DataFrame

Long-format DataFrame with columns item_id, timestamp, and any future exogenous columns.

Source code in skforecast/foundation/_adapters.py
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
def _build_future_df(
    self,
    series_names: list,
    context: dict[str, pd.Series],
    exog: dict[str, pd.DataFrame | None] | None,
    steps: int,
    is_datetime: bool,
) -> pd.DataFrame:
    """
    Build a long-format future DataFrame expected by TabICL.

    Each series' forecast horizon becomes rows with `item_id`,
    `timestamp`, and optional future exogenous covariate columns.

    Parameters
    ----------
    series_names : list
        Ordered list of series names.
    context : dict pandas Series
        Per-series context windows (used to derive future timestamps).
    exog : dict or None
        Per-series future exogenous variables covering the forecast
        horizon.
    steps : int
        Number of steps ahead.
    is_datetime : bool
        Whether the series have a `DatetimeIndex`.

    Returns
    -------
    future_df : pandas DataFrame
        Long-format DataFrame with columns `item_id`, `timestamp`, and
        any future exogenous columns.

    """

    future_df = []
    for name in series_names:
        series = context[name]
        part = pd.DataFrame({
            "item_id":   np.full(steps, name),
            "timestamp": np.asarray(
                self._get_future_timestamps(series, steps, is_datetime)
            ),
        })
        future_exog = exog.get(name) if exog is not None else None
        if future_exog is not None:
            part = pd.concat(
                [part, future_exog.reset_index(drop=True)], axis=1
            )
        future_df.append(part)

    future_df = pd.concat(future_df, ignore_index=True)

    return future_df