Skip to main content
kivi logo

kivi

Credit risk modeling with pandas

A toolkit for the whole scorecard project:
screen and bin the variables, fit and scale the model, calibrate it, price the cut-offs, monitor the model and provision for the loans it approves.

PyPI Downloads Documentation Python 3.10+ pandas 2.0+ Docs: English | 中文 License: MIT GitHub stars

English · 简体中文

Documentation · Quickstart · User guide · API · Release notes


✨ Highlights

  • 🏦 Built for risk teams. Covers a credit scorecard project end to end: variable profiles, classing, variable selection, reject inference, a logistic fit, scaling to points, evaluation, calibration on a master scale, cut-off strategy and expected loss, deployment and monitoring by period, plus vintage and roll-rate analysis of the approved loans and their IFRS 9 expected credit loss.
  • 📐 Fit once, reuse everywhere. Bin edges, category groupings, WOE tables, master scales and cut-offs are fitted on the development sample and applied unchanged to later samples. bin_edges learns quantile or uniform edges, chimerge_edges, tree_edges and monotonic_edges also use the target, and chimerge_groups merges categories with similar event rates. The outer edges are infinite, so every future value still lands in a bin.
  • 🔍 Transparent results. Tables return raw counts, smoothed shares and a contribution per bin, grade or cut-off, not just one number.
  • 📏 Uncertainty in view. roc_auc_interval gives the DeLong confidence interval of an AUC and a Gini, and delong_test tests whether two scores rank the same sample equally well.
  • 💾 Reproducible in production. fit_spec bins a whole data frame, and BinningSpec saves the edges and WOE tables as versioned JSON, so production groups new data exactly as development did.
  • 🧩 Nothing silently dropped. Missing values, special codes such as -1 and categories seen in only one sample get their own group, and a category that a fitted grouping or WOE table does not know raises an error unless you say where it belongs.
  • ⚖️ Sample weights throughout. Binning, WOE, PSI, the metrics, calibration, the model fits, the strategy tables, the monitoring report, vintage tables and the stage table take sample weights, and integer weights count like repeated rows: the same counts, rates and coefficients. Only quantile edges differ, because weighted quantiles do not interpolate.
  • 🧊 Honest smoothing. Empty cells are replaced by smoothing (default 0.5) before normalizing, and the reported counts are never altered.
  • 🐼 Just pandas and NumPy. No Spark, no database drivers and no global random state in the core.
  • 🌏 Bilingual, tested docs. Every example in the English and Chinese manuals runs in CI.
WOE chart for age
WOE chart: share of customers, event rate and WOE per bin.
Variables ranked by information value
Variable screening: IV ranking with the usual reading bands; duration is a leak.
PSI by month with thresholds
Monitoring: PSI per period against the development sample, with the 0.1 and 0.25 thresholds and sample sizes.
Event rate per score band and the gains curve
Gains: event rate and lift per score band, and the share of events captured.
Cumulative bad rate by month on book for several cohorts
Vintage curves: cumulative 90+ bad rate of each origination cohort.
Bad rate of the approved book against the approval rate for a current and a new score
Cut-off strategy: the bad rate of the approved book at each approval rate, for a current and a new score.
Inferred bad rate and refitted PD of the rejected applicants for several factors
Reject inference: the inferred bad rate and the refitted PD of the declined applicants for each factor.
Population, known outcomes, Gini and PSI of a score by month
Model monitoring: population, known outcomes, Gini and PSI of the score in every month.
Cumulative PD by month on book for each cohort and pooled
Lifetime PD: the cumulative PD of each cohort and the pooled term structure used for the expected credit loss.

🧭 How it works

Every step fits on the development sample and applies the result unchanged to later samples:

Step Modules Main functions
Profile the candidates kivi.univariate profile_table
Bin and encode kivi.binning, kivi.woe bin_edges, monotonic_edges, chimerge_groups, woe_table, woe_transform
Select and fit kivi.selection, kivi.reject_inference stepwise, logistic_regression, fuzzy_augmentation
Scale and evaluate kivi.scorecard, kivi.metrics points_table, roc_auc, roc_auc_interval, gains_table
Calibrate kivi.calibration master_scale, assign_grades, jeffreys_test
Decide kivi.strategy cutoff_table, swap_set, expected_loss_table
Deploy and monitor kivi.spec, kivi.monitoring, kivi.stability fit_spec, monitoring_table, stability_table, csi_table
Follow the loans kivi.vintage, kivi.lifetime vintage_table, transition_pd, expected_credit_loss, assign_stages

Binning shows the pattern: fit the edges once, cut every sample with them, then measure.

Fit edges once with bin_edges, cut every sample with pandas.cut, then measure with woe_table and psi_table

📦 Installation

pip install kivi

Requires Python 3.10+, NumPy 1.24+ and pandas 2.0+. For the latest development version, use pip install "git+https://github.com/gchensy/kivi".

Upgrading from 0.2.x? The API changed in 0.3. Read the migration guide before upgrading existing code.

🚀 Quickstart

import pandas as pd
from kivi.binning import bin_edges
from kivi.datasets import load_bank
from kivi.stability import psi_table
from kivi.woe import woe_table

data = load_bank()                              # 4,521 bank marketing customers
reference, current = data.iloc[:3000], data.iloc[3000:]

edges = bin_edges(reference["age"], bins=5)     # 1. fit once on the reference
before = pd.cut(reference["age"], edges)        # 2. cut every sample
after = pd.cut(current["age"], edges)

evidence = woe_table(before, reference["target"])  # 3. measure
stability = psi_table(before, after)

print(evidence[["event", "non_event", "woe", "iv"]].round(3))
print(f"IV = {evidence['iv'].sum():.3f}, PSI = {stability['psi'].sum():.4f}")
              event  non_event    woe     iv
bin
(-inf, 32.0]     90        612  0.114  0.003
(32.0, 36.0]     55        475 -0.125  0.003
(36.0, 42.0]     58        529 -0.180  0.006
(42.0, 51.0]     71        569 -0.050  0.001
(51.0, inf]      74        467  0.189  0.007
IV = 0.019, PSI = 0.0024

Categorical columns skip the edges; pass their labels as they are, or group them first with category_groups or chimerge_groups:

jobs = woe_table(reference["job"], reference["target"])
print(f"IV(job) = {jobs['iv'].sum():.3f}")      # IV(job) = 0.137

🧰 API at a glance

Function What it does
kivi.univariate.profile_table One row per candidate: missing values, distribution, event rates, the IV of a quick binning and the Gini of numeric values
kivi.binning.bin_edges Fit quantile or uniform edges on a reference sample, with infinite outer edges
kivi.binning.cut Assign values to bins, with a separate group for each special value such as -1
kivi.binning.chimerge_edges Merge fine quantile bins with ChiMerge until neighbours differ significantly
kivi.binning.tree_edges Decision-tree splits by entropy or Gini, with a minimum share per bin
kivi.binning.monotonic_edges Merge fine quantile bins until the WOE is monotonic
kivi.binning.category_groups, kivi.binning.chimerge_groups, kivi.binning.group_categories Group the categories of a categorical variable: pool the rare ones or merge those with similar event rates, then apply the grouping to every sample
kivi.woe.woe_table Counts, shares, WOE and IV for every group
kivi.woe.woe_transform Replace each group with its development WOE, with an explicit policy for unseen groups
kivi.woe.woe, kivi.woe.iv, kivi.stability.psi WOE, IV and PSI from counts that are already aggregated
kivi.selection.correlation_filter, kivi.selection.vif Drop correlated variables by IV, and variance inflation factors
kivi.selection.logistic_regression, kivi.selection.stepwise NumPy logistic regression and stepwise selection that keeps every coefficient positive, with frequency weights
kivi.reject_inference.fuzzy_augmentation, kivi.reject_inference.parceling, kivi.reject_inference.reweighting Infer the outcomes of declined applicants, as weighted rows or as weights of the approved ones
kivi.scorecard.score_scaling, kivi.scorecard.pd_to_score, kivi.scorecard.score_to_pd PDO scaling factor and offset, and conversion between PD and score
kivi.scorecard.points_table, kivi.scorecard.woe_to_points, kivi.scorecard.reason_codes Points per group with PDO scaling, scores for new data, and reason codes
kivi.metrics.roc_auc, kivi.metrics.gini, kivi.metrics.ks, kivi.metrics.brier_score AUC, Gini, KS and Brier score of a score or PD against a binary target
kivi.metrics.gains_table Gains and lift by score band, with cumulative capture and KS
kivi.metrics.roc_table, kivi.metrics.roc_auc_interval, kivi.metrics.delong_test The ROC curve with one row per threshold, the DeLong confidence interval of an AUC and a Gini, and the DeLong test of two scores
kivi.calibration.master_scale, kivi.calibration.fit_grade_pd, kivi.calibration.assign_grades Build a master scale from the PD of each grade or fit it to default rates, and give each PD its grade
kivi.calibration.calibration_table, kivi.calibration.binomial_test, kivi.calibration.jeffreys_test, kivi.calibration.hosmer_lemeshow Event rate against predicted PD per grade, with binomial, Jeffreys and Hosmer-Lemeshow tests
kivi.calibration.prior_correction, kivi.calibration.corrected_intercept, kivi.calibration.herfindahl_index Correct PDs for an oversampled sample, and measure grade concentration
kivi.calibration.platt_fit, kivi.calibration.platt_predict, kivi.calibration.isotonic_fit, kivi.calibration.isotonic_predict Recalibrate a score to probabilities with Platt scaling or isotonic regression
kivi.strategy.cutoff_table, kivi.strategy.swap_set Approval and bad rates of each cut-off, and the swap set between a current and a new score
kivi.strategy.expected_loss, kivi.strategy.expected_loss_table Expected loss, PD × LGD × EAD, of each exposure and by grade
kivi.spec.fit_spec, kivi.spec.BinningSpec Bin and WOE-encode a whole data frame, and save the specification as versioned JSON
kivi.stability.psi_table Per-group PSI contributions between two samples
kivi.stability.csi_table Characteristic stability index: how much each variable's shift moves the average score
kivi.monitoring.monitoring_table, kivi.monitoring.stability_table One row per period with the population, the known outcomes, AUC, Gini, KS and the PSI of the score, and the PSI of every variable by period
kivi.vintage.vintage_table Cumulative bad rate of each origination cohort by month on book
kivi.vintage.transition_matrix, kivi.vintage.roll_rates Movements between delinquency buckets and the forward roll rate of each bucket
kivi.lifetime.convert_pd, kivi.lifetime.transition_pd Convert PD term structures between cumulative, marginal and conditional PDs, and project them from a transition matrix
kivi.lifetime.expected_credit_loss, kivi.lifetime.significant_increase, kivi.lifetime.assign_stages, kivi.lifetime.stage_table IFRS 9: 12-month and lifetime expected credit loss, significant increase in credit risk, stages 1 to 3 and the loss allowance by stage
kivi.datasets.load_bank, kivi.datasets.make_loan_panel, kivi.datasets.make_applications The bundled bank marketing data, and seeded synthetic loan panels and loan applications

📚 Documentation

English 中文
Quickstart Read 阅读
Risk modeling workflow Read 阅读
Univariate profile Read 阅读
Binning Read 阅读
WOE and IV Read 阅读
Variable selection Read 阅读
Reject inference Read 阅读
Scorecard Read 阅读
Model performance Read 阅读
Calibration Read 阅读
Credit strategy Read 阅读
Binning specifications Read 阅读
PSI Read 阅读
Model monitoring Read 阅读
Vintage and roll-rate analysis Read 阅读
Lifetime PD and expected credit loss Read 阅读
Example data Read 阅读
Conventions Read 阅读
Compatibility Read 阅读
Glossary Read 阅读
Migrating from 0.2.x Read 阅读

🗺️ Roadmap

  • ✅ Quantile and uniform binning, WOE, IV and PSI on a pandas core
  • ✅ English and Simplified Chinese documentation with tested examples
  • ✅ Special values such as -1 or -999 in their own bins
  • ✅ Charted risk examples: special values, coarse classing, IV screening, PSI monitoring
  • ✅ Supervised binning: ChiMerge, decision tree and monotonic WOE
  • ✅ WOE encoding of new data, with an explicit policy for unseen groups
  • ✅ Sample weights in binning, WOE and PSI
  • ✅ Scorecard workflow: variable selection, logistic regression, PDO scaling, reason codes, evaluation and calibration
  • ✅ CSI, vintage and roll-rate analysis, batch binning with saved specifications
  • ✅ Platt and isotonic calibration, and sample weights in the metrics
  • ✅ Credit strategy: cut-off tables, swap sets and expected loss
  • ✅ Reject inference with weighted model fits
  • ✅ Master scales and univariate variable profiles
  • ✅ Topic guides on one outline, a conventions page and a glossary
  • ✅ Categorical grouping, ROC tables and DeLong tests of the AUC
  • ✅ Model monitoring by period
  • ✅ Lifetime PD term structures, IFRS 9 expected credit loss and stage allocation
  • ✅ Type hints checked in CI, test coverage, and an API review: the 0.9 deprecations and the compatibility promise for 1.0
  • 🔜 1.0: semantic versioning, with the 0.9 deprecations removed

🤝 Contributing

git clone https://github.com/gchensy/kivi.git
cd kivi
python -m pip install -e '.[test,docs,lint]'              # the lint extra needs Python 3.11 or newer
pre-commit install                                        # ruff and mypy before every commit
python -m pytest --cov                                    # unit tests with branch coverage
python -m sphinx -W -b doctest docs docs/_build/doctest   # documentation examples
python docs/build.py                                      # English and Chinese HTML

After editing English pages or docstrings, run python docs/build.py --update-po and translate the new entries in docs/locale/zh_CN/LC_MESSAGES/kivi.po. See Writing documentation for the translation steps and the conventions of the pages, and the development guide for the checks that every pull request runs.

📄 License

The code is released under the MIT License. The bundled Bank Marketing data by S. Moro, P. Rita and P. Cortez (2014) is licensed under CC BY 4.0; see DATA-LICENSE.txt.

If kivi helps your models, a ⭐ helps others find it.

Metadata

Release files for kivi 0.9.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 kivi 0.9.0
File Size Uploaded Provenance Actions
kivi-0.9.0.tar.gz 890.6 kB With provenance Details for kivi-0.9.0.tar.gz

Built distribution (wheel)

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

Total release size: 1.1 MB

Release files / kivi-0.9.0.tar.gz

Download URL kivi-0.9.0.tar.gz
Size 890.6 kB
Tags Source
SHA-256 checksum
How to use checksums
27d0c972507e74c9e952a5573458a9cba4967788b16fc22fe0602a0788b4a6cc
BLAKE2b-256 checksum
How to use checksums
1122cfee4bde0a028bff503c8e0972031e2742f9b33b50c562472d5be5fe6a26
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 Nov 22, 2026.

Transparency log

Release files / kivi-0.9.0-py3-none-any.whl

Download URL kivi-0.9.0-py3-none-any.whl
Size 235.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d0b886c587f793e3b0939fffa5d016ddd4f5d52a1961ea7f81808cfb2e9d0893
BLAKE2b-256 checksum
How to use checksums
7a0d71370028beaf4231fd00ca75392ac96c4db433d9f2465045bcd5de8818fb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 Nov 22, 2026.

Transparency log

Security for kivi 0.9.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 kivi-0.9.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 Nov 22, 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