Skip to main content

capacities_ml_fin

capacities_ml_fin is a Python package for working with capacities, Choquet integrals, capacity-based machine-learning models, and non-additive risk measures.

Documentation · Source code

The package provides the complete workflow around these objects: defining and validating capacities, computing Choquet integrals, learning capacities from data, interpreting interactions, selecting model complexity, and applying capacities to financial loss distributions.

Main features

  • Explicit, k-additive, and Möbius capacity representations.
  • Discrete Choquet integrals for individual observations and batches.
  • Shapley values and interaction indices for capacity interpretation.
  • Scikit-learn-compatible regression and classification estimators.
  • Choquet autoregression implementing the native sktime forecasting interface.
  • Choquet neural regressors and classifiers.
  • Capacity preprocessing, regularization, and model-selection utilities.
  • SciPy, CVXPY, and PYMOO optimization backends.
  • Point-in-time financial data, return, feature, and portfolio utilities.
  • Distortion, spectral, and generalized risk measures.
  • Conditional and rolling risk forecasts with backtesting tools.

Installation

The project requires Python 3.12 or later. Install the package and its development environment from the repository root with Poetry:

poetry install

Commands can then be run inside the project environment:

poetry run python your_script.py
poetry run pytest

The local project can also be installed with pip:

pip install .

Once published, the distribution can be installed from PyPI with pip install capacities-ml-fin.

Capacities and Choquet integrals

A capacity assigns a value to each coalition of variables. Unlike a probability measure, it does not need to be additive, allowing the model to represent complementarity and redundancy between variables.

import numpy as np

from capacities_ml_fin.base.capacities import MobiusCapacity
from capacities_ml_fin.base.integrals.choquet import ordered_choquet

capacity = MobiusCapacity(
    coefficients={
        ("quality",): 0.35,
        ("cost",): 0.25,
        ("speed",): 0.20,
        ("quality", "speed"): 0.20,
    },
)

score = ordered_choquet(capacity, np.array([0.8, 0.4, 0.7]))
print(score)

ExplicitCapacity stores the complete capacity table, while MobiusCapacity supports a sparse, directly evaluable Möbius representation. Both implement the common BaseCapacity interface through event_value() and nested_event_values().

Machine-learning models

The supervised estimators follow the scikit-learn API and can be used with pipelines, cross-validation, metrics, and parameter search.

from sklearn.pipeline import Pipeline

from capacities_ml_fin.ml.models import ChoquetRegressor
from capacities_ml_fin.ml.optimization import KAdditivity
from capacities_ml_fin.ml.preprocessing import CapacityNormalizer

model = Pipeline(
    [
        ("normalize", CapacityNormalizer(cost_features=["volatility"])),
        (
            "model",
            ChoquetRegressor(
                sparsity=KAdditivity(order=2),
            ),
        ),
    ]
).set_output(transform="pandas")

model.fit(X_train, y_train)
predictions = model.predict(X_test)

Capacity objects infer names from named coalition keys. Supervised estimators infer them from DataFrame columns, or generate x0, x1, ... for array input. For an intentionally sparse capacity whose keys omit some variables, pass n_elements= or var_names= to state the otherwise unknowable elements.

The available estimators are:

  • ChoquetRegressor for continuous targets.
  • ScaledChoquetRegressor for continuous targets with a learned scale multiplying the Choquet integral.
  • ChoquetClassifier for deterministic threshold classification. It can learn non-negative feature scales jointly with the capacity and exposes margins through decision_function(); it intentionally has no predict_proba().
  • ChoquisticRegression for probabilistic binary classification.
  • ChoquetAutoRegressor for nonlinear autoregressive forecasting.
  • FuzzyChoquetInputLayer for a reusable supervised Choquet transformation.
  • FuzzyChoquetNeuralRegressor and FuzzyChoquetNeuralClassifier for conventional neural models fed by a supervised Choquet input layer.
  • FuzzyChoquetNeuralAutoRegressor for paper-style fuzzy neural forecasting with chronological selection from 2 to 8 lags by default.

Predictors should normally be oriented and normalized before fitting. The CapacityNormalizer scales inputs and reverses cost criteria so that larger transformed values always have the same interpretation.

Capacity complexity can be controlled with full, k-additive, or selected-pair representations. L1 and L2 penalties are available, and the model-selection module provides grids that can be passed directly to scikit-learn search objects.

Aggregate predictions from several models

The aggregation API learns a capacity whose elements are source models and whose inputs are their predictions. Regression uses the Choquet integral directly, while binary classification combines positive-class probabilities through a Choquistic link.

import pandas as pd

from capacities_ml_fin import aggregate_regression_predictions
from capacities_ml_fin.base.interpretation import (
    pairwise_interactions,
    shapley_indices,
)
from capacities_ml_fin.ml.optimization import KAdditivity

fit_predictions = pd.DataFrame(
    {"ridge": ridge_oof, "forest": forest_oof, "boosting": boosting_oof}
)
test_predictions = pd.DataFrame(
    {"ridge": ridge_test, "forest": forest_test, "boosting": boosting_test}
)

result = aggregate_regression_predictions(
    fit_predictions,
    y_fit,
    test_predictions,
    sparsity=KAdditivity(order=2),
)

final_predictions = result.predictions
model_importance = shapley_indices(result.capacity)
model_interactions = pairwise_interactions(result.capacity)

Use aggregate_binary_probabilities(...) for shared-capacity, class-wise binary positive-class probabilities. DataFrame columns become model names in the learned capacity, so Shapley values and pairwise interactions directly describe importance, complementarity, and redundancy between models. Fit the aggregator on honest out-of-fold or validation predictions rather than in-sample source predictions.

Time-series models

ChoquetAutoRegressor aggregates lagged observations through a learned capacity and subclasses sktime.forecasting.base.BaseForecaster. It can therefore be used with sktime forecasting horizons, temporal pipelines, splitters, metrics, tuning, exogenous variables, prediction intervals, and update workflows.

from sktime.forecasting.base import ForecastingHorizon
from sktime.forecasting.compose import TransformedTargetForecaster

from capacities_ml_fin.ml.models import ChoquetAutoRegressor

fh = ForecastingHorizon(y_test.index, is_relative=False)
model = TransformedTargetForecaster(
    [("forecast", ChoquetAutoRegressor(lags=5))]
)
model.fit(y_train, X=X_train, fh=fh)
forecast = model.predict(X=X_test)
intervals = model.predict_interval(X=X_test, coverage=0.95)
model.update(y_new, X=X_new)

The model exposes one-step training fitted values, residuals, AIC, BIC, and a stationary contraction constraint. Input y should use a supported pandas time index; when exogenous data are used, X must be indexed at the same dates and must cover every recursive future step.

FuzzyChoquetNeuralAutoRegressor provides the paper-style alternative. It normalizes lag windows, learns a 2-additive fuzzy input, feeds it to a tanh network, and selects the best lag order chronologically:

from capacities_ml_fin import FuzzyChoquetNeuralAutoRegressor

fuzzy_forecaster = FuzzyChoquetNeuralAutoRegressor(
    lag_candidates=tuple(range(2, 9)),
    random_state=0,
).fit(y_train)

fuzzy_forecaster.best_lag_
fuzzy_forecaster.lag_scores_
fuzzy_forecast = fuzzy_forecaster.predict(fh=[1, 2, 3])

Risk measures

The risk module applies capacities to events in a finite loss distribution. Larger values must represent larger losses.

It includes empirical distributions, probability and distorted capacities, probability envelopes, VaR, Expected Shortfall, generalized quantiles, spectral measures, Kusuoka representations, conditional residual bootstrapping, rolling capital estimation, and statistical backtesting.

from capacities_ml_fin.risk import (
    ExpectedShortfallDistortion,
    RollingRiskEstimator,
    capital_backtest,
)

estimator = RollingRiskEstimator(
    ExpectedShortfallDistortion(alpha=0.95),
    window=256,
    min_periods=256,
).fit(losses)

capital = estimator.predict_in_sample()
diagnostics = capital_backtest(losses, capital)

Rolling forecasts use only information preceding each forecast date. Backtesting utilities summarize capital breaches and provide coverage, independence, stress, bootstrap, and HAC diagnostics.

Package structure

Folder Contents
base Capacity objects, Möbius transforms, Choquet integrals, validation, and interpretation
ml Models, preprocessing, model selection, regularization, and optimization
finance Point-in-time alignment, returns, market features, and portfolio utilities
risk Loss distributions, distortions, risk measures, forecasting, and backtesting

These domains are part of the same capacities_ml_fin distribution and therefore share the same capacity abstractions and release version.

Notebooks

Guided examples are available in notebooks/:

  1. 01_capacities_and_choquet_integral.ipynb
  2. 02_choquet_regression.ipynb
  3. 03_choquet_classifier.ipynb
  4. 04_choquistic_regression.ipynb
  5. 05_optimization_backends.ipynb
  6. 06_risk_pipeline.ipynb

The notebooks cover the main modeling workflows, preprocessing, model selection, regularization, interpretation, evaluation metrics, optimization backends, and the complete risk pipeline.

Testing

Run the complete test suite with:

poetry run pytest

The tests are organized by package component and include capacities, integrals, estimators, optimization, preprocessing, interpretation, finance, and risk functionality.

Metadata

Release files for capacities-ml-fin 0.3.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 capacities-ml-fin 0.3.0
File Size Uploaded Provenance Actions
capacities_ml_fin-0.3.0.tar.gz 79.2 kB With provenance Details for capacities_ml_fin-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for capacities-ml-fin 0.3.0
File Interpreter ABI Platform Actions
capacities_ml_fin-0.3.0-py3-none-any.whl Python 3 none any Details for capacities_ml_fin-0.3.0-py3-none-any.whl

Total release size: 207.8 kB

Release files / capacities_ml_fin-0.3.0.tar.gz

Download URL capacities_ml_fin-0.3.0.tar.gz
Size 79.2 kB
Tags Source
SHA-256 checksum
How to use checksums
7de90229145a4bff46def540d1331507c868797a632d0af0f4bf75670180cf57
BLAKE2b-256 checksum
How to use checksums
c05b2b4a8e5054f352cdd0564af51c69854e63275bf4dbdf86456eb9748328b8
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 Aug 19, 2026.

Transparency log

Release files / capacities_ml_fin-0.3.0-py3-none-any.whl

Download URL capacities_ml_fin-0.3.0-py3-none-any.whl
Size 128.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
665c99286e5099ccb0c2d7f6cbf326cccd82036484fc2ed5b9b70d7a019e10de
BLAKE2b-256 checksum
How to use checksums
9f48b653e2e07544e41b7d3eef0cafda8283ca061c668ad86f65543c58bc7cd6
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 Aug 19, 2026.

Transparency log

Security for capacities-ml-fin 0.3.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.

Full provenance

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

Select from 2 files

Attestation for capacities_ml_fin-0.3.0.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 Aug 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