Skip to main content
Twiga Forecast logo

Twiga Forecast

Point & probabilistic time series forecasting — one interface, every model.

"Twiga" means giraffe in Swahili 🦒

Python PyPI License Ruff uv

Documentation · Tutorials · API Reference · PyPI · Changelog


Most forecasting libraries force a choice — ML or deep learning, point forecasts or probabilistic ones, flexibility or production readiness. Twiga removes that trade-off.

A single TwigaForecaster trains, tunes, evaluates and backtests gradient-boosted trees, neural networks, quantile regression, parametric distributions and conformal prediction through one consistent, config-driven API. It was built for energy and power-system forecasting, where calibrated uncertainty matters as much as accuracy, and works on any time series.


Quick start

Install the core with the tree models, then run a complete forecast on a synthetic hourly load. Nothing else is needed: the data is generated in the snippet.

pip install "twiga[ml]"
import numpy as np
import pandas as pd

from twiga.core.config import DataPipelineConfig, ExperimentConfig
from twiga.forecaster.core import TwigaForecaster
from twiga.models.ml.lightgbm_model import LIGHTGBMConfig

# Twelve weeks of hourly load with a daily cycle, a weekend effect and noise.
timestamps = pd.date_range("2025-01-01", periods=24 * 7 * 12, freq="h")
generator = np.random.default_rng(0)
load = (
    50
    + 10 * np.sin(2 * np.pi * timestamps.hour / 24)
    + 4 * (timestamps.dayofweek >= 5)
    + generator.normal(0, 1.5, len(timestamps))
)
data = pd.DataFrame({"timestamp": timestamps, "load_mw": load})
train_df, test_df = data.iloc[: -24 * 7], data.iloc[-24 * 7 :]

data_params = DataPipelineConfig(target_feature="load_mw", period="1h", forecast_horizon=24, lookback_window_size=48)
cv_params = ExperimentConfig(split_freq="days", train_size=28, test_size=7)

forecaster = TwigaForecaster(data_params=data_params, model_params=[LIGHTGBMConfig()], cv_params=cv_params)
forecaster.fit(train_df=train_df)
predictions, metrics = forecaster.evaluate_point_forecast(test_df=test_df)

print(predictions.head())  # one row per forecast step: forecast and Actual
print(metrics.mean(numeric_only=True))  # mae, rmse, nrmse, ... averaged over the test days

A DataFrame needs a timestamp column and the target column; lookback_window_size and forecast_horizon are counted in steps of period.

The same data, a probabilistic forecast

Swap one config. Quantile regression returns a full predictive distribution and is scored with the pinball loss, calibration error and sharpness.

from twiga.models.ml.qrlightgbm_model import QRLIGHTGBMConfig

probabilistic = TwigaForecaster(data_params=data_params, model_params=[QRLIGHTGBMConfig()], cv_params=cv_params)
probabilistic.fit(train_df=train_df)
quantiles, scores = probabilistic.evaluate_quantile_forecast(test_df=test_df)
print(scores[["pinball", "calibration_error", "sharpness"]].mean())

Conformal prediction around any point model

Wrap a trained model with distribution-free intervals: calibrate on held-out data, then ask for intervals.

from twiga.core.config import ConformalConfig

conformal = TwigaForecaster(
    data_params=data_params,
    model_params=[LIGHTGBMConfig()],
    cv_params=cv_params,
    conformal_params=ConformalConfig(),
)
conformal.fit(train_df=train_df.iloc[: -24 * 7])
conformal.calibrate(calibrate_df=train_df.iloc[-24 * 14 :])
intervals, inference_time = conformal.predict_interval(test_df=test_df)
lower, forecast, upper = intervals["lightgbm"]  # each (forecasts, horizon, targets)

Neural networks use the same pattern: MLPGAMConfig() in place of LIGHTGBMConfig(), or MLPFConfig(distribution="normal") for a probabilistic head. See the tutorials for backtesting, hyper-parameter search, ensembles and MLOps.


What Twiga offers

Feature Description
🔀 One interface, every model Swap a gradient-boosted tree for a neural network by changing one config object, not rewriting code
📊 Probabilistic forecasting Quantile regression, parametric distributions and flexible quantile heads, composable with any backbone
🎯 Calibrated uncertainty Conformal prediction (CQR, CRC, multivariate) wraps a trained model with finite-sample coverage guarantees, no retraining required
⚙️ Experiment-ready Pydantic configs wired directly to Optuna search spaces; time-based backtesting, checkpoint-based resume and a rolling-origin experiment engine
📏 Proper evaluation Point, interval and quantile metrics: pinball, CRPS, Winkler, PICP, coverage-width efficiency, the weighted interval score and quantile-weighted CRPS
🔍 Feature intelligence Eight association measures fused with Borda-count rank aggregation; stationarity tests, entropy and residual diagnostics in one call
🚀 Production MLOps Optional stack with experiment tracking, versioned checkpoints, drift monitoring, a REST API and automated retraining

Models

Family Models
Baselines Naive, seasonal naive, drift, window average, context parrot
Tree and linear (ml) LightGBM, XGBoost, CatBoost, linear regression, random forest
Probabilistic trees (ml) Quantile LightGBM, XGBoost, CatBoost and random forest; Gaussian CatBoost; NGBoost (normal, log-normal, exponential)
Neural networks (nn) MLP forecaster (MLPF), generalised-additive MLP (MLPGAM), gated-attention-fusion MLP (MLPGAF), N-HiTS, RNN
Neural output heads Normal, Laplace, log-normal, Gamma, Beta, Cauchy, Student-t, Poisson, negative binomial, zero-inflated Poisson and negative binomial, quantile regression, fully parameterised quantile regression (FPQR), conformal (CRC), Monte-Carlo dropout and Bayesian
Foundation models (foundational) Wrappers for Chronos-2, TimesFM, Moirai, Lag-Llama and TabICL

Pick a head with the distribution field, for example MLPFConfig(distribution="fpqr"); the registry resolves it to the matching probabilistic model.

Training toolkit

Neural models train with AdamW by default and can switch, through the config, to Lion, SAM, a Muon and AdamW hybrid, or weight averaging (EMA and SWA): optimizer_type, lr_scheduler_type and weight_averaging on NeuralTrainingConfig.


Installation

# Core: forecaster, data pipeline, metrics, conformal, statistics,
# baseline, linear and random-forest models
pip install twiga

# + Tree-boosting and probabilistic ML models (XGBoost, LightGBM, CatBoost, NGBoost, quantile forest)
pip install "twiga[ml]"

# + Plotting (lets-plot, Great Tables, Matplotlib, Plotly)
pip install "twiga[plots]"

# + Neural networks (PyTorch Lightning)
pip install "twiga[nn]"

# Everything
pip install "twiga[all]"

Lean core — the base install covers the full forecasting workflow with baseline, linear and random-forest models. Tree-boosting models and plotting are opt-in extras (ml, plots).

Extra What it adds
ml XGBoost, LightGBM, CatBoost, NGBoost, quantile-forest, Optuna integration
plots lets-plot, Great Tables, Matplotlib, Plotly (publication-quality & interactive charts)
nn PyTorch, Lightning, TorchMetrics, TensorBoard, Optuna integration
foundational Chronos (and PyTorch) for the foundation-model wrappers
explain SHAP feature attribution
tracking TensorBoard
tuning Optuna dashboard
mlops MLflow, FastAPI, Evidently, Prefect, Streamlit
all ml, nn, foundational, tracking, tuning, mlops, explain and plots

On macOS, PyTorch, LightGBM and scikit-learn each ship their own OpenMP runtime and can crash when loaded together. Developers use make sync, which fixes this (see README_dev.md).

GPU (CUDA) support for neural networks

The default twiga[nn] install pulls the CPU-only PyTorch wheel from PyPI. To use a GPU, point your installer at the PyTorch CUDA index instead:

# pip
pip install "twiga[nn]" --extra-index-url https://download.pytorch.org/whl/cu124

# uv  (--index-strategy required so uv falls back to PyPI for non-torch packages)
uv pip install "twiga[nn]" \
  --extra-index-url https://download.pytorch.org/whl/cu124 \
  --index-strategy unsafe-best-match

Replace cu124 with the suffix that matches your driver:

CUDA version Suffix
11.8 cu118
12.1 cu121
12.4 cu124
12.6 cu126

Run nvidia-smi to check your CUDA version.


Documentation

Section Description
Get Started Install, key concepts, and your first forecast
User Guide Forecaster API, data pipeline, metrics, backtesting
Models ML tree models, neural networks, HPO
Probabilistic Distributions, quantile regression, conformal prediction
Tutorials End-to-end Jupyter notebooks
MLOps Tracking, serving, monitoring, orchestration
API Reference Full API reference

Contributing

Bug reports and feature requests are welcome — please open an issue.

git clone https://github.com/sambaiga/twiga-forecast && cd twiga-forecast
make sync-all                 # uv environment with every extra, plus the macOS OpenMP fix
make test                     # the full suite with its coverage gate
uv run pre-commit install --hook-type pre-commit --hook-type commit-msg --hook-type pre-push

Work on a branch and open a pull request against main. Commit messages and squash titles follow Conventional Commits (feat:, fix:, docs:, ...), because the changelog and the release notes are generated from them. The hooks run ruff, type checking and the other checks; see README_dev.md for the developer guide.


Contributors

Thanks goes to these wonderful people:

Anthony Faustine
Anthony Faustine
Frederick Apina
Frederick Apina
Lucas Pereira
Lucas Pereira

References

  1. A. Faustine, N. J. Nunes and L. Pereira, "Efficiency through Simplicity: MLP-based Approach for Net-Load Forecasting with Uncertainty Estimates," IEEE Transactions on Power Systems, doi: 10.1109/TPWRS.2024.3400123.
  2. A. Faustine and L. Pereira, "FPSeq2Q: Fully Parameterized Sequence to Quantile Regression for Net-Load Forecasting With Uncertainty Estimates," IEEE Transactions on Smart Grid, vol. 13, no. 3, pp. 2440-2451, May 2022, doi: 10.1109/TSG.2022.3148699.
  3. A. Faustine and L. Pereira, "Conformal Multilayer Perceptron-Based Probabilistic Net-Load Forecasting for Low-Voltage Distribution Systems with Photovoltaic Generation," 2024 IEEE International Conference on Communications, Control, and Computing Technologies for Smart Grids (SmartGridComm), Oslo, Norway, 2024, pp. 59-64, doi: 10.1109/SmartGridComm60555.2024.10738106.
  4. A. Faustine and L. Pereira, "Enhancing LV System Resilience through Probabilistic Forecasting of Interdependent Variables: Voltage, Reactive and Active Power," CIRED Chicago Workshop 2024: Resilience of Electric Distribution Systems, Chicago, USA, 2025, pp. 27-31, doi: 10.1049/icp.2024.2555.

Apache 2.0 License · Built with ❤️ for energy & power systems forecasting

Metadata

Release files for twiga 1.1.8

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for twiga 1.1.8
File Size Uploaded Provenance Actions
twiga-1.1.8.tar.gz 1.7 MB With provenance Details for twiga-1.1.8.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for twiga 1.1.8
File Interpreter ABI Platform Actions
twiga-1.1.8-py3-none-any.whl Python 3 none any Details for twiga-1.1.8-py3-none-any.whl

Total release size: 2.8 MB

Release files / twiga-1.1.8.tar.gz

Download URL twiga-1.1.8.tar.gz
Size 1.7 MB
Tags Source
SHA-256 checksum
How to use checksums
ae150b2caa0c8a9734517dca1986a62ca8c3878dfb0eb29881e007115f89b8e4
BLAKE2b-256 checksum
How to use checksums
8e4fd952b4cf845e05706314f29f327454a3514cf074a0f30b72eab1cd4c9b8f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Release files / twiga-1.1.8-py3-none-any.whl

Download URL twiga-1.1.8-py3-none-any.whl
Size 1.1 MB
Tags Python 3
SHA-256 checksum
How to use checksums
26bb23eb05167550b4d4f78e792bef617d7837abb78df2cd3dfd3f0095b0eb97
BLAKE2b-256 checksum
How to use checksums
62ade149a9715e61caedfb46f9587fedeba5ee5598b14f4b54d6cf5db25259db
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Security for twiga 1.1.8

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for twiga-1.1.8.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page