Skip to main content

Module for handling time series data and forecasting using Darts.

Project description



Sinapsis Darts Forecasting

Module for handling time series data and forecasting using Darts.

🐍 Installation 🚀 Features 📚 Usage Example 🌐 Webapp📙 Documentation 🔍 License

Sinapsis Darts Forecasting provides a powerful and flexible implementation for time series forecasting using the Darts library.

🐍 Installation

Install using your package manager of choice. We encourage the use of uv

Example with uv:

  uv pip install sinapsis-darts-forecasting --extra-index-url https://pypi.sinapsis.tech

or with raw pip:

  pip install sinapsis-darts-forecasting --extra-index-url https://pypi.sinapsis.tech

🚀 Features

Templates Supported

The Sinapsis Darts Forecasting provides a powerful and flexible implementation for time series forecasting using the Darts library.

TimeSeriesFromCSVLoader

Loads one or more columns from a CSV file directly into a TimeSeriesPacket using TimeSeries.from_csv(). Supports assigning the result to any packet attribute (content, past_covariates, future_covariates, predictions) and can either create a new packet or update an existing one in the container.

The following attributes apply to TimeSeriesFromCSVLoader:

  • root_dir (str | None, optional): Base directory prepended to path_to_csv. If omitted, path_to_csv is used as-is.
  • assign_to (Literal, required): The TimeSeriesPacket attribute where the loaded series is stored. One of "content", "past_covariates", "future_covariates", "predictions".
  • reuse_packet (bool, optional): If True, assigns the loaded series to the first existing TimeSeriesPacket in the container instead of creating a new one. Useful when loading multiple columns (e.g., target + covariates) into the same packet. Defaults to False.
  • loader_params (FromCSVKwargs, required): CSV-specific loading parameters:
    • path_to_csv (str): Filename or relative path to the CSV file.
    • time_col (str | None): Column name to use as the time index.
    • value_cols (str | list[str] | None): Column(s) to use as series values.
    • freq (str | None): Time series frequency (e.g., "D" for daily, "H" for hourly).
    • fill_missing_dates (bool): If True, inserts rows for missing timestamps. Defaults to False.
    • fillna_value (float | None): Fill value for any resulting NaNs after date insertion.
TimeSeriesFromDataframeLoader

Converts Pandas DataFrame objects already present in a TimeSeriesPacket into Darts TimeSeries instances using TimeSeries.from_dataframe(). Useful when upstream templates deliver DataFrames that need to be converted before forecasting.

The following attributes apply to TimeSeriesFromDataframeLoader:

  • apply_to (list[Literal], required): List of TimeSeriesPacket attributes to convert. Valid values: "content", "past_covariates", "future_covariates", "predictions".
  • from_pandas_kwargs (FromDataFrameKwargs, optional): Keyword arguments forwarded to TimeSeries.from_dataframe():
    • time_col (str | None): Column to use as the time index.
    • value_cols (str | list[str] | None): Column(s) to use as the series values.
    • freq (str | None): Time series frequency (e.g., "D", "H").
    • fill_missing_dates (bool): Insert rows for missing timestamps. Defaults to False.
    • fillna_value (float | None): Value used to fill NaNs introduced by date filling.
    • make_copy (bool): Whether to copy the underlying NumPy array. Defaults to True.
TimeSeriesFromSeriesLoader

Converts Pandas Series objects already present in a TimeSeriesPacket into Darts TimeSeries instances using TimeSeries.from_series(). The series index is automatically converted to timestamps via to_timestamp() before conversion.

The following attributes apply to TimeSeriesFromSeriesLoader:

  • apply_to (list[Literal], required): List of TimeSeriesPacket attributes to convert. Valid values: "content", "past_covariates", "future_covariates", "predictions".
  • from_pandas_kwargs (FromPandasBaseKwargs, optional): Keyword arguments forwarded to TimeSeries.from_series():
    • freq (str | None): Time series frequency (e.g., "D", "H").
    • fill_missing_dates (bool): Insert rows for missing timestamps. Defaults to False.
    • fillna_value (float | None): Value used to fill NaNs introduced by date filling.
    • make_copy (bool): Whether to copy the underlying NumPy array. Defaults to True.
Darts Transformers

Dynamic wrapper that exposes every transformer from darts.dataprocessing.transformers as an individual Sinapsis template (e.g., ScalerWrapper, MissingValuesFillerWrapper, BoxCoxWrapper). Transformations are applied to the selected TimeSeriesPacket attributes in-place.

For stateful transformers (e.g., Scaler), fitted parameters can be persisted in TimeSeriesPacket.generic_data and recovered automatically for inverse transforms — enabling clean scaler/unscaler pairs in a pipeline without manual state management.

The following attributes apply to all Darts Transformer templates:

  • apply_to (list[Literal], required): TimeSeriesPacket attributes to transform. Valid values: "content", "past_covariates", "future_covariates", "predictions".
  • method (Literal, required): Transformation method to call. One of "fit", "transform", "fit_transform", "inverse_transform".
  • transform_kwargs (dict[str, Any], optional): Extra keyword arguments forwarded to the chosen method (e.g., {"method": "linear"} for MissingValuesFiller). Defaults to {}.
  • params_key (str | None, optional): Key under which fitted parameters are stored in TimeSeriesPacket.generic_data. Required when pairing a fit_transform step with a later inverse_transform. Defaults to None (no storage).

Additional transformer-specific init arguments can be set via the *_init key (e.g., missingvaluesfiller_init, scaler_init). These are forwarded directly to the transformer constructor.

[!NOTE] For a full list of available transformers, see the Darts transformers documentation.

Darts Models

The following attribute apply only to templates from Darts Models:

  • forecast_horizon (int, optional): Number of future time steps the model should predict. Defaults to 10.
  • validation_mode (bool, optional): If True, the model is trained on all but the last forecast_horizon steps of the target series and predictions are generated for that held-out window, enabling metric evaluation. Defaults to False.

Additional model-specific attributes can be dynamically assigned through the class initialization dictionary (*_init attributes). These correspond directly to the constructor arguments of the chosen Darts model and are typically used for hyperparameter configuration.

[!NOTE] Not all Darts models support both past_covariates and future_covariates. Unsupported covariates are automatically ignored at runtime based on each model's supports_past_covariates / supports_future_covariates properties.

TimeSeriesVisualization

Generates per-packet visualizations of the historical target series alongside the model's predictions. For each TimeSeriesPacket that contains predictions, the template produces:

  • One Matplotlib PNG image per time series column, stored as ImagePacket objects in container.images.
  • One interactive Plotly HTML file per time series column, stored as FilePacket objects in container.files.

HTML files are named <html_figure_save_path>_<packet_id>_<column>.html so that multiple packets and multivariate series never overwrite each other.

The following attributes apply to TimeSeriesVisualization:

  • html_figure_save_path (str, optional): Base filename for the output HTML files. Defaults to "forecast_plot.html".
  • root_dir (str, optional): Root directory where HTML files are saved. Defaults to SINAPSIS_CACHE_DIR. Parent directories are created automatically if they do not exist.
  • plot_params (TimeSeriesPlotParams, optional): Nested model to customise the appearance of both Matplotlib and Plotly figures. Available sub-fields:
    • target_series_label (str): Legend label for the historical series. Defaults to "Historical".
    • predictions_label (str): Legend label for the predicted series. Defaults to "Predictions".
    • title (str): Figure title. Defaults to "Time Series Forecast Results".
    • x_axis_title (str): X-axis label. Defaults to "Time".
    • low_quantile (float): Lower quantile bound for probabilistic prediction intervals (Matplotlib only). Defaults to 0.05.
    • high_quantile (float): Upper quantile bound for probabilistic prediction intervals (Matplotlib only). Defaults to 0.95.
TimeSeriesMetrics

Dynamic wrapper that exposes every metric from darts.metrics as an individual Sinapsis template (e.g., maeTimeSeriesWrapper, mseTimeSeriesWrapper, rmseTimeSeriesWrapper). The selected metric is applied to the predictions and ground truth of each TimeSeriesPacket, and the result is stored in TimeSeriesPacket.generic_data keyed by the metric function name.

[!IMPORTANT] validation_mode: True must be set on the forecasting model template so that predictions cover the held-out tail of the target series and can be correctly aligned with the ground truth for metric computation.

The following attributes apply to all metric templates. They are specified as a nested dictionary under the metric function name (e.g., mae: {}):

  • intersect (bool, optional): When True, only the overlapping time interval between ground truth and predictions is used. Defaults to True.
  • q (float | list[float] | None, optional): Quantile(s) to evaluate for probabilistic or quantile predictions. Defaults to None (median for stochastic predictions).
  • n_jobs (int, optional): Number of parallel jobs when evaluating over a sequence of series. Defaults to 1.
  • verbose (bool, optional): Whether to print progress. Defaults to False.

The following parameters are intentionally excluded and cannot be overridden via the template config (they are managed internally): actual_series, pred_series, component_reduction, series_reduction, time_reduction.

[!TIP] Use CLI command sinapsis info --all-template-names to show a list with all the available Template names installed with Sinapsis Darts Forecasting.

[!TIP] Use CLI command sinapsis info --example-template-config TEMPLATE_NAME to produce an example Agent config for the Template specified in TEMPLATE_NAME.

For example, for TimeSeriesFromDataframeLoader use sinapsis info --example-template-config TimeSeriesFromDataframeLoader to produce the following example config:

agent:
  name: my_test_agent
templates:
- template_name: InputTemplate
  class_name: InputTemplate
  attributes: {}
- template_name: TimeSeriesFromDataframeLoader
  class_name: TimeSeriesFromDataframeLoader
  template_input: InputTemplate
  attributes:
    apply_to: 'content'
    from_pandas_kwargs: {}

📚 Usage Example

Below is an example configuration for Sinapsis Darts Forecasting using an XGBoost model. This setup extracts pandas DataFrames from the time series packet attributes and converts them into TimeSeries objects, using the Date column as the time index. Missing dates are filled with a daily frequency, and any missing values are interpolated using a linear method. The model is then trained and used to generate predictions with a forecast horizon of 100 days, with several configurable hyperparameters.

Example config
agent:
  name: XGBLSTMForecastingAgent
  description: ''

templates:

- template_name: InputTemplate
  class_name: InputTemplate
  attributes: {}

- template_name: TimeSeriesFromDataframeLoader
  class_name: TimeSeriesFromDataframeLoader
  template_input: InputTemplate
  attributes:
    apply_to: ["content", "past_covariates", "future_covariates"]
    from_pandas_kwargs:
      time_col: "Date"
      fill_missing_dates: True
      freq: "D"

- template_name: MissingValuesFiller
  class_name: MissingValuesFillerWrapper
  template_input: TimeSeriesFromDataframeLoader
  attributes:
    method: "transform"
    missingvaluesfiller_init: {}
    apply_to: ["content", "past_covariates", "future_covariates"]
    transform_kwargs:
      method: "linear"

- template_name: TimeSeries
  class_name: XGBModelWrapper
  template_input: MissingValuesFiller
  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

This configuration defines an agent and a sequence of templates to handle the data and perform predictions.

[!IMPORTANT] Attributes specified under the *_init keys (e.g., missingvaluesfiller_init, xgbmodel_init) correspond directly to the Darts transformation or models parameters. Ensure that values are assigned correctly according to the official Darts documentation, as they affect the behavior and performance of the model or the data.

To run the config, use the CLI:

sinapsis run name_of_config.yml

🌐 Webapp

The webapp provides an intuitive interface for data loading, preprocessing, and forecasting. The webapp supports CSV file uploads, visualization of historical data, and forecasting.

[!NOTE] Kaggle offers a variety of datasets for forecasting. In this-link from Kaggle, you can find a Bitcoin historical dataset. You can download it to use it in the app. Past and future covariates datasets are optional for the analysis.

[!IMPORTANT] Note that if you use another dataset, you need to change the attributes of the TimeSeriesFromDataframeLoader

[!IMPORTANT] To run the app you first need to clone this repository:

git clone git@github.com:Sinapsis-ai/sinapsis-time-series-forecasting.git
cd sinapsis-time-series-forecasting

[!NOTE] If you'd like to enable external app sharing in Gradio, export GRADIO_SHARE_APP=True

🐳 Docker

IMPORTANT This docker image depends on the sinapsis-nvidia:base image. Please refer to the official sinapsis instructions to Build with Docker.

  1. Build the sinapsis-time-series-forecasting image:
docker compose -f docker/compose.yaml build
  1. Start the app container:
docker compose -f docker/compose_apps.yaml up sinapsis-darts-forecasting-gradio -d
  1. Check the status:
docker logs -f sinapsis-darts-forecasting-gradio
  1. The logs will display the URL to access the webapp, e.g.:

NOTE: The url can be different, check the output of logs

Running on local URL:  http://127.0.0.1:7860
  1. To stop the app:
docker compose -f docker/compose_apps.yaml down
💻 UV

To run the webapp using the uv package manager, please:

  1. Create the virtual environment and sync the dependencies:
uv sync --frozen
  1. Install the wheel:
uv pip install sinapsis-time-series[all] --extra-index-url https://pypi.sinapsis.tech
  1. Run the webapp:
uv run webapps/darts_time_series_gradio_app.py
  1. The terminal will display the URL to access the webapp, e.g.:

NOTE: The url can be different, check the output of the terminal

Running on local URL:  http://127.0.0.1:7860

📙 Documentation

Documentation for this and other sinapsis packages is available on the sinapsis website

Tutorials for different projects within sinapsis are available at sinapsis tutorials page

🔍 License

This project is licensed under the AGPLv3 license, which encourages open collaboration and sharing. For more details, please refer to the LICENSE file.

For commercial use, please refer to our official Sinapsis website for information on obtaining a commercial license.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sinapsis_darts_forecasting-0.1.14.tar.gz (37.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sinapsis_darts_forecasting-0.1.14-py3-none-any.whl (39.5 kB view details)

Uploaded Python 3

File details

Details for the file sinapsis_darts_forecasting-0.1.14.tar.gz.

File metadata

File hashes

Hashes for sinapsis_darts_forecasting-0.1.14.tar.gz
Algorithm Hash digest
SHA256 603276e9e0a6e4ea7a9d23c73801f7183941d13412c42a0981361cbd6b3a5e12
MD5 2abd93ef563bc88ce1a90321a83394b0
BLAKE2b-256 c4e8bef3288c96b651ee0cf882cb1b2b93dd791245a6dba8c4c02ae36385d8f0

See more details on using hashes here.

File details

Details for the file sinapsis_darts_forecasting-0.1.14-py3-none-any.whl.

File metadata

File hashes

Hashes for sinapsis_darts_forecasting-0.1.14-py3-none-any.whl
Algorithm Hash digest
SHA256 c9906a67dcaf3e3868f301aec5bc92a4b2822b4d284b6ce80974458855884568
MD5 18618429323a1bddb2a24e9bf0c7e069
BLAKE2b-256 4f4d718927bd09e0da1f3cb5ff8355b1a264e8aec76bc7c20a29429e74c340b4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page