Skip to main content

Comforta

CI License: MIT Python 3.12+

Comforta is a conformal forecasting library for panels of time series. It makes point forecasts at many origins, reconciles them over a hierarchy, and calibrates bands and bounds from out-of-sample residuals.

Install

Install comforta from PyPI:

pip install comforta
# or
uv add comforta

The vendor model adapters need an extra: stats (statsforecast), ml (mlforecast), or neural (neuralforecast).

pip install "comforta[stats]"

Quick start

import numpy as np
import pandas as pd

from comforta import Absolute, BottomUp, Hierarchy, LeadTime, Panel, SeasonalNaive, Signed
from comforta import SplitQuantile, Step, replay, rolling_forecasts
from comforta.metrics import coverage

rng = np.random.default_rng(0)
series = np.array(["a", "b", "c"])
periods = pd.date_range("2024-01-01", periods=120, freq="D")
panel = Panel(series, periods, rng.poisson(5.0, (3, 120)), "D")
hierarchy = Hierarchy.from_attributes(
    series, pd.DataFrame({"group": ["x", "x", "y"]}, index=series)
)

origins = np.arange(60, 113)  # each origin is the index of the last observed period
run = rolling_forecasts(panel, hierarchy, SeasonalNaive(7), BottomUp(hierarchy), origins, 7)
actuals = hierarchy.aggregate(panel.values)

calibrator = SplitQuantile(0.9, window=28)
bands = replay(run, actuals, target=Step(), score=Absolute(), calibrator=calibrator)
bound = replay(run, actuals, target=LeadTime(7), score=Signed(), calibrator=calibrator)
print(coverage(bands.target, bands.lower, bands.upper))

Concepts

Shapes use these axes: B bottom series, T periods, N nodes with bottoms first, S forecast series (B for BottomUp, N otherwise), O origins, H forecast steps, and C target columns (H for Step, 1 for LeadTime).

Panel and Hierarchy go to the Forecaster, base forecasts to the Reconciler, points to the Calibrator, bounds to order_up_to and settle

Stage Names
Data Panel, Hierarchy, Covariate
Forecast Forecaster, Reconciler (BottomUp, Identity, WlsStruct), rolling_forecasts
Calibrate Target (Step, LeadTime), Score (Absolute, Signed), Loss (Miss), Calibrator (SplitQuantile, ACI, QuantileTracker, RiskControl), step, replay
Decide critical_ratio, order_up_to, settle
Measure comforta.metrics: coverage, width, interval score, pinball, cost

Two rules hold everywhere. A model reads only its window, so a later value cannot change a point unless a covariate declares it known ahead. A calibrator sees a score only once its target is known, and before the origin that knows it issues.

Architecture has the shapes and the modules.

Write a calibrator

A calibrator owns its target, a level or a loss, and is three functions of an explicit state. comforta.online handles the origins, the delays, and the indexing. A new method is one file in comforta/conformal/calibrators/ that imports only calibrators.base, calibrators.ranks, and conformal.losses. This is the whole of a quantile tracker:

import numpy as np

from comforta.conformal.calibrators.base import Calibrator


class Tracker(Calibrator):
    def __init__(self, level, lr):
        self.level = level
        self.lr = lr

    def initial_state(self, n_nodes, n_columns):
        return {"q": np.zeros((n_nodes, n_columns))}

    def update(self, state, feedback):
        q = state["q"].copy()
        for row, column in enumerate(feedback.column):  # one row = one origin, one column
            miss = feedback.scores[row] > feedback.issued[row]
            q[:, column] += self.lr * (miss - (1 - self.level))
        return {"q": q}

    def threshold(self, state):
        return state["q"].astype(np.float32)

Keep the state in numpy arrays. Then a product can save it after each origin with comforta.online.state.flatten and continue from it.

Models

Model Kind Install
comforta.forecast.models.naive.SeasonalNaive local core
comforta.forecast.models.statsforecast.StatsForecastModel local, any statsforecast.models model comforta[stats]
comforta.forecast.models.mlforecast.MLForecast global regressor with lags and covariates comforta[ml]
comforta.forecast.models.neuralforecast.NeuralForecast global network from neuralforecast.models comforta[neural]
from lightgbm import LGBMRegressor
from comforta import BottomUp, Covariate, rolling_forecasts
from comforta.forecast.models.mlforecast import MLForecast

model = MLForecast(
    LGBMRegressor(), lags=[7, 14, 28], features=["price"], fit_periods=365, lookback=84
)
price = Covariate(prices, known_ahead=True, aggregate="mean")  # [B, T + H]
run = rolling_forecasts(
    panel,
    hierarchy,
    model,
    BottomUp(hierarchy),
    origins,
    28,
    refit_every=7,
    covariates={"price": price},
)

Benchmarks

bench/ is a folder of scripts. They load benchmark data from a directory, run benchmark protocols, and compare calibrators. They import the installed comforta. Raw data is not in Git.

Script Content
vn2.py load(path): weekly VN2 sales with the out-of-stock mask, hierarchy, and starting stock. play(data, bounds): six orders up to the bounds, eight settled weeks, holding 0.2 and shortage 1.0
m5.py load(path): daily M5 sales and the 12-level hierarchy (42,840 nodes). prices(horizon): the sell price covariate
compare.py compare(forecasts, actuals, calibrators, target, score, level): one row of metrics per method, on the cells where each method was ready

vn2_conformal.py runs the whole VN2 path in about one second:

uv run python bench/vn2_conformal.py data/vn2

Documents

Development

uv sync --group dev
uv run pytest
uv run ruff check .
uv run ruff format --check .
uv run ty check src/
uv build --no-sources

See Contributing.

License

MIT

Metadata

Release files for comforta 0.1.0

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

Source distribution (sdist)

Source distribution for comforta 0.1.0
File Size Uploaded Provenance Actions
comforta-0.1.0.tar.gz 27.1 kB Without provenance Details for comforta-0.1.0.tar.gz

Built distribution (wheel)

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

Total release size: 68.6 kB

Release files / comforta-0.1.0.tar.gz

Download URL comforta-0.1.0.tar.gz
Size 27.1 kB
Tags Source
SHA-256 checksum
How to use checksums
0bb496200c5613ae688b8b6c375074e9fdb5e1968867e6f4733109ea7915c93a
BLAKE2b-256 checksum
How to use checksums
eefd800d0fad5bb5f3b088782c06ad6f3f3571c3245c74172b4a5ae5c0ec9ba1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.0 {"installer":{"name":"uv","version":"0.12.0","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / comforta-0.1.0-py3-none-any.whl

Download URL comforta-0.1.0-py3-none-any.whl
Size 41.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
941a57acac8c5de193d7d4e26947b405cfe6bca5591fcc6d161ec3d796c7be94
BLAKE2b-256 checksum
How to use checksums
e8a467d18090ac3ddf6905de35d08b7eb110e6d6c8a986b13bc1e227063f8d37
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.0 {"installer":{"name":"uv","version":"0.12.0","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for comforta 0.1.0

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

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