Compatibility#

This page states what a release of kivi may change and what it keeps: the versions it supports, the public names, the layout of the tables it returns, its exception types and the files of BinningSpec and FeatureSpec. The rules that every function follows, such as the order of the arguments, are on Conventions, and they are part of the API too.

Releases and deprecations#

From version 1.0, kivi follows semantic versioning:

  • A major release, such as 2.0, may remove or change any part of the public API.

  • A minor release, such as 1.3, adds functions, arguments, table columns or format versions, and may deprecate a part of the API.

  • A patch release, such as 1.3.1, only fixes errors.

  • A deprecated function, argument or behavior keeps working, with a FutureWarning that says what to use instead, for the rest of the major version. It changes in the next major release, so a deprecation of 1.4 takes effect in 2.0. The release notes list each deprecation under Changed.

  • A fix of a wrong result can come in any release, minor or patch, even when code relies on the wrong result. The release notes list such fixes under Fixed.

Before 1.0 a shorter rule applied: what 0.9 deprecated changed in 1.0, as Migration guide lists. To find the calls that a release will change, run the code or its tests with FutureWarning turned into an error, as python -W error::FutureWarning or pytest -W error::FutureWarning do.

Supported versions#

kivi supports Python 3.10 or newer, NumPy 1.24 or newer and pandas 2.0 or newer, and its tests run on these oldest versions and on the newest releases. The charts of kivi.plotting also need matplotlib 3.7 or newer, which pip install "kivi[plot]" installs; no other module imports it. From 1.0, a minimum version rises only in a minor release, and the notes of the release before it announce the change. A patch release never raises a minimum.

What is public#

Results that are pairs of parameters, such as the (factor, offset) of score_scaling(), the (slope, intercept) of platt_fit(), the (edges, probability) of isotonic_fit(), the (statistic, p_value) of hosmer_lemeshow() and spiegelhalter_test() and the (probability, correlation) of vasicek_fit(), are tuples. A minor release may turn them into named tuples, which unpack in the same way.

Tables#

The index name, the column names and the order of the columns of every table are public. A minor release may append columns at the end of a table, but renames, reorders or removes a column only after a deprecation, so select columns by name rather than by position. The attrs of logistic_regression() and fractional_regression() are set on the returned frame, and pandas drops them in many operations.

Function

Index

Columns

window_features()

The index of observations, in its order

For each window in turn {prefix}events_{window}, then {prefix}{column}_{aggregation}_{window} column by column and aggregation by aggregation, and the ratios last, {numerator}_over_{window} or {numerator}_over_{denominator}

panel_features()

The index of observations, in its order

For each window in turn {prefix}months_{window}, {prefix}bad_months_{window}, {prefix}longest_bad_run_{window}, {prefix}longest_good_run_{window}, {prefix}worst_status_{window}, then {prefix}months_since_bad

FeatureSpec.compute

The index of observations, in its order

The columns of each group of events, then of each group of panel, as the two functions above give them, and the ratios last; FeatureSpec.columns lists them

woe_table(), BinningSpec.tables

bin

non_event, event, total, non_event_share, event_share, total_share, event_rate, woe, iv

woe() of Series counts

A Series named woe with the index of the counts

psi_table()

bin

reference, current, reference_share, current_share, psi

csi_table()

bin

reference, current, reference_share, current_share, points, csi

calibration_table()

bin

total, event, event_rate, mean_probability

backtest_table()

bin

total, estimated, realized, difference, variance, statistic, p_value

brier_decomposition()

A Series with the index statistic: brier, reliability, resolution, uncertainty, within_variance, within_covariance

concentration_test()

A Series with the index statistic: hi, cv, initial_hi, initial_cv, statistic, p_value

expected_loss_table()

bin

total, exposure, exposure_weighted_probability, expected_loss, expected_loss_rate

gains_table()

bin, the score bands as intervals

non_event, event, total, event_rate, lift, cum_non_event_share, cum_event_share, cum_total_share, ks, cum_lift

roc_table()

threshold

cum_non_event, cum_event, false_positive_rate, true_positive_rate, precision

roc_auc_interval()

statistic: auc and gini

estimate, se, lower, upper

delong_test()

A Series with the index current_auc, new_auc, difference, se, lower, upper, z, p_value

generalized_auc()

statistic: gauc and somers_d

estimate, se, lower, upper

profile_table()

variable

kind, count, missing, missing_share, distinct, top, top_share, special, special_share, mean, std, min, q01, q50, q99, max, with a target event_rate, missing_event_rate, non_missing_event_rate, missing_lift, non_missing_lift, iv, tied_bins, gini, then skewness, kurtosis, cv, and with a target ks, chi2_p_value

logistic_regression(), fractional_regression()

variable: intercept, then the columns of X

coef, se, z, p_value

vif()

A Series named vif with the index variable

correlation_filter(), vif_filter()

A pandas.Index of the kept columns of X, in their order, or of their positions when X is not a DataFrame

selection_path()

step: 1 to the number of variables in order

variable, auc, gini, ks, max_p_value, min_coefficient, and with validation validation_auc, validation_gini, validation_ks

points_table()

variable

bin, woe, points

woe_to_points()

The index of woe

One column per variable of coefficients, with the name of its index

reason_codes()

The index of points

reason_1 to reason_<top>

ahp_weights()

A Series named weight with the index factor

ahp_consistency()

A Series with the index statistic: lambda_max, ci, ri, cr

combine_weights()

A Series named weight with the index factor, sub_factor

master_scale()

grade

lower, probability, upper

cutoff_table()

cutoff

approved, approval_rate, approved_event, approved_event_rate, rejected_event_share, rejected_non_event_share, and with loss approved_loss

confusion_table()

cutoff

true_positive, false_positive, true_negative, false_negative, precision, recall, f1, accuracy

swap_set()

current and new, four rows

total, share, and with a target known, event, event_rate

fuzzy_augmentation()

The index of probability, each reject twice

target, weight

parceling()

The index of reject_score, each reject twice with expected=True

target, weight

reweighting()

A Series named weight with the index of score

monitoring_table()

period

total, known, event, event_rate, auc, gini, ks, psi

stability_table()

period

One per column of groups, in columns named variable

workout_lgd()

loan: the values of loan, in their order

ead, recovery, cost, lgd

lgd_table()

bin

total, total_share, mean, std, min, max, zero_share, full_share

most_prudent_pd()

A Series named most_prudent_pd with the index of a Series event or total, an array otherwise

delinquency_panel()

A range, one row per loan and month

loan_id, cohort, month, month_on_book, days_past_due, overdue_amount, outstanding, with principal balance, and status

vintage_table()

cohort

One per month on book, in columns named month_on_book

transition_matrix()

before

One per state, in columns named after

roll_rates()

A Series named roll_rate with the index before

migration_bandwidth()

A Series with the index statistic: upper, lower

migration_test()

before and after, one row per off-diagonal cell of grades

total, share, statistic, p_value

transition_pd()

state

One per horizon, in columns named horizon

survival_table()

period: 1 to the largest duration

at_risk, event, competing (only with competing), censored, hazard, survival, cumulative_pd

stage_table()

stage: 1, 2 and 3

total, exposure, exposure_share, expected_credit_loss, coverage

make_loan_panel()

A range

loan_id, cohort, month, month_on_book, term, amount, balance, status

make_applications()

A range

age, income, debt_to_income, inquiries, housing, employment, incumbent_pd, policy_decline, approved, target, and with include_risk=True risk

make_transactions()

A range, sorted by applicant and time

applicant_id, timestamp, amount, kind, merchant_category

make_defaults()

A range, sorted by default date

loan_id, segment, default_date, ead, limit, drawn, collateral_value, discount_rate, closing_date

make_recoveries()

A range, in the order of the loans of defaults, then by date

loan_id, date, amount, kind

load_bank()

A range

The 16 columns of the UCI data and target

The feature names follow from the arguments. Column names and prefixes are kept as given, and kivi’s own parts of the names, the aggregations, the windows and the names of the panel features, are in lower case, with windows written as 3m, 90d or 6m_3m. The dtypes are public too: the events, count and nunique features and the counts of panel_features() are int64, worst_status has the dtype of the status column, and the other features are float64. A window without values gives 0 for these counts and for sum, a missing status for worst_status, and NaN for the other features.

load_bank() always returns the same data. make_loan_panel(), make_applications(), make_transactions(), make_defaults() and make_recoveries() keep their columns and dtypes, including the categories of kind, merchant_category and segment, but the values that they simulate for a given rng stay the same only within a minor version, so that a minor release can improve the simulation.

woe_trend() returns one of six labels, "increasing", "decreasing", "u_shaped", "inverted_u", "irregular" and "flat", which are public like column names, and so is its rule that neighbouring bins whose WOE differ by at most a relative \(10^{-10}\) neither rise nor fall.

The random indices of ahp_consistency(), the table of Tone (1986) for 3 to 15 factors, are constants. A release changes them only to correct a wrong value, as a fix that the release notes list under Fixed, so the consistency ratio of a matrix stays the same from release to release.

Charts#

The functions of kivi.plotting keep the data that they draw from each table, which column goes on which axis, their arguments, the errors they raise and what they return: every function returns the matplotlib.axes.Axes it drew on, except woe_chart(), the one chart with two y-axes, which returns the pair of Axes of its bars and its line. distribution_chart() draws the shares of the raw non_event and event counts, not the smoothed share columns of a WOE table, and precision_recall_chart() draws the rows of a ROC table that have a precision and a line at the precision of its last row, the event rate. Colors, line styles, figure sizes, the placement of legends and annotations, tick formats and the number of matplotlib artists that make up a chart may change in any release, so that a release can improve how the charts look. Code that styles a chart further should work on the returned Axes rather than on the artists inside it.

Errors and warnings#

  • The exception types are public. Invalid input raises ValueError, and a model that cannot be fitted raises SeparationError, a subclass of ValueError. A call that Python itself rejects, such as one with a missing or an unknown argument, raises TypeError.

  • The warning categories are public: a UserWarning means that a result differs from the request, a RuntimeWarning that a fit did not converge, and a FutureWarning that a part of the API is deprecated.

  • The wording of a message is not public and may change in any release. The rule that a message names the argument and the value received stays.

Saved specifications#

BinningSpec.to_json and FeatureSpec.to_json write files that later releases read; Binning specifications and Time-window features describe their formats.

  • format is always "kivi.BinningSpec" or "kivi.FeatureSpec", and format_version is an integer. A binning specification has version 1 without category groupings and 2 when it groups a column. A feature specification has version 1, the format of kivi 1.3.0, whose keys after kivi_version are the arguments of FeatureSpec as it takes them: id, observation_time, events, ratios and panel, with every key of each group.

  • Every 1.x release reads every format version of a binning specification written by kivi 0.6.0 or later, and of a feature specification written by kivi 1.3.0 or later.

  • A specification is written in the lowest format version that can hold it, so a file that uses no newer feature stays readable by older releases. A new format version only adds content, and within a major version the meaning of an existing key never changes.

  • A file with a newer format version raises ValueError and names the version, instead of being read in part. Unknown keys raise as well, so a new key always comes with a new format version. A feature specification also raises for a missing key and for a key repeated within one JSON object.

  • kivi_version records the release that wrote the specification and never changes how a file is read. Equality and hashing include it, as they include every field, so a specification saved by an earlier release differs from the same fit today; Saving and loading a specification shows how to compare their content.

  • Encoding with a binning specification reads only the bin and woe of each table row. The other columns describe the fit and are loaded as written.

The tests of kivi keep binning specifications written by 0.6.0, in format version 1, and by 0.8.0, in format version 2, and check that each loads and encodes a fixed sample exactly as the release that wrote it did, and that it matches a fresh fit apart from kivi_version and the rounding of the last digits. They keep a feature specification of 1.3.0 in the same way, with window and panel groups and ratios, and check that it loads, writes the same JSON again and computes the same features of a fixed sample.