Skip to content

Data and preparation API

Azoic 0.8.0 documentation

This page describes Azoic 0.8.0. See the changelog for changes since 0.5.0.

Use these APIs to validate a Parquet data contract, review feature quality, learn inspectable mappings, and create leakage-safe split labels. The data profiling and preprocessing guide shows the task flow before the generated signatures below.

Module Public API Purpose
azoic.data DatasetSpec, load_data, split_portfolio Special-column contract; Parquet loading with contract validation
azoic.profile profile_features, screen_features Per-column screening stats; recommended keep/drop/group actions
azoic.preprocessing AutoBinner, AutoGrouper Inspectable numeric binning and categorical grouping transformers
azoic.validation make_strata, temporal_split Exposure-balanced stratum labels; leakage-safe temporal split

Dataset specifications and loaders.

pandas / pyarrow at boundaries. S3 paths work out of the box via fsspec when the optional aws extra is installed (uv sync --extra aws).

EXPOSURE_FLOOR = MIN_EXPOSURE * (1.0 - 0.001) module-attribute

Validation threshold: one day minus a 0.1% relative tolerance for day-count representations (freMTPL2 stores one-day policies ~163 ulps below 1/366).

MIN_EXPOSURE = 1.0 / 366.0 module-attribute

Minimum per-row exposure: one day in year fractions (leap-year denominator).

Sub-day rows are data errors for pure-premium modelling: a tiny exposure inflates claim_amount / exposure rates and destabilizes GLM fits.

DatasetSpec

Bases: BaseModel

Names of the special (non-feature) columns in a pricing dataset.

Feature columns exclude every declared column role, including id_col and excluded_cols (incumbent rates and partition metadata, for example). Exposure is always in years. Currency, observation period, claim valuation basis and upstream adjustments are descriptive evidence, not transformations. Unknown fields are rejected.

load_data(path, spec=None, **kwargs)

Read a Parquet dataset (local or s3://) into a pandas DataFrame.

When spec is given, required columns must be present or ValueError. Extra kwargs forward to pandas.read_parquet.

split_portfolio(df, final_test_ids, *, id_col)

Separate development and final-test copies by predeclared unique record IDs.

Returns (development, final_test) in source row order, preserving index labels. Save both portfolios and their ID lists before inspecting outcomes. Membership uses IDs only; no outcome validation, repair, caps or fitting is performed here. Unused categorical levels are removed within each partition. IDs must be nonmissing unique strings or integers. Both partitions must be nonempty and every requested final-test ID must exist.

Feature profiling and screening (actuary-in-the-loop, before modelling).

profile_features returns one row per column with the cheap stats needed for screening (missingness, cardinality, zero-variance, dtype, basic numerics). Per-level actuarial stats live on the binning/grouping transformers' mapping_, not here -- profiling is for the column-level keep/drop/review decision.

screen_features turns a profile into per-column actions: keep / bin (numeric high cardinality) / group (categorical high cardinality) / drop (zero variance or excessive missingness).

profile_features(df)

One row per column with screening-relevant stats.

screen_features(profile, *, max_groups=10, max_numeric_unique=20, missing_drop=0.5)

Per-column recommended action with a one-line reason.

Rules

zero_variance -> drop missing_rate > missing_drop -> drop numeric & n_unique > max_numeric_unique -> bin categorical & n_unique > max_groups -> group else -> keep

Auto-binning and auto-grouping transformers for tariff preprocessing.

numeric columns -> actuarially-credible interval bins

("tree" weighted LightGBM leaves, or "quantile" equal-exposure edges).

AutoGrouper: categorical columns -> credibility-stable level groups ("similarity" native LightGBM groups, or "rare" floor-based).

Both follow the scikit-learn transformer API and survive sklearn.utils.estimator_checks.parametrize_with_checks. Special columns (exposure, claim_count, target) travel inside X per AGENTS.md rule 8. mapping_ is overridable via set_mapping; transform honours the override.

AutoBinner

Bases: TransformerMixin, BaseEstimator

Bin numeric columns into actuarially-credible tariff bins.

Binned columns become ordered interval categoricals (DataFrame input) or integer bin codes (ndarray input). Non-target columns pass through unchanged. Learned tree edges include their upper boundary (<=); quantile and manual edges include their lower boundary. Tree NaNs follow the fitted missing route; quantile NaNs use a reserved "Missing" bin. Transform input must contain every fitted mapping column; arrays use x0, x1, etc. Unmatched column names raise ValueError.

Parameters

cols : list[str] | None Columns to bin. None -> all numeric columns found in fit. strategy : {"tree", "quantile"}, default="tree" "tree" = one exposure-weighted LightGBM regression tree on rates. Requires a target. "quantile" = weighted equal-frequency edges. max_bins : int Maximum number of bins per column (>=1). min_exposure : float | None Minimum total exposure per group. Tree sibling subtrees collapse below either floor; quantile bins merge with neighbours. Requires a real exposure_col column and must be >= 1/366 (one day); raises otherwise (a count-unit fallback would change units). min_claims : float | None Minimum aggregate claim count per bin; smaller bins merge into neighbours. exposure_col, claim_count_col, target_col : str | None Configured exposure and claim-count columns must exist at fit and contain finite values; exposures must be at least one day (1/366, with day-count tolerance), and claim counts must be non-negative. Without exposure_col, binning is unweighted. For tree binning, the target is target_col / exposure_col (pure premium) when both are set, else target_col, else y. Supplied outcomes must be finite after numeric and unit conversion; missing outcomes are never treated as zero. monotonic : False | True | "increasing" | "decreasing" When set, bin means are smoothed to be monotonic in the target via isotonic_regression and adjacent bins with the same smoothed mean merge. No-op without a target. False = off, True / "increasing" = non-decreasing bin means, "decreasing" = non-increasing. Native tree means include missing rows in their routed group. Pooling preserves floors. random_state : int | None Tree strategy seed, a non-negative 32-bit integer or None. fixed : mapping | None Per-feature {edges: [...], closure: 'left'|'right', missing: bin_index}. Fixed features do not learn edges or enforce learned credibility floors. Use an existing bin index or len(edges) + 1 for a separate Missing bin. Other selected features learn normally.

Attributes

mapping_ : dict[str, np.ndarray] Bin edges per binned column (length n_bins - 1). category_dtypes_ : dict[str, pd.CategoricalDtype] Stable ordered output vocabularies for DataFrame inputs. missing_ : dict[str, int] Fitted missing destination, as a zero-based bin index. closure_ : dict[str, str] "right" for native trees, "left" for quantile/manual edges. bin_cols_ : list[str] n_features_in_ : int feature_names_in_ : list[str] | None

set_mapping(mapping, *, missing=None)

Replace fitted bin mappings with finite, strictly increasing edge vectors.

Keys must name currently binned columns. Omitted columns pass through. Changed tree mappings require missing={column: bin_index}. An unchanged round-trip preserves native routing; manual edges are lower- inclusive. Manual decisions replace learned floor/monotonic guarantees. Invalid overrides leave the fitted mappings and vocabularies intact.

AutoGrouper

Bases: TransformerMixin, BaseEstimator

Group categorical levels into credibility-stable groups.

Strategies

"rare" Levels below min_exposure / min_claims -> other_label. min_exposure requires a real exposure_col column and must be >= 1/366 (one day). "similarity" One exposure-weighted LightGBM regression tree on rates. Nominal levels use native categorical splits, ordered levels use numeric codes to preserve contiguous groups. Sibling subtrees collapse when either credibility floor fails. If portfolio floors are impossible, one group remains.

mapping_ is {col: {original_level: group_label}}. Tree missing and unseen levels follow the fitted missing route; unseen levels warn. The rare strategy uses other_label. Output vocabularies are frozen during fit. Transform input must contain every fitted mapping column; arrays use x0, x1, etc. Unmatched column names raise ValueError.

Configured exposure and claim-count columns must exist at fit and contain finite values; exposures must be at least one day (1/366, with day-count tolerance), and claim counts must be non-negative. Without exposure_col, grouping uses unit row weights. When exposure is configured, target_col contains aggregate claims divided by exposure for tree training. Otherwise it contains rates. When absent, y supplies strictly one-dimensional rates. Supplied outcomes must be finite after numeric and unit conversion; missing outcomes are never treated as zero.

fixed accepts per-feature {groups: [{level: ..., group: ...}], missing: ..., unseen: ...}. Scalar category types are retained; missing/unseen destinations are explicit. Equal numeric/boolean aliases are rejected.

Attributes

mapping_, category_dtypes_, group_cols_, n_features_in_, feature_names_in_. missing_ : dict[str, object] Fitted group label used for missing and unseen levels. unseen_ : dict[str, object] Explicit unseen destinations for fixed mappings; otherwise uses missing_.

set_mapping(mapping, *, missing=None)

Replace fitted groups: {col: {level: group_label}}.

Keys must name currently grouped columns. Omitted columns pass through. Changed tree mappings require missing={column: group_label}, also used for unseen levels. An unchanged round-trip preserves native routing. Manual decisions replace learned credibility guarantees. Invalid overrides leave the fitted mappings and vocabularies intact.

Stratum labels for sklearn stratifiers and a tie-safe temporal holdout.

make_strata(y, sample_weight=None, *, n_strata=10)

Integer stratum labels for a continuous y, for sklearn's stratifiers.

sklearn's StratifiedKFold / StratifiedGroupKFold stratify on discrete classes; pure-premium / claim-count targets are continuous. Discretize into n_strata quantiles of y -- exposure-weighted when sample_weight is given (each fold then carries similar portfolio adequacy, the actuarial CV convention) -- and feed the codes back to the splitter as the stratification target. Missing values and their exposure do not affect weighted boundaries. Weights must be finite and non-negative; zero total observed weight assigns observed rows to group 0.

Returns

ndarray[int] Integer codes (-1 for NaN rows); distinct positive codes count <= n_strata when y has fewer unique values. The unweighted path inherits pandas qcut behaviour of skipping the indices of dropped duplicate edges, so the label set need not be 0..k-1 contiguous -- sklearn stratifiers only need distinct labels. Drop -1 rows or remap to 0 before passing to a splitter that rejects negative labels. Constant unweighted observations belong to group 0; missing rows still receive -1. Weighted tie semantics are unchanged.

temporal_split(df, time_col, *, test_size=None, cutoff=None)

Return positional (train_idx, test_idx) for a single temporal holdout.

Rows are sorted by time_col (ascending) regardless of input order, so the train block precedes the test block in time -- no leakage. Pass exactly one of:

test_size Fraction in (0, 1) or an int selects the latest rows for test. If the boundary falls inside a timestamp tie, the whole tied block goes to test. cutoff Timestamp / scalar comparable to df[time_col]. Rows with time <= cutoff go to train; time > cutoff go to test.

Returns

(ndarray[int], ndarray[int]) Positional row indices into the input df (use df.iloc[...]).

returns positional indices only -- a single holdout does not need

a sklearn splitter; for walk-forward OOT use TimeSeriesSplit.