Docs /Templates/ sinapsis-darts-forecasting

CrostonWrapper

sinapsis-darts-forecastingDartsdartsdynamicforecastingmodels

Python template · sinapsis_darts_forecasting.templates.time_series_model

Overview

Base Template for Darts Time Series forecasting models.

Croston — inherited documentation

The base class for transferable future covariates "local" forecasting models, handling single uni- or multivariate target and optional future covariates time series. Additionally, at prediction time, it can be applied to new data unrelated to the original series used for fitting the model.

Transferable Future Covariates Local Forecasting Models (TFC-LFM) are models that can be trained on a single uni- or multivariate target and optional future covariates series. Additionally, at prediction time, it can be applied to new data unrelated to the original series used for fitting the model. Currently in Darts, all models in this category wrap to statsmodel models such as VARIMA. TFC-LFMs usually train on the entire target and future covariates series supplied when calling :func:`fit()` at once. They can also predict in one go with :func:`predict()` for any number of predictions `n` after the end of the training series. When using future covariates, the values for the future `n` prediction steps must be given in the covariate series.

All implementations must implement the :func:`_fit()` and :func:`_predict()` methods.Croston method as presented `in this paper <https://otexts.com/fpp3/counts.html>`__ and based on the `Statsforecasts package <https://github.com/Nixtla/statsforecast>`__.

We refer to the StatsForecast documentation of `CrostonClassic <https://nixtlaverse.nixtla.io/statsforecast/src/core/models.html#crostonclassic>`__, `CrostonOptimized <https://nixtlaverse.nixtla.io/statsforecast/src/core/models.html#crostonoptimized>`__, `CrostonSBA <https://nixtlaverse.nixtla.io/statsforecast/src/core/models.html#crostonsba>`__, and `Teunter-Syntetos-Babai <https://nixtlaverse.nixtla.io/statsforecast/src/core/models.html#tsb>`__.

In addition to univariate deterministic forecasting, it comes with additional support:

- **Future covariates:** Use exogenous features to potentially improve predictive accuracy. Darts adds support by first regressing the series against the future covariates using a :class:`~darts.models.forecasting.linear_regression_model.LinearRegressionModel` model and then running the StatsForecast model on the in-sample residuals from this original regression. This approach was inspired by `this post of Stephan Kolassa <https://stats.stackexchange.com/q/220885>`__.

- **Probabilstic / Conformal forecasting:** Probabilstic forecasting can be performed using conformal prediction. To activate it, simply set `prediction_intervals` at model creation. To generate probabilistic forecasts, you can set the following parameters when calling :meth:`~darts.models.forecasting.sf_model.StatsForecastModel.predict`:

- Forecast quantile values directly by setting `predict_likelihood_parameters=True`.

- Generate sampled forecasts from these quantiles by setting `num_samples >> 1`.

- **Transferable series forecasting:** Apply the fitted model to a new input `series` at prediction time. Darts adds support by first fitting a copy of the model on the new series, and then using that model to generate the corresponding forecast.

.. note:: Future covariates are not supported when the input series contain missing values.

.. note:: The first model call might take more time than all subsequent calls as the model relies on Numba and jit compilation.

Parameters ---------- version - "classic" corresponds to classic Croston. - "optimized" corresponds to optimized classic Croston, which searches for the optimal ``alpha`` smoothing parameter and can take longer to run. Otherwise, a fixed value of ``alpha=0.1`` is used. - "sba" corresponds to the adjustment of the Croston method known as the Syntetos-Boylan Approximation [1]_. - "tsb" corresponds to the adjustment of the Croston method proposed by Teunter, Syntetos and Babai [2]_. In this case, `alpha_d` and `alpha_p` must be set. alpha_d For the "tsb" version, the alpha smoothing parameter to apply on demand. alpha_p For the "tsb" version, the alpha smoothing parameter to apply on probability. add_encoders A large number of future covariates can be automatically generated with `add_encoders`. This can be done by adding multiple pre-defined index encoders and/or custom user-made functions that will be used as index encoders. Additionally, a transformer such as Darts' :class:`Scaler` can be added to transform the generated covariates. This happens all under one hood and only needs to be specified at model creation. Read :meth:`SequentialEncoder <darts.dataprocessing.encoders.SequentialEncoder>` to find out more about ``add_encoders``. Default: ``None``. An example showing some of ``add_encoders`` features:

.. highlight:: python .. code-block:: python

def encode_year(idx): return (idx.year - 1950) / 50

add_encoders={ 'cyclic': {'future': ['month']}, 'datetime_attribute': {'future': ['hour', 'dayofweek']}, 'position': {'future': ['relative']}, 'custom': {'future': [encode_year]}, 'transformer': Scaler(), 'tz': 'CET' } .. quantiles Optionally, produce quantile predictions at `quantiles` levels when performing probabilistic forecasting with `num_samples > 1` or `predict_likelihood_parameters=True`. random_state Controls the randomness for reproducible forecasting. kwargs Keyword arguments for ``statsforecasts.models.Croston*``.

References ---------- .. [1] Aris A. Syntetos and John E. Boylan. The accuracy of intermittent demand estimates. International Journal of Forecasting, 21(2):303 – 314, 2005. .. [2] Ruud H. Teunter, Aris A. Syntetos, and M. Zied Babai. Intermittent demand: Linking forecasting to inventory obsolescence. European Journal of Operational Research, 214(3):606 – 615, 2011.

Examples -------- >>> from darts.datasets import AirPassengersDataset >>> from darts.models import Croston >>> from darts.utils.timeseries_generation import datetime_attribute_timeseries >>> series = AirPassengersDataset().load() >>> # optionally, use some future covariates; e.g. the value of the month encoded as a sine and cosine series >>> future_cov = datetime_attribute_timeseries(series, "month", cyclic=True, add_length=6) >>> # define Croston parameters >>> model = Croston(version="optimized") >>> model.fit(series, future_covariates=future_cov) >>> pred = model.predict(6, future_covariates=future_cov) >>> print(pred.values()) [[419.84565922] [424.06484452] [440.05509455] [463.53183473] [488.20449148] [507.46204636]]

Capabilities

Capabilities: not set

Installation

Install the published package using pip or uv.

Terminalbash
pip install sinapsis-darts-forecasting==1.0.0
uv pip install sinapsis-darts-forecasting==1.0.0
uv add sinapsis-darts-forecasting==1.0.0

Configuration

Effective fields from the inspector schema, including nested Pydantic model fields.

metadata
sinapsis_core.template_base.base_models.TemplateMetadata | None
Optional
Default: null
croston_initRequired
BaseModel
Required
Default: null
validation_mode
bool
Optional
Default: false
forecast_horizon
int
Optional
Default: 10

Configuration example

Generated from documented defaults. Replace any placeholders and complete required nested settings before running.

yaml
templates:
  - template_name: "CrostonWrapper"
    class_name: "CrostonWrapper"
    attributes:
      croston_init: {}
      validation_mode: false
      forecast_horizon: 10
View original docstring example

The source example references XGBModelWrapper, not CrostonWrapper.

yaml
agent:
    name: my_test_agent
templates:
- template_name: InputTemplate
  class_name: InputTemplate
  attributes: {}
- template_name: XGBModelWrapper
  class_name: XGBModelWrapper
  template_input: InputTemplate
  attributes:
    forecast_horizon: 100
    xgbmodel_init:
        lags: 30
        lags_past_covariates: 30
        output_chunk_length: 100
        random_state: 42
        n_estimators: 200
        learning_rate: 0.1
        max_depth: 6
For a full list of options use the sinapsis cli: sinapsis info --all-template-names.
If you want to see all available models, please visit:
https://unit8co.github.io/darts/generated_api/darts.models.forecasting.html

Inheritance

Immediate parent: sinapsis_darts_forecasting.templates.time_series_model.TimeSeriesModel

Environment variables

Environment definitions belong to their canonical Python modules.

SINAPSIS_BUILD_DOCS · defined elsewhere