Metadata-Version: 2.5
Name: twiga
Version: 1.1.7
Summary: Point and probabilistic time series forecasting — one interface, every model.
Project-URL: Homepage, https://github.com/sambaiga/twiga-forecast
Project-URL: Repository, https://github.com/sambaiga/twiga-forecast
Project-URL: Documentation, https://sambaiga.github.io/twiga-docs
Project-URL: Bug Tracker, https://github.com/sambaiga/twiga-forecast/issues
Project-URL: Changelog, https://github.com/sambaiga/twiga-forecast/blob/main/CHANGELOG.md
Author-email: sambaiga <sambaiga@gmail.com>, apina <fred.apina@gmail.com>
License: Apache-2.0
License-File: LICENSE
Keywords: forecasting,machine-learning,neural-networks,probabilistic,time-series
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: antropy>=0.2.2
Requires-Dist: astral>=3.2
Requires-Dist: hurst>=0.0.5
Requires-Dist: numpy>=2.5.3
Requires-Dist: optuna>=4.8.0
Requires-Dist: pandas>=3.0.6
Requires-Dist: pyarrow>=23.0.0
Requires-Dist: pydantic>=2.13.0
Requires-Dist: rich>=15.0.0
Requires-Dist: scikit-learn>=1.9.0
Requires-Dist: scipy>=1.14.0
Requires-Dist: statsmodels>=0.14.6
Requires-Dist: tqdm>=4.67.3
Provides-Extra: all
Requires-Dist: anyio>=4.0.0; extra == 'all'
Requires-Dist: apscheduler>=3.10.0; extra == 'all'
Requires-Dist: catboost>=1.2.10; extra == 'all'
Requires-Dist: chronos-forecasting>=0.2.0; extra == 'all'
Requires-Dist: evidently>=0.7.21; extra == 'all'
Requires-Dist: fastapi>=0.136.1; extra == 'all'
Requires-Dist: great-tables>=0.21.0; extra == 'all'
Requires-Dist: lets-plot>=4.10.1; extra == 'all'
Requires-Dist: lightgbm>=4.7.0; extra == 'all'
Requires-Dist: lightning>=2.6.6; extra == 'all'
Requires-Dist: matplotlib-inline>=0.2.1; extra == 'all'
Requires-Dist: matplotlib>=3.10.8; extra == 'all'
Requires-Dist: mlflow>=3.11.1; extra == 'all'
Requires-Dist: ngboost>=0.5.9; extra == 'all'
Requires-Dist: optuna-dashboard>=0.20.0; extra == 'all'
Requires-Dist: optuna-integration>=4.8.0; extra == 'all'
Requires-Dist: plotly>=5.24.1; extra == 'all'
Requires-Dist: prefect>=3.6.28; extra == 'all'
Requires-Dist: pydantic-settings>=2.14.0; extra == 'all'
Requires-Dist: quantile-forest>=1.4.1; extra == 'all'
Requires-Dist: shap>=0.46.0; extra == 'all'
Requires-Dist: streamlit>=1.58.0; extra == 'all'
Requires-Dist: tensorboard>=2.19.0; extra == 'all'
Requires-Dist: torch>=2.10.0; extra == 'all'
Requires-Dist: torch>=2.14.0; extra == 'all'
Requires-Dist: torchmetrics>=1.9.0; extra == 'all'
Requires-Dist: uvicorn[standard]>=0.34.0; extra == 'all'
Requires-Dist: xgboost>=3.2.0; extra == 'all'
Provides-Extra: dev
Requires-Dist: commitizen>=4.13.10; extra == 'dev'
Requires-Dist: ipykernel>=7.2.0; extra == 'dev'
Requires-Dist: ipython>=9.13.0; extra == 'dev'
Requires-Dist: ipywidgets>=8.1.8; extra == 'dev'
Requires-Dist: jupyter-cache>=1.0.0; extra == 'dev'
Requires-Dist: myst-nb>=1.0.0; extra == 'dev'
Requires-Dist: myst-parser>=5.0.0; extra == 'dev'
Requires-Dist: nbstripout>=0.9.1; extra == 'dev'
Requires-Dist: notebook>=7.5.5; extra == 'dev'
Requires-Dist: pre-commit>=4.5.1; extra == 'dev'
Requires-Dist: pydata-sphinx-theme>=0.17.0; extra == 'dev'
Requires-Dist: pytest-cov>=7.1.0; extra == 'dev'
Requires-Dist: pytest-mpl>=0.19.0; extra == 'dev'
Requires-Dist: pytest-xdist>=3.8.0; extra == 'dev'
Requires-Dist: pytest>=9.0.3; extra == 'dev'
Requires-Dist: ruff>=0.14.14; extra == 'dev'
Requires-Dist: sphinx-autobuild>=2025.8.25; extra == 'dev'
Requires-Dist: sphinx-autodoc-typehints>=3.10.1; extra == 'dev'
Requires-Dist: sphinx-copybutton>=0.5.2; extra == 'dev'
Requires-Dist: sphinx-design>=0.7.0; extra == 'dev'
Requires-Dist: sphinx-prompt>=1.10.2; extra == 'dev'
Requires-Dist: sphinx-tabs>=3.5.0; extra == 'dev'
Requires-Dist: sphinx-togglebutton>=0.4.5; extra == 'dev'
Requires-Dist: sphinx>=9.1.0; extra == 'dev'
Requires-Dist: sphinxcontrib-mermaid>=2.0.1; extra == 'dev'
Requires-Dist: ty>=0.0.28; extra == 'dev'
Provides-Extra: explain
Requires-Dist: shap>=0.46.0; extra == 'explain'
Provides-Extra: foundational
Requires-Dist: chronos-forecasting>=0.2.0; extra == 'foundational'
Requires-Dist: torch>=2.10.0; extra == 'foundational'
Provides-Extra: lightning
Requires-Dist: lightning>=2.6.6; extra == 'lightning'
Requires-Dist: optuna-integration>=4.8.0; extra == 'lightning'
Requires-Dist: tensorboard>=2.19.0; extra == 'lightning'
Requires-Dist: torch>=2.14.0; extra == 'lightning'
Requires-Dist: torchmetrics>=1.9.0; extra == 'lightning'
Provides-Extra: ml
Requires-Dist: catboost>=1.2.10; extra == 'ml'
Requires-Dist: lightgbm>=4.7.0; extra == 'ml'
Requires-Dist: ngboost>=0.5.9; extra == 'ml'
Requires-Dist: optuna-integration>=4.8.0; extra == 'ml'
Requires-Dist: quantile-forest>=1.4.1; extra == 'ml'
Requires-Dist: xgboost>=3.2.0; extra == 'ml'
Provides-Extra: mlops
Requires-Dist: anyio>=4.0.0; extra == 'mlops'
Requires-Dist: apscheduler>=3.10.0; extra == 'mlops'
Requires-Dist: evidently>=0.7.21; extra == 'mlops'
Requires-Dist: fastapi>=0.136.1; extra == 'mlops'
Requires-Dist: mlflow>=3.11.1; extra == 'mlops'
Requires-Dist: prefect>=3.6.28; extra == 'mlops'
Requires-Dist: pydantic-settings>=2.14.0; extra == 'mlops'
Requires-Dist: streamlit>=1.58.0; extra == 'mlops'
Requires-Dist: uvicorn[standard]>=0.34.0; extra == 'mlops'
Provides-Extra: nn
Requires-Dist: lightning>=2.6.6; extra == 'nn'
Requires-Dist: optuna-integration>=4.8.0; extra == 'nn'
Requires-Dist: tensorboard>=2.19.0; extra == 'nn'
Requires-Dist: torch>=2.14.0; extra == 'nn'
Requires-Dist: torchmetrics>=1.9.0; extra == 'nn'
Provides-Extra: plots
Requires-Dist: great-tables>=0.21.0; extra == 'plots'
Requires-Dist: lets-plot>=4.10.1; extra == 'plots'
Requires-Dist: matplotlib-inline>=0.2.1; extra == 'plots'
Requires-Dist: matplotlib>=3.10.8; extra == 'plots'
Requires-Dist: plotly>=5.24.1; extra == 'plots'
Provides-Extra: torch
Requires-Dist: lightning>=2.6.6; extra == 'torch'
Requires-Dist: optuna-integration>=4.8.0; extra == 'torch'
Requires-Dist: tensorboard>=2.19.0; extra == 'torch'
Requires-Dist: torch>=2.14.0; extra == 'torch'
Requires-Dist: torchmetrics>=1.9.0; extra == 'torch'
Provides-Extra: tracking
Requires-Dist: tensorboard>=2.19.0; extra == 'tracking'
Provides-Extra: tuning
Requires-Dist: optuna-dashboard>=0.20.0; extra == 'tuning'
Description-Content-Type: text/markdown

# Twiga Forecast

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

*"Twiga" means giraffe in Swahili 🦒*

[![Python](https://img.shields.io/badge/python-3.12|3.13-3776ab?style=flat-square&logo=python&logoColor=white)](https://www.python.org/downloads/)
[![PyPI](https://img.shields.io/pypi/v/twiga?style=flat-square&color=0f718e)](https://pypi.org/project/twiga/)
[![License](https://img.shields.io/badge/license-Apache--2.0-green?style=flat-square)](LICENSE)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json&style=flat-square)](https://github.com/astral-sh/ruff)
[![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json&style=flat-square)](https://github.com/astral-sh/uv)

[Documentation](https://sambaiga.github.io/twiga-docs) · [Tutorials](https://sambaiga.github.io/twiga-docs/tutorials/index.html) · [API Reference](https://sambaiga.github.io/twiga-docs/api/index.html) · [PyPI](https://pypi.org/project/twiga/) · [Changelog](CHANGELOG.md)

---

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.

```bash
pip install "twiga[ml]"
```

```python
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.

```python
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.

```python
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](https://sambaiga.github.io/twiga-docs/tutorials/index.html) 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

```bash
# 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](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:

```bash
# 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](https://sambaiga.github.io/twiga-docs/getting-started/index.html) | Install, key concepts, and your first forecast |
| [User Guide](https://sambaiga.github.io/twiga-docs/core/index.html) | Forecaster API, data pipeline, metrics, backtesting |
| [Models](https://sambaiga.github.io/twiga-docs/models/index.html) | ML tree models, neural networks, HPO |
| [Probabilistic](https://sambaiga.github.io/twiga-docs/probabilistic/index.html) | Distributions, quantile regression, conformal prediction |
| [Tutorials](https://sambaiga.github.io/twiga-docs/tutorials/index.html) | End-to-end Jupyter notebooks |
| [MLOps](https://sambaiga.github.io/twiga-docs/mlops/index.html) | Tracking, serving, monitoring, orchestration |
| [API Reference](https://sambaiga.github.io/twiga-docs/api/index.html) | Full API reference |

---

## Contributing

Bug reports and feature requests are welcome — please [open an issue](https://github.com/sambaiga/twiga-forecast/issues).

```bash
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](https://www.conventionalcommits.org/) (`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](README_dev.md) for the developer guide.

---

## Contributors

Thanks goes to these wonderful people:

<table>
  <tbody>
    <tr>
      <td align="center" valign="top" width="14.28%">
        <a href="https://github.com/sambaiga">
          <img src="https://avatars.githubusercontent.com/u/338440?v=4" width="100px;" alt="Anthony Faustine"/><br/>
          <sub><b>Anthony Faustine</b></sub>
        </a>
      </td>
      <td align="center" valign="top" width="14.28%">
        <a href="https://github.com/fred-apina">
          <img src="https://avatars.githubusercontent.com/u/39369908?v=4" width="100px;" alt="Frederick Apina"/><br/>
          <sub><b>Frederick Apina</b></sub>
        </a>
      </td>
      <td align="center" valign="top" width="14.28%">
        <a href="https://github.com/alspereira">
          <img src="https://avatars.githubusercontent.com/u/7491890?v=4" width="100px;" alt="Lucas Pereira"/><br/>
          <sub><b>Lucas Pereira</b></sub>
        </a>
      </td>
    </tr>
  </tbody>
</table>

---

## 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](https://ieeexplore.ieee.org/document/10529636).
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](https://ieeexplore.ieee.org/document/9701598).
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](https://ieeexplore.ieee.org/document/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](https://doi.org/10.1049/icp.2024.2555).

---

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