Release notes#
Unreleased#
Changes merged since the last release.
New#
kivi.strategy.cutoff_tabletakesrevenue, a non-negative revenue per observation such as the interest margin of a loan, and then adds the columnapproved_revenue, the revenue of the approved book, and withlossalsoprofit, the revenue minus the losses.table["profit"].idxmax()gives the most profitable of the cut-offs. Withoutrevenuethe table is unchanged.kivi.metrics.expected_maximum_profitgives the expected maximum profit (EMP) of a credit score of Verbraken, Bravo, Weber and Baesens (2014): the profit per applicant of the best cut-off, as a share of the loan amount, averaged over a loss of default that is 0 with the probabilityno_loss_share, total with the probabilityfull_loss_shareand evenly spread in between, together with the share of applicants that the best cut-off rejects. The defaults and the results are those of the R package EMP and the Python package empulse, andweightsare frequency weights.The new module
kivi.rulesmeasures the policy rules of a credit strategy, passed as a DataFrame with one column of booleans, or of 0 and 1, per rule.rule_tablegives the hits, the hit rate and the unique hits of each rule, those that no other rule of the set hits, and with a target the hits with a known outcome, the events, the event rate, the lift, the recall and the events among the unique hits.rule_set_tableapplies the rules in order, as a decision waterfall: each row gives the new hits of a rule and the events among them, and the book that the rules up to it leave approved, with the columns ofkivi.strategy.cutoff_table. Missing labels in the target are unknown outcomes, as inkivi.strategy.swap_set, a missing value in a rule raises, andweightsare frequency weights.The new guide to policy rules measures the two policy rules and two candidate rules of the simulated applications: their hits and event rates, the overlap matrix of the rules, a waterfall that reproduces the approval decisions with the score cut-off as its last rule, what the order of the rules changes, and what the outcomes of the approved applicants alone can and cannot show.
1.6.0 (2026-11-25)#
New#
The new module
kivi.lgdmeasures and models the loss given default and the credit conversion factor of defaulted loans.workout_lgddiscounts the recoveries and costs of each workout to the date of default at an annual rate, one for all loans or one per loan, with the days counted ACT/365, and gives the exposure, the present values of the recoveries and of the costs and the realized LGD of each loan, without clipping it to [0, 1]. Costs before the date of default are compounded to it, as paragraph 144 of the EBA’s guidelines on LGD estimation asks.kivi.lgd.conversion_factorgives the realized CCF of each credit line from the amount drawn at default and the limit and the amount drawn at a reference date, NaN for lines that were fully drawn or overdrawn at that date, andkivi.lgd.lgd_tablesummarizes realized LGDs by group: the number of defaults, the average, the standard deviation, the range and the shares of defaults without loss and with a total loss, after flooring negative LGDs at 0 as the regulations ask for long-run averages.kivi.lgd.fractional_regressionfits the fractional logit of Papke and Wooldridge to a response between 0 and 1, such as a realized LGD, and returns the coefficient table oflogistic_regressionwith robust (HC0) standard errors. A response of only 0 and 1 gives the coefficients oflogistic_regression.The new guide to LGD and EAD lists the rules of the Basel framework, the EBA and China’s 2023 capital rules for realized LGDs and CCFs side by side, with their paragraphs and articles: the discount rate, costs before default, drawings, write-offs, cures, open workouts, long-run averages, negative values, the LGD and EAD floors, the reference date, fully drawn lines and the CCFs of the foundation approach.
kivi.datasets.make_defaultssimulates defaulted loans for LGD and EAD models: secured loans, unsecured loans and revolving lines that defaulted from 2018 to 2024, with the exposure at default, the value of the collateral, the limit and drawn amount of the revolving lines 12 months before default, a discount rate fixed at the default date and the date the workout ended, missing for the workouts still open at the data cut-off of 30 June 2025.kivi.datasets.make_recoveriessimulates the cash flows of their workouts, one row per recovery, cost or cure, so that the realized LGDs are bimodal: close to 0 for most secured and cured loans and close to 1 for the other unsecured loans and revolving lines, with a few negative LGDs, a few LGDs above 1 and a few legal costs before default. The realized CCFs of the revolving lines mostly lie from 0 to 1. The samerngseed always gives the same loans and cash flows.
Changed#
The guide to LGD and EAD comes after the guide to calibration and before the credit strategy, whose expected loss takes the LGDs and EADs. The home page, the index of the user guide and both READMEs describe
kivi.lgdand the simulated defaults and recoveries, with charts of the realized LGDs by segment and of the mean LGD of secured loans by loan-to-value band.The conventions page describes the cash flows and the
rateofworkout_lgd, theresponseoffractional_regressionand how the functions ofkivi.lgdtreat dates, missing values, booleans and weights. The compatibility page lists the tables ofworkout_lgd,lgd_tableandfractional_regressionand the columns ofmake_defaultsandmake_recoveries, and the glossary defines the workout, the closed workout, the cure, the economic loss, the realized LGD, the long-run average LGD, the reference date of a CCF, the fractional logit and robust standard errors.
1.5.0 (2026-11-24)#
New#
The new module
kivi.capitalcomputes the regulatory capital of the internal ratings-based approach.asset_correlationandcapital_requirementevaluate the risk-weight functions of the Basel framework (CRE31) and of China’s capital rules of 2023 for corporate exposures, high-volatility commercial real estate, residential mortgages, qualifying revolving and other retail exposures, with the SME adjustment ofturnoverover aturnover_rangethat takes either jurisdiction’s bounds, the 1.25 multiplier offinancialinstitutions and the maturity adjustment. They reproduce the 152 risk weights of Annex 5 of Basel II.kivi.capital.conditional_pdgives the PD of the one-factor model of Vasicek in a scenario of the economy,systematic_factorthe factor that an observed default rate implies, andvasicek_fitestimates the long-run PD and the asset correlation from a series of default rates by the method of moments, which allows years without defaults.kivi.capital.most_prudent_pdgives the most prudent upper bounds of Pluto and Tasche for the PDs of a portfolio with few or no defaults, with independent or correlated defaults, and reproduces the tables of their paper.The new guide to regulatory capital lists the parameters of the Basel framework and of China’s rules side by side, with their paragraphs and articles: the SME range and unit, the financial-institution multiplier, the PD and LGD floors, the foundation LGDs, the maturity, the scope of the advanced approach and the output floor.
kivi.lifetime.survival_tableestimates a cumulative PD term structure from the duration of each loan until it defaults, leaves for another reason or is last observed. It gives the loans at risk, the defaults, the other exits and the censored loans of each period, the hazard rate, the probability of being still on book and the cumulative PD: the Kaplan–Meier estimate, or withcompeting, such as early repayments, the Aalen–Johansen estimate of the cumulative incidence of default, which does not overstate the PD as 1 − Kaplan–Meier does when repaid loans count as censored.entryhandles left truncation, such as a panel that starts after the loans were originated, andweightsare frequency weights. Itscumulative_pdconverts withconvert_pdlike a vintage curve.kivi.datasets.make_loan_paneltakesprepayment, the monthly probability that a current loan repays its whole balance early. A loan that repays early has a balance of 0 in that month and no rows after it, so the columns stay the same. The default, 0, gives the same panel as before for everyrng.The lifetime guide shows how to derive durations, defaults and repayments from a monthly loan panel, why the cumulative incidence and not 1 − Kaplan–Meier is the lifetime PD when loans repay early, how
entrycorrects for a panel that starts late, and a discrete-time hazard model fitted withlogistic_regressionon a person-period table.
Changed#
The guide to regulatory capital comes after the guide to model validation. The home page, the index of the user guide and both READMEs describe
kivi.capitalandsurvival_table, with charts of the risk weight of each asset class against the PD and of the cumulative PD with early repayments as a competing risk or as censored.The lifetime guide weights the expected credit loss over economic scenarios:
conditional_pdshifts the PDs of each delinquency state to an upside, a base case and a downturn, and the probability-weighted ECL comes out above that of the base case.The conventions page describes
asset_class, thelevelof the capital functions, andevent,durationandentryofsurvival_table. The compatibility page lists the table ofsurvival_table, the result ofmost_prudent_pdand the tuple ofvasicek_fit, and the glossary defines the IRB approach, the asset class and asset correlation, the capital requirement, the risk weight, the maturity and SME adjustments, HVCRE and QRRE, the one-factor model, the systematic factor, stressed and through-the-cycle PDs, most prudent estimates of low-default portfolios, the output floor, censoring, left truncation, the risk set, competing risks, early repayment, the cumulative incidence, the Kaplan–Meier and Aalen–Johansen estimators, discrete-time hazard models and economic scenarios.
1.4.0 (2026-11-24)#
New#
kivi.plotting.distribution_chartdraws the share of all non-events and the share of all events in each row of a gains table or a WOE table as bars side by side, from the rawnon_eventandeventcounts, in the order of the table and with its empty rows.kivi.plotting.precision_recall_chartdraws the precision against the true positive rate, the recall, of every threshold of a ROC table as steps whose area is the average precision, with a dashed line at the event rate of the sample, the precision of a score that ranks at random.kivi.selection.vif_filterdrops the variable with the largest VIF, recomputes the VIFs of the others and repeats until no VIF exceedsthreshold(5 by default). Variables with infinite VIFs go first, andpriority, such as the information values, decides between tied VIFs. It returns the kept columns, likecorrelation_filter.kivi.selection.selection_pathfits the logistic regression on the first 1, 2, 3 and more variables of an order, such as the variables sorted by information value, and returns one row per step with the variable added, the AUC, Gini and KS of the model, its largest Wald p-value and its smallest coefficient. An optional validation sample adds the same metrics on that sample, scored with the models of the development sample. Each row equals whatlogistic_regressionandkivi.metricsgive on the same columns.kivi.vintage.migration_bandwidthandkivi.vintage.migration_testsummarize and test the migrations of customers between rating grades, as sections 2.5.5.1 and 2.5.5.2 of the European Central Bank’s instructions for reporting the validation results of internal models ask. The first gives the upper and lower matrix weighted bandwidth (MWB) of the migrations to worse and to better grades. The second gives, for every off-diagonal cell of the migration matrix, the z test of whether it holds more customers than its neighbour towards the diagonal. Both take the grades of each customer at the beginning and at the end of the period liketransition_matrix, withgradesfrom the best to the worst, and count a customer whose status at the end is not a grade, such as"default"or"closed", among the customers of its grade at the beginning.kivi.calibration.concentration_testgives the HI and the coefficient of variation of the shares of the grades of a rating scale and tests whether they are more concentrated than at the initial validation, as section 2.5.5.3 of the ECB’s instructions asks. The HI is1 + ln(HHI) / ln(K)for the Herfindahl-Hirschman index ofherfindahl_indexandKgrades.kivi.calibration.backtest_tableback-tests continuous estimates, such as LGDs, ELBEs and CCFs, against their realized values: for every group it gives the mean estimate and realized value, the variance of their difference and the t test of the ECB’s instructions. Its p-value is one-sided, as sections 2.6.2.1, 2.8.2.1 and 2.9.3.1 ask for the LGD, the LGD in-default and the CCF, so small p-values mean that the estimates are too low; the ELBE test of section 2.7.2.1 is two-sided, with the p-value2 * min(p_value, 1 - p_value).kivi.calibration.spiegelhalter_testtests the probabilities of single observations with Spiegelhalter’s z statistic, which compares their Brier score with the score they would have if they were the true probabilities.kivi.calibration.brier_decompositionsplits the Brier score by groups into reliability, resolution and uncertainty, plus two terms for probabilities that vary within a group, which are 0 on a master scale whose grades each have one PD.kivi.metrics.generalized_aucgives the generalized AUC of the ECB’s instructions (section 2.6.3.1 and annex 3.2) and Somers’ D, with their standard errors and a confidence interval likeroc_auc_interval. It measures how well estimated segments, such as the facility grades of an LGD model, rank realized ones, such as the realized LGDs cut into segments.The new guide to model validation maps the quantitative tools of the ECB’s validation report to kivi’s functions, and shows the back-tests, the comparison of the current AUC and gAUC with those of the initial validation, and the twelve LGD segments of the ECB on simulated data.
kivi.woe.woe_trendnames the shape of the WOE over the bins of a numeric variable, from awoe_tableresult or a table of aBinningSpec:"increasing","decreasing","u_shaped","inverted_u","irregular"or"flat". It reads the rows labeled with intervals in the order of the table, leaves out the rows of special codes and missing values, and counts neighbouring bins with equal WOE as neither rising nor falling.
Changed#
The vintage guide gains a diagram of how
delinquency_panelturns the instalments and payments of one loan into its rows at each month end. The binning guide gains a diagram of the second step ofks_edges, which compares the best cuts of the two bins of the first cut, and says whyks_edgesis not in its comparison of the methods.The diagram of
ahp_weightsin the guide to expert scorecards shows the statistics ofahp_consistencyas the unnamed Series that the function returns, without the column namevalue.The glossary defines ChiMerge, Best-KS and monotonic binning, delinquency buckets, bad definitions, the overdue and outstanding amounts of
delinquency_panel, the tolerances ofdelinquency_paneland of the AHP functions and the global weights of sub-factors, and tells the events ofkivi.featuresapart from the events of a target.The migration guide corrects its mappings of 0.2.x:
StepWisecompared the models of a fixed order and becomesselection_path, whilestepwiseselects by p-values;VIF.LowVIFFeaturesbecomesvif_filter,woe/utils.monotonybecomeswoe_trend, andBinaryMetrics.plot_ks,plot_scoreandplot_prbecomegains_chart,distribution_chartandprecision_recall_chart. It states how each differs from the legacy code, and gives pandas code forint_scoreandStepWise.top_n_features, which are not ported.The conventions page describes the arguments
realized,estimatedandgrades, the compatibility page lists the tables ofselection_pathand of the validation tests and the labels ofwoe_trend, and the glossary defines back-tests, the Brier decomposition, the generalized AUC and Somers’ D, the HHI and the HI, the migration matrix and its bandwidth, the initial validation, the ELBE and the CCF, the precision-recall curve, average precision and recall, the selection path, VIFs and their elimination, and the trend of the WOE.The guide to model validation comes after the guide to model monitoring, and the home page and the index of the user guide describe it. The guides gain diagrams of how
generalized_auc,migration_bandwidthandmigration_testcompute their results, and charts of a selection path, of the Brier decomposition, of the concentration of grades and of the back-test of LGD grades.The README gallery opens with a chart of time-window features: the share of applicants and the event rate per band of the cash withdrawals in the last three months and in the three months before, computed with a
FeatureSpecfrom synthetic transactions. The features guide shows the same chart after its screening of these features.The workflow diagram of the README starts with defining the features once with a
FeatureSpecand computing them for every sample, before the bin edges are fitted once and every sample is cut with them.The tutorial gains a chapter on transaction features, after the data and samples, so it has eleven chapters. The lender dates the applications, simulates the transactions on the applicants’ accounts with
make_transactions, derives cash, repayment and purchase features as of each application date with aFeatureSpec, checks that the transactions after the application count in none of them, profiles them withprofile_tablenext to the application data, and saves the specification as JSON. The scorecard of the later chapters still uses the application data alone, and their results are unchanged.The chapter on the loan book under IFRS 9 reads the repayment history of each loan with
panel_featuresand shows how a probation of six months for cured loans changes the stages and the loss allowance.
1.3.0 (2026-11-23)#
New#
The new module
kivi.featurescomputes time-window features of event data, such as transactions, point in time.window_featuresaggregates the events of each entity over windows that end at the observation time of each row of an observation table, such as the application date, and never uses an event at or after that time. Windows count calendar months, as"3M", or days, as"90D", and a pair such as("6M", "3M")is the period before the most recent one;closed="right"includes the events at the observation time instead. The aggregations arecount,sum,mean,min,max,std,nunique,first,lastanddays_since_last,ratiosdivides two features, andprefixnames the features of filtered events. The columns are named{prefix}{column}_{aggregation}_{window}next to{prefix}events_{window}, the number of events of each window. The events are sorted once and the bounds of every window found by binary search, so counts, sums, means and first and last values take a time that grows with the number of rows, whilemin,max,stdandnuniquelook at every event of every window.kivi.features.FeatureSpeckeeps the definitions of one or more groups of window features and their ratios, computes them on any sample withcomputeand saves them as versioned JSON withto_jsonandfrom_json, so that development and production compute the same features. Nothing in it is fitted to data.kivi.datasets.make_transactionssimulates the account transactions that precede the applications ofmake_applications: card purchases, cash withdrawals and instalment repayments over the twelve months (orn_months) before each application date, as a long table with the applicant id, the timestamp, the amount, the kind and the merchant category. The transactions depend on the hidden risk factor and on the income, not on the outcome: applicants at risk build up stress, withdraw more cash as the application nears and repay less, so that features of time windows carry a clear but imperfect signal abouttarget, also within bands ofincumbent_pd. The dates of the applications, required, come from a column, as one date or as a Series. The samerngseed always gives the same transactions.kivi.datasets.make_applicationstakesinclude_risk=Trueto append the hidden risk factor as the last columnrisk. The default output is unchanged.kivi.features.panel_featuressummarizes a monthly panel of repayment statuses, such as the result ofkivi.vintage.delinquency_panelorkivi.datasets.make_loan_panel, before each observation time. For every window of months it gives the number of months with a status, the bad months, the longest runs of consecutive bad and good months and the worst status, and it adds the months since the latest bad month. A status is bad frombadon,"30-59"by default, in the order of the ordered categorical status column. Only the month ends before the month of the observation time count, an entity with several loans takes the worst status of each month, and a month without a status counts in no window and ends a run.kivi.features.FeatureSpecholds groups of panel features inpanel, next to the groups of window features inevents, andcomputetakes the panels aspanel. Ratios may divide features of both kinds. Version 1 of its JSON format is final.
Changed#
The migration guide maps
FeatureTools,FeatureToolsV2andindex/collect.pyof 0.2.x towindow_features,panel_featuresandFeatureSpecofkivi.features, and states how their windows, aggregations, ratios and runs of months differ from the legacy code. It no longer lists the ratios ofFeatureToolsamong the tools without a replacement, and it namesmake_transactionsnext to the synthetic data of 0.2.x.The conventions page describes the tables, time columns, column names and windows of
kivi.features, the compatibility page lists the columns of its functions and ofmake_transactionsand the JSON format ofFeatureSpec, and the glossary defines point in time, observations, windows and window pairs, and the bad months, runs and monthly status panels of repayment behaviour.The guide to time-window features comes first among the topic guides, before the univariate profile. It gains two diagrams, of the windows of
window_featuresand of the months ofpanel_features, and a section that computes features of the transactions ofmake_transactionswith aFeatureSpecand screens them withprofile_table.
1.2.0 (2026-11-22)#
New#
kivi.vintage.delinquency_panelbuilds the monthly loan panel thatvintage_table,transition_matrixandroll_ratestake from the instalment schedules and the payments of the loans. It applies the payments of each loan to its oldest unpaid instalment first, so that an amount paid early counts towards the next instalment, and at every month end up toendcounts only the payments made by then. Each row has the columns ofmake_loan_panelthat a schedule gives, with the same names and in the same order:loan_id,cohort,month,month_on_book, withprincipalthe unpaid principal asbalance, andstatusin the buckets ofmake_loan_panel. It adds the days past due since the oldest unpaid instalment fell due and the amounts overdue and outstanding. The cohort is the month before the first due date, or withoriginationthe origination month of each loan.tolerancelets an instalment count as paid when a small amount of it remains unpaid. A loan leaves the panel once it is repaid, and keeps rolling after its last due date while it is not.The new module
kivi.expertweighs the factors of an expert scorecard, the kind of scorecard that credit analysts set by judgment where there are too few defaults to fit a model, with the analytic hierarchy process.ahp_weightsturns a pairwise comparison matrix into weights that sum to 1, by Saaty’s principal eigenvector or by the geometric mean of the rows, andahp_consistencyreturns the principal eigenvalue, the consistency index, Saaty’s random index and the consistency ratio, so that judgments with a ratio above the 0.1 rule of thumb can be reviewed.combine_weightsmultiplies the weights of factors and of their sub-factors into global weights. The matrix is a DataFrame whose index and columns name the factors, or an array, and it must have a diagonal of 1 and reciprocal entries, which the functions check. They replace the geometric-mean weights and the consistency check of theAHPclass of the 0.2.x series, which is not part of kivi 1.ks_edges()fits edges by Best-KS binning. It cuts each bin where the cumulative shares of its events and of its non-events differ most, the KS of the bin, among the cuts that leavemin_bin_shareof the observations on each side, and splits the bins best first, by the pairs of an event and a non-event that a cut ranks apart: its KS times the numbers of events and non-events in the bin. It takesmax_bins,specialandweightsastree_edgesdoes and returns edges of the same form, with observed values as interior edges.fit_spec()fits a column withks_edgeswhenmethodis"ks". The saved specification stores the edges, so its format version does not change.
Changed#
The migration guide maps
KSBins,PortfolioAnalysis.Vintageand theAHPclass of 0.2.x toks_edges,delinquency_paneland the functions ofkivi.expert, and states how each one differs from the legacy code. It no longer lists the analytic hierarchy process and the repayment-schedule calculations among the tools without a replacement.The conventions page describes the comparison matrices of
kivi.expertand the dates ofdelinquency_panel, the compatibility page lists the results of the new functions and keeps the random indices ofahp_consistencyconstant, and the glossary defines the terms of the analytic hierarchy process, the grace period and the repayment schedule.The binning guide gains a chart of the Best-KS cuts, and the guide to expert scorecards two diagrams: how the weights and the consistency ratio follow from a comparison matrix, and which judgments of an inconsistent matrix to discuss first.
1.1.0 (2026-11-22)#
New#
kivi.strategy.confusion_tablecounts, at each cut-off of a score, the declined events and non-events and the approved ones, with the precision, recall, F1 score and accuracy of the decision. A score above the cut-off is declined, as incutoff_table, and counts as the prediction of an event. The function takescutoffsandweightsascutoff_tabledoes, so the rows line up, and itsrecallis therejected_event_shareof that table.precisionis NaN for a cut-off that declines nobody.The new module
kivi.plottingdraws the result tables of the other modules with matplotlib, an optional dependency installed withpip install "kivi[plot]".woe_chartdraws the share and the event rate or WOE of each group of a WOE table,correlation_charta correlation matrix,roc_chartthe ROC curve with its KS,gains_chartthe cumulative shares of a gains table,calibration_chartthe observed against the predicted event rate of each group,cutoff_chartthe event rate of the approved book against the approval rate,psi_chartthe reference and current shares of a PSI table,monitoring_chartone column of a monitoring or stability table by period, as a line or as bars, andvintage_chartthe curve of each cohort of a vintage table.Each chart draws on the matplotlib Axes passed as
ax, or on a new figure, and returns the Axes it drew on. It never shows the figure, never changesmatplotlib.rcParamsand never modifies the table, and the text inside it is limited to column names and data values.profile_table()appends five columns. Numeric columns getskewnessandkurtosis, the bias-corrected sample skewness and excess kurtosis thatpandas.Series.skewandpandas.Series.kurtcompute, andcv, the coefficient of variation, all from the values without missing values and special codes and weighted withweights. With a target, numeric columns getks, the KS statistic of their values, and every column getschi2_p_value, the p-value of the chi-squared test of independence between the target and the groups of the quick binning that givesiv.correlation_filter()takesmethod="spearman"for Spearman’s rank correlation, aspandas.DataFrame.corrcomputes it, which suits raw variables with monotone but not linear relations and long tails. The default"pearson"keeps the previous results and remains the choice for WOE-encoded variables.
Changed#
Fourteen topic guides gain diagrams that show how a function computes its result, with the numbers of the guide’s example: the rows of
profile_table, edges andpandas.cut,woe_tableandwoe_transform,correlation_filterand the steps ofstepwise, fuzzy augmentation and the bands of parceling and reweighting, the points of a scorecard, the ROC table, isotonic regression, the confusion matrix and the swap set of a cut-off, a binning specification from the fit to JSON,psi_table, the monitoring table, the transition matrix, and the expected credit loss and the days-past-due backstops of the stages. The calibration guide gains a small example of isotonic regression to go with its diagram.The migration guide maps the charts, the confusion matrix and F1 score, the skewness, kurtosis and coefficient of variation, and the Spearman correlation of 0.2.x to their replacements in 1.1, and it lists the 0.2.x tools that have no replacement, such as
KSBins,KmeansBins,PearsonBinsandDataset.crime_data().The installation page explains the
plotextra, and the conventions and compatibility pages state the rules and the promises of the charts.The risk modeling workflow merges the twelve jobs into three groups with
chimerge_groupsbefore it measures their WOE, sends new jobs to the group ofunknownwithunseen, and saves that grouping in itsBinningSpecwithmethod={"job": "chimerge"}. Its model, scorecard, evaluation, calibration, cut-off and stability report are computed again on the grouped variable.The documentation gains a tutorial section: a credit scorecard project in ten chapters, from the applications of a year to the IFRS 9 loss allowance of the loans. It profiles and bins the candidates, selects the variables, infers the outcomes of the rejects, scales and evaluates the scorecard against the incumbent’s PD, calibrates it on a master scale, chooses the cut-off, monitors a year of production with a shift in the applicants, and allocates the loan book to stages. Boxes marked “Simulation check” compare each estimate with the outcomes that only the simulated data reveal.
Type checkers infer the precise result of the functions whose result follows the type of their input, which now declare it with overloads: a Series input gives a
pandas.Series, a number afloat, and a list or a one-dimensional NumPy array an array, or apandas.Categoricalforcut,group_categoriesandassign_grades. Code such aspd_to_score(series, ...).round(2).indexno longer reports a false error in mypy or Pylance. The functions arepd_to_scoreandscore_to_pdofkivi.scorecard;prior_correction,platt_predict,isotonic_predict,binomial_test,jeffreys_test,fit_grade_pdandassign_gradesofkivi.calibration;kivi.strategy.expected_loss;convert_pd,expected_credit_loss,significant_increaseandassign_stagesofkivi.lifetime;kivi.reject_inference.reweighting;woeandwoe_transformofkivi.woe; andcutandgroup_categoriesofkivi.binning. An argument typednumpy.typing.ArrayLikestill gets the union of the possible results, mypy infersAnyfor aSeries[Any]such as a DataFrame column, and nothing changes at run time.
1.0.0 (2026-11-22)#
Changed#
kivi.woe.woereturns a Series namedwoe, with the index of the counts, when a count argument is a Series, as other functions shape their results like their input. Lists and arrays still give an array. Use.to_numpy()for the array and.ilocto select by position.kivi 1.0 is the first stable release. From now on it follows semantic versioning, as Compatibility describes, and its package metadata says
Development Status :: 5 - Production/Stable.
Removed#
smoothing=Trueraises aValueErrorinkivi.woe.woe_table,kivi.woe.woe,kivi.woe.iv,kivi.stability.psi_table,kivi.stability.psi,kivi.binning.monotonic_edges,kivi.calibration.fit_grade_pd,kivi.monitoring.monitoring_tableandkivi.monitoring.stability_table, as it already did inkivi.spec.fit_specandkivi.binning.chimerge_groups. kivi 0.9 read it as 1 with aFutureWarning; passsmoothing=1for that result.kivi.woe.woe,kivi.woe.ivandkivi.stability.psiraise aValueErrorwhen both counts are Series with different indices, which kivi 0.9 matched by position with aFutureWarning. Align the counts first, for example withSeries.align(other, fill_value=0), or pass arrays when both list the groups in the same order.kivi.datasets.Datasetand its methodbank_data()are removed.kivi.datasets.load_bank()returns the same frame.The
probabilitiesargument ofkivi.calibration.isotonic_predictis removed; passprobability.
0.9.0 (2026-11-22)#
New#
A new page, Compatibility, states what kivi promises from 1.0: semantic versioning, with deprecations that warn with a
FutureWarningfor the rest of a major version, fixes of wrong results in any release, and Python 3.10, NumPy 1.24 and pandas 2.0 as the oldest supported versions, which rise only in a minor release announced by the release before. It also lists the public names, the index and the columns of every table, the exception and warning types, and what later releases read from a savedBinningSpec.Conventions states more of the rules that every function follows: the order of the data of other observations, the names of frames and similar options, the default
bins, how Series results are named, the index names of tables, the fixed rows of some tables, missing values in the binning fits, and the functions withoutweights.The tests keep specifications saved by kivi 0.6.0 and 0.8.0 and check that they still load and encode a sample as those releases did, and that they match a fresh fit up to rounding.
kivi ships inline type hints and a
py.typedmarker, so type checkers such as mypy check code that calls it. Every function in the package is annotated and checked with mypy.
Changed#
kivi.woe.woe,kivi.woe.ivandkivi.stability.psiwarn with aFutureWarningwhen both counts are Series with different indices. They still match the counts by position; kivi 1.0 raises aValueError, as the other functions do for Series that describe the same groups. Pass Series with identical indices, or arrays to keep matching by position.smoothing=Truewarns with aFutureWarninginkivi.woe.woe_table,kivi.woe.woe,kivi.woe.iv,kivi.stability.psi_table,kivi.stability.psi,kivi.binning.monotonic_edges,kivi.calibration.fit_grade_pd,kivi.monitoring.monitoring_tableandkivi.monitoring.stability_table. It still counts as 1, not as the default 0.5; kivi 1.0 raises aValueError, askivi.spec.fit_specandkivi.binning.chimerge_groupsalready do. Passsmoothing=1for the same result.kivi.datasets.Dataset.bank_data()warns with aFutureWarningand is removed in kivi 1.0.kivi.datasets.load_bank()returns the same frame.kivi.calibration.isotonic_predicttakes the probability of each band asprobability, the name the other functions use, andkivi.calibration.isotonic_fitdocuments its second result under that name.probabilities=still works with aFutureWarninguntil kivi 1.0.kivi.strategy.expected_lossnames a Series resultexpected_loss. It took the name of the first Series among its inputs, such aspdorbalance.kivi.calibration.master_scalelabels the grades by the index of a Seriesprobabilitywhenlabelsis not given, somaster_scale(fit_grade_pd(event, total))keeps the grades of a table. A list or an array still gives grades numbered from 1.kivi.lifetime.assign_stagesalso takesdays_past_dueanddefaultedby position, as inassign_stages(significant_increase, days_past_due, defaulted). Calls with keywords work as before.The index of
kivi.selection.logistic_regressionand ofkivi.selection.vifis namedvariable, like that ofkivi.scorecard.points_table, whatever the name of the columns ofX. The index ofkivi.metrics.roc_auc_intervalis namedstatistic.reset_index()therefore gives a column of that name, andkivi.scorecard.woe_to_pointswith coefficients taken fromlogistic_regressiongives columns namedvariable.Error messages show the value at fault in the same form everywhere. NumPy scalars appear as plain numbers, so
bins=numpy.int64(0)givesgot 0instead ofgot np.int64(0). Every function that takes a target saystarget must contain only 0 and 1, got 2ortarget must contain both 0 and 1, got only 0; the weights messages show the first invalid weight or the total of each class; and a weights index that differs from the data saysscore and weights must have identical indices, like the other arguments.The messages that NumPy and pandas gave for kivi’s arguments now name those arguments:
kivi.binning.cutsaysedges must be increasing numbers, got [3, 1]where pandas spoke ofbinsand of aduplicateskeyword thatcutdoes not have, and the binning functions sayvalues must be numbers or special values, got 'a'.kivi.binning.bin_edgesand the supervised binning functions sayvaluesinstead ofreference values.kivi.versionandkivi.PackageNotFoundError, which the package imported fromimportlib.metadataby accident, no longer exist; usekivi.__version__. The public modules no longer bind the helpers they import, such askivi.binning.as_seriesorkivi.metrics.normal_quantile. None of these names was documented.
Fixed#
kivi.woe.woe_transformlooked a number up in the interval of apandas.cuttable that contained it, so raw values and special codes that the table did not have, such as-1grouped bykivi.binning.cutwithspecial=[-1], silently got the WOE of an interval. Labels are now matched by equality, as documented, and such groups are unseen: they raise an error unlessunseengives them a WOE.kivi.binning.cutnow raises an error for an infinite value that is not a special value.pandas.cutleft-infin no interval, so that it was counted as a missing value, and putinfin the last interval. Pass infinite codes inspecialto give them their own group.kivi.spec.BinningSpec.woe_transformgaveinfthe WOE of the last interval, while-infwas unseen. Both are now unseen, like every infinite value that is not a special code of its column, so they raise an error unless the column has an unseen WOE.BinningSpec.cutleaves both missing.kivi.stability.csi_tableraised an error for points of several variables only when the variables were in an index namedvariable. Apoints_tableresult afterreset_index(), with the variables in avariablecolumn, was read as one variable and mixed their groups. It now raises the same error.kivi.spec.fit_specbinned a column with a complex dtype by its real part, with NumPy’sComplexWarning. It now raises an error, and so doBinningSpec.cutandBinningSpec.woe_transformfor a complex column fitted as numeric.kivi.spec.BinningSpecanddataclasses.replacerejected a numeric table whose intervals ran between the exact edges wheneverpandas.cutrounds them in its labels, such as an edge of 0.6428571428571428 shown as 0.643. Such intervals are now accepted and stored under the labels ofkivi.binning.cut, asBinningSpec.from_dictalready did.kivi.woe.woe_transformacceptedunseen=numpy.nan, which gave unseen groups a missing WOE, and infinite values.unseenmust now be"raise"or a finite number, as forkivi.spec.fit_specandkivi.stability.csi_table.kivi.calibration.prior_correction, theprobabilityofcalibration_table,binomial_test,jeffreys_test,hosmer_lemeshowandherfindahl_indexread numbers given as strings, so thatherfindahl_index(["50", "30"])gave 0.53125. They now raise an error that names the argument, such as “counts must be real and numeric, got dtype object with the value ‘50’”, as the other functions of the module do.The counts of
kivi.calibrationread True and False as 1 and 0, so thatbinomial_test([True], [True], 0.5)gave 0.5. Theeventandtotalofbinomial_test,jeffreys_test,hosmer_lemeshowandfit_grade_pdand thecountsofherfindahl_indexnow reject booleans, as weights do. Probabilities and scores still count them as 1 and 0.kivi.calibration.fit_grade_pdraised “the fitted PDs must rise with the grade” for grades that were in order whensmoothingwas not smaller than the total of a grade without defaults, as with the counts of acalibration_tablewhose weights sum to 1. It now says what is wrong, such as “smoothing must be smaller than the total of each grade without defaults, got 0.5 for grade 1 with a total of 0.4”, and the documentation says that weighted counts must be on the scale of observation counts.Invalid arguments that NumPy or pandas used to reject with a
TypeErrornow raise aValueErrorthat names the argument, as the conventions promise: asmoothingthat is a string,Noneor an array, anrngthatnumpy.random.default_rngdoes not accept inkivi.reject_inference.parceling,kivi.datasets.make_applicationsandkivi.datasets.make_loan_panel,edgesofkivi.binning.cutthat are not numbers, and a WOE table ofkivi.woe.woe_transformorkivi.scorecard.points_tablethat holds a value that is not a number.kivi.lifetime.significant_increaselet floating-point rounding decide ties: a PD of 0.04 against 0.03 counted as more than one percentage point higher, and 0.45 as more than 1.5 times 0.30. A PD within a few units in the last place of a threshold now meets it exactly and is not flagged, as the strict thresholds say. Of the 89 pairs of two-decimal PDs that are 0.01 apart, 71 were flagged before and none are now.kivi.lifetime.transition_pdaccepted a float such ashorizons=3.0. A single number of periods must now be an integer, as thehorizonofexpected_credit_lossis; a sequence of horizons may still hold whole numbers as floats.A list or an object array of numbers with
pd.NA, such as[0.5, pd.NA], raised aTypeErroror “must be real and numeric, got dtype object” inkivi.calibration,kivi.scorecard,kivi.strategyandkivi.lifetime, andkivi.calibration.platt_predict([0.5, pd.NA], 1, 0)named the valid value 0.5 in its message. These functions now readpd.NAas a missing value, like None and NaN, and their messages show the first value that is not a number.kivi.scorecard.pd_to_scoreandscore_to_pdread any input as floats:score_to_pdof a date gave a PD of 0, andpd_to_score(["0.1", "0.2"], ...)gave scores. Strings, dates and complex numbers now raise “must be real and numeric”, as inkivi.metrics, while booleans still count as 1 and 0.kivi.scorecard.reason_codeslisted a variable twice, such ashousing, housing, contact, when a column ofpointswas repeated. It now raises an error, aswoe_to_pointsdoes.kivi.scorecard.reason_codesgave None between two reasons when the points of a group intablewere missing, for example after editing the table by hand. Missing or infinite points of a variable ofpointsnow raise an error.kivi.scorecard.woe_to_pointsaligned a mapping of Series by their index labels, so that one row could combine the WOE values of different applicants. The Series of a mapping must now have identical indices, as the Series that describe the same observations must everywhere in kivi; other values are still matched by position.kivi.scorecard.score_scalingreturned NumPy scalars for NumPy arguments, so that afloat32pdorounded the scores ofpd_to_scoreand the points ofpoints_tableto single precision. It now returns Python floats.kivi.scorecard.points_tableandwoe_to_pointssaid “tables has no entry for 1 variable(s): ‘intercept’” for thecoefcolumn ofkivi.selection.logistic_regression, which includes the intercept. They now say “coefficients has an ‘intercept’ entry; drop it and pass it as intercept”.kivi.selection.vifgave a finite VIF for some exact linear combinations: 1.003 forawhencisb + 1e-5 * a, and 5.6e29 for the two columns of a frame with two rows. A column now has an infinite VIF when it is a linear combination of the others up to rounding, as documented; the VIFs of the other columns are unchanged.kivi.vintage.transition_matrixread anynormalizethat is true in Python as True, so thatnormalize="columns", aspandas.crosstabtakes it, gave the shares of each row. It now raises unlessnormalizeis True or False, askivi.calibration.herfindahl_indexdoes.kivi.vintage.transition_matrixandroll_ratesgave a missing value instatesa row and a column of its own, although missing values ofbeforeandafterraise. A missing state now raises an error.kivi.vintage.vintage_tablemade a column of a negativemonth_on_book. It now raises an error, because the months on book count from origination.
0.8.0 (2026-11-21)#
New#
kivi.binninggroups the categories of categorical variables in the same two steps as numeric binning.category_groupspools the categories belowmin_shareormin_countinto one group, andchimerge_groupssorts the categories by their smoothed WOE and merges neighbours by ChiMerge undermax_groups,alphaandmin_group_share. Both return a dict from category to group, takespecialandweights, and leave missing values out.group_categoriesapplies the dict to any sample; a category that it does not map raises an error unlessunseennames the group it should join.fit_specgroups a categorical column thatmethodnames with"rare"or"chimerge";specialandoptionsthen apply to it, and so doesbinswith"chimerge".BinningSpeckeeps the groupings in a newgroupsfield and applies them incutandwoe_transform. Columns without a grouping are fitted as before.The unseen policy of a grouped column can name one of its groups as
{"group": label}:cutthen assigns new categories to that group, andwoe_transformgives them its WOE.A
BinningSpecwith a grouped column is saved withformat_version2, which adds the groupings and the unseen groups; every other specification is still saved as version 1, so earlier versions of kivi read it.from_jsonreads both versions.The new module
kivi.lifetimecovers lifetime PDs and the expected credit loss of IFRS 9.convert_pdconverts a PD term structure, such as the cumulative bad rates of a vintage table, between cumulative, marginal and conditional PDs, and keeps the months on book that a cohort has not reached missing.transition_pdprojects the cumulative PD of each state of a transition matrix over any number of periods, with the default state made absorbing.expected_credit_lossadds up the marginal PD, the LGD and the EAD of each period after the reporting date, discounted at the effective interest rate, into the 12-month or the lifetime expected credit loss of each account. The LGD and the EAD can be constants, one value per account or schedules per account and period.significant_increaseflags a significant increase in credit risk from a relative and an absolute PD threshold, which have no defaults because they are the entity’s policy.assign_stagesgives stages 1 to 3 from these flags, the days past due backstops, by default more than 30 days for stage 2 and 90 days or more for stage 3 as presumed by IFRS 9, and defaulted flags, andstage_tablesums the exposure and the loss allowance of each stage, with its coverage ratio.The new module
kivi.monitoringtracks a score over time.monitoring_tablegives one row per period, such as a month, with the number of observations, the known outcomes and events, the AUC, Gini and KS of the known outcomes, and the PSI of the score against a reference period or a reference sample, on bands fitted once on the reference. A missing target marks an outcome that is not known yet; it counts intotalbut not in the event columns, and a period without both classes has NaN discrimination instead of an error.stability_tablegives the PSI of every grouped variable in every period against the same reference, for the variable part of a stability report. Both functions takeweights, and integer weights give the same table as repeating rows, formonitoring_tableon the same band edges.kivi.metrics.roc_tablelists the points of the ROC curve, one row per distinct score from the highest to the lowest, with the cumulative event and non-event counts, the true and false positive rates and the precision. The trapezoids under it add up toroc_auc, and the largest gap between the rates isks.kivi.metrics.roc_auc_intervalgives the AUC and the Gini coefficient a standard error and a confidence interval at alevel, using DeLong’s method with the fast midrank algorithm of Sun and Xu.kivi.metrics.delong_testtests whether two scores of the same observations have the same AUC, and returns both AUCs, their difference with its standard error and interval, the z statistic and the two-sided p-value.The standard errors read
weightsas frequency weights, so integer weights give the same results as repeating rows. They reproduce the DeLong results that Stata’s and SAS’s manuals publish for the data of Hanley and McNeil (1982) and of DeLong et al. (1988).
Changed#
BinningSpec.format_versionis now the version of the JSON format that each specification writes, 1 or 2, instead of a class attribute equal to 1. The new class constantBinningSpec.FORMAT_VERSIONis the newest version that kivi reads, now 2.The topic guides follow one outline with the same section titles, such as
Special values,Sample weightsandErrors and warnings, and their openings link to the steps before and after them. The binning guide gathers its special values in one section, and the univariate profile shows special codes after the screening by IV. The first mention of a kivi function in each section links to its API entry.The API reference starts with two new pages: the conventions that every function follows, such as the order of the arguments, keyword-only options, inputs and results, sample weights and error messages, and a glossary of credit risk terms. Its module pages come in the order of the user guide, each with an introduction and a link to its guide, and
:mod:links now reach them.The migration guide lists the ROC and precision-recall curves, precision, recall, F1 score and confusion matrix of
BinaryMetricsand the correlation heatmaps ofevaluate/Heatmap.pyas not ported, with their replacements.The user guide gains the guides “Model monitoring” and “Lifetime PD and expected credit loss” in their places in a project. The glossary and the conventions page cover the terms and rules of the new functions. The risk modeling workflow reports the DeLong interval of the Gini and points on to monitoring and the expected credit loss. The guides have new charts for category grouping, the ROC curve, the monitoring report, variable stability by period and PD term structures, and the README shows the monitoring and lifetime PD charts.
Fixed#
kivi.metrics.roc_aucandkivi.metrics.ginicould return a value just above 1 when fractionalweightsrounded the AUC past it. Both are now at most 1, as documented. Other values are unchanged.kivi.stability.psi_table,kivi.stability.csi_tableandkivi.monitoring.stability_tablecounted the groups of the current sample under the wrong labels when both samples were unordered categoricals with the same categories listed in another order, such as["a", "b"]and["b", "a"]. The groups are now matched by label.kivi.stability.psi_tableandkivi.stability.csi_tableraised pandas’IntCastingNaNErrorfor two samples ofpandas.cutbins on other integer edges when one of them had missing values. Such bins are now joined as intervals of floats, which compare equal to the integer intervals.kivi.stability.psi_tableandkivi.stability.csi_tableno longer emit aRuntimeWarning(“invalid value encountered in cast”) on NumPy older than 2.2 when one sample holdspandas.cutbins with an infinite edge and the other sample has other groups: bins cut on other edges or with unused categories removed, intervals that are not categorical, or other labels. The tables are unchanged.A
weightsSeries was compared only with the index of the data, so when the score, the values or the groups were an array, it was matched by position to atargetSeries with another index. The functions ofkivi.metrics,kivi.woe.woe_table,kivi.calibration.calibration_table,platt_fitandisotonic_fit, the supervised functions ofkivi.binning, andkivi.selection.logistic_regressionandstepwisenow raise in that case, for example “target and weights must have identical indices”, as they do for any other two Series that describe the same observations.
0.7.0 (2026-11-20)#
New#
kivi.datasets.make_applicationssimulates seeded loan applications with numeric and categorical features, the PD of an incumbent scorecard, policy declines, the approval decision and a true default flag for every applicant, to try reject inference on.kivi.calibration.master_scalebuilds a master scale from the PD of each grade, such as a geometric grid fromnumpy.geomspace: one row per grade with its lower bound, PD and upper bound, covering 0 to 1. The bounds are the geometric means of adjacent PDs by default, or their arithmetic means withboundary="arithmetic", as in the 0.2 versions.fit_grade_pdfits the PD of each grade to observed default rates, with the logarithm of the rate a straight line in the grade number, by least squares weighted with the number of observations. A grade without defaults enters the fit withsmoothingdefaults, and a grade without observations gets a PD from the line.assign_gradesgives each predicted PD the grade of a scale as an ordered categorical, whichcalibration_tablecounts directly, in the order of the scale. A PD on a bound goes to the lower grade, as withpandas.cut.The new module
kivi.reject_inferenceinfers outcomes for rejected applicants, so that a scorecard developed on approved applicants can be refitted on all of them.fuzzy_augmentationsplits each reject into a bad and a good row weighted by its PD,parcelinglabels the rejects of each score band at the band’s bad rate with a seeded generator, or returns the expected weights, andreweightingweights the approved applicants of each band by the inverse of its approval rate. Afactorabove 1 raises the inferred bad rate, and bands without approved applicants raise an error.logistic_regressionandstepwisetakeweights, frequency weights like those of statsmodels’GLM(freq_weights=...). Integer weights give the same coefficients, standard errors and selection as repeating rows; weights that do not count observations, such as those of reject inference, make the standard errors and p-values too small.The new module
kivi.strategysupports the credit decisions that follow a scorecard.cutoff_tableshows, for each candidate cut-off of a PD or of negated points, the approval rate, the bad rate of the approved book, the shares of bads and goods it rejects and, withloss, the expected loss it approves. Scores at or below the cut-off are approved, so tied scores always get the same decision.swap_setcompares the decisions of a current and a new score at their cut-offs: the applicants both approve, the swap-ins and swap-outs, and those both decline, with event rates where outcomes are known. A missing target marks an unknown outcome, such as that of an applicant the current score declined.expected_lossmultiplies PD, LGD and EAD, andexpected_loss_tableadds up the exposure and the expected loss of each grade, with the expected loss rate and the exposure-weighted PD.The new module
kivi.univariateprofiles the candidates of a model.profile_tablesummarizes every column of a data frame in one row: its kind, missing values, distinct and most frequent values and, for numeric columns, the range, quantiles, mean and standard deviation. With a target it adds the event rates and lifts of missing and non-missing rows, the IV of a quick binning and the Gini coefficient of numeric values. Tied quantiles are recorded in thetied_binscolumn instead of raising a warning for each column, andspecialcodes andweightswork as infit_spec.
Changed#
The risk modeling workflow screens the candidates with
profile_table, calibrates the PD on a master scale withmaster_scaleandassign_grades, and sets a cut-off withcutoff_tableandexpected_loss_table. The user guide has new charts for cut-off curves, reject inference, grade PDs and missing values, and the README shows the cut-off and reject inference charts.
Fixed#
gains_tablewarned about tied scores by suggesting thespecialargument ofbin_edges, whichgains_tabledoes not take. It now suggests fewer bins or explicit edges, ascutoff_tabledoes, and the warning points at the line that called it.
0.6.0 (2026-11-20)#
New#
kivi.calibration.platt_fitandplatt_predictcalibrate a score with a logistic curve, andisotonic_fitandisotonic_predictwith a step function that rises with the score. The fits return plain numbers, a slope and an intercept or band edges and their probabilities, that apply to the scores of any later sample.kivi.stability.csi_tablecomputes the characteristic stability index of a scorecard variable: the change of each group’s share from the reference to the current sample, multiplied by the group’s points. Its sum is the change of the variable’s average points, and over all variables the change of the average score. The shares are not smoothed, and a group without points raises an error unlessunseen_pointsgives its points.kivi.datasets.load_bankloads the bank marketing data.Dataset.bank_datareturns the same data and keeps working without a warning.kivi.datasets.make_loan_panelsimulates a seeded monthly panel of instalment loans whose delinquency rolls forward and cures, to try the vintage and roll-rate functions on.reason_codestakesunseen_points, the points of applicants in groups thatwoe_transformencoded withunseen, one value or values by variable. Points that match no group but lie withinatolofunseen_pointscost nothing, so the variable is not one of those applicants’ reasons. Every other mismatch still raises an error, which now suggests checkingatoland the model and scaling first.The new module
kivi.specbins all the columns of a data frame at once.fit_specfits each numeric column withbin_edgesor a supervised method chosen by column, or with given edges, and measures the WOE of every group; other columns keep their labels. The binning is never changed automatically.The resulting
BinningSpecgroups a sample withcut, encodes it withwoe_transformusing an unseen-group policy by column, and keeps thewoe_tableof every column for review.to_jsonandfrom_jsonsave and load it without changing the groups or the WOE encoding, so production reproduces development exactly.The new module
kivi.vintageanalyses loan portfolios.vintage_tablegives the cumulative bad rate of each origination cohort by month on book, by count or by amount lent, and leaves the months that a cohort has not reached as NaN.transition_matrixcounts the movements of loans between delinquency buckets or of obligors between rating grades, as counts, row shares or sums of balances, androll_ratesgives the share of each bucket that rolls to the next worse one.roc_auc,gini,ks,gains_table,brier_scoreandcalibration_tabletakeweights, likewoe_table. Counts become sums of weights, and integer weights give the same result as repeating rows, forgains_tableon fixed edges.
Changed#
The risk modeling workflow saves the shortlist’s binning with
fit_specand adds the characteristic stability index of every scorecard variable to its stability report. The user guide has new charts for gains, calibration and vintage curves, and the README shows the gains and vintage charts.
Fixed#
On pandas 2.0,
calibration_tableno longer fails when the target has a nullable integer dtype.cut,bin_edgesand the supervised binning functions match special codes after converting numeric strings, so a column read as text, wherepdaysholds"-1", gives the code-1its own group instead of putting it into an interval. Boolean special codes, whichTrue == 1made match the value 1, raise an error.
Removed#
kivi.evaluateis removed; importpsi_tableand the other stability functions fromkivi.stability.bin_edgesno longer acceptsmethodby position; passmethod="uniform"by keyword.
0.5.0 (2026-11-20)#
New#
The new module
kivi.calibrationchecks the calibration of PDs.prior_correctionandcorrected_interceptcorrect a model for a development sample with another event rate.calibration_tablecompares the observed and predicted default rates of master scale grades or other groups, whichbinomial_test,jeffreys_testandhosmer_lemeshowthen test.herfindahl_indexmeasures the concentration of the grades.kivi.woe.woe,kivi.woe.ivandkivi.stability.psicompute WOE, IV and PSI from counts that are already aggregated, including weighted counts.kivi.stabilityholdspsi_tableandpsi.kivi.metricsevaluates a score against a binary target.roc_auc,giniandksmeasure how well it ranks events above non-events,gains_tablereports event rates, captured events, KS and lift by score band, andbrier_scorecompares predicted probabilities with the outcomes. Likewoe_table, each takes the score first and the target second, the reverse of scikit-learn. A higher score must mean a higher event probability, so negate scorecard points before passing them in.bin_edges,chimerge_edges,tree_edges,monotonic_edgesandwoe_tabletakeweights, andpsi_tabletakesreference_weightsandcurrent_weights. Counts become sums of weights, quantile edges become weighted quantiles by the inverted CDF, and observations or groups with zero weight are left out.The new module
kivi.scorecardscales a logistic regression on WOE values into scorecard points.score_scaling,pd_to_scoreandscore_to_pdconvert between probabilities and scores from the points to double the odds, a base score and base odds.points_tablegives the points of every group,woe_to_pointsthose of each applicant, andreason_codesnames the variables that cost an applicant the most points.The new
kivi.selectionmodule selects the variables of a scorecard from WOE-encoded candidates.correlation_filterdrops one variable of each strongly correlated pair, keeping the one with the higher priority, such as its IV.vifcomputes variance inflation factors.logistic_regressionfits a logistic regression in NumPy and reports each coefficient with its standard error, Wald z statistic and p-value. It raisesSeparationErrorwhen the variables separate the classes, so that the estimates do not exist.stepwiseselects variables by their p-values in forward, backward or both directions. By default, it keeps every coefficient positive, as expected for kivi’s WOE.woe_transformreplaces each group with its WOE from awoe_tableresult, the encoding used by a scorecard model. Groups that are not in the table raise an error unlessunseengives their WOE.
Changed#
The API reference has a page for each module. Links to a function on the former single page now go to the page of its module.
methodofbin_edgesis keyword-only. Passing it by position raises aFutureWarningand stops working in 0.6.0.kivi.evaluateis deprecated in favour ofkivi.stability. Importingpsi_tablefrom it raises aFutureWarning, and the module is removed in 0.6.0.The risk modeling workflow runs end to end: variable selection, a fitted logistic model, scorecard points, evaluation, calibration and score stability.
woe_tablealso reportstotal,total_shareandevent_ratefor each group, the columns of a classing report. They use the observed counts; onlynon_event_shareandevent_shareare smoothed.
Fixed#
woe_tableandpsi_tableno longer cause pandas to issueRuntimeWarning: invalid value encountered in caston NumPy older than 2.2 when the groups come frompandas.cutwith infinite edges.On pandas 2.0,
cutand the supervised binning functions no longer fail when nullable integer or float values are combined withspecial.
0.4.0 (2026-11-19)#
New#
bin_edgestakes aspecialargument. Codes such as-1or-999are left out when the edges are fitted.kivi.binning.cutassigns values to the fitted bins and gives each special value its own group. Without special values it returns the same result aspandas.cut.chimerge_edges,tree_edgesandmonotonic_edgesfit edges from a binary target: ChiMerge merging of fine quantile bins, decision-tree splits by entropy or Gini with a minimum bin share, and merging until the WOE is monotonic. They accept the same array-like inputs aswoe_table, return infinite-ended edges likebin_edgesand need only NumPy and pandas.The binning guide compares the three methods on the bank data, with a chart for each.
chimerge_edges,tree_edgesandmonotonic_edgestakespeciallikebin_edges. The codes are left out of the fit together with their labels, andkivi.binning.cutwith the same codes gives each one its own group.
Changed#
bin_edges,woe_tableandpsi_tableaccept any one-dimensional array-like input, such as a list or a NumPy array. Group and target series passed towoe_tablemust still share an index; arrays and lists are matched by position.bin_edgesissues aUserWarningwhen tied edges leave fewer bins than requested. The message names the most frequent value so that it can be passed inspecial.Error messages name the argument and report the value received.
kivi.__version__is"0+unknown"when kivi is imported from a source tree that is not installed, instead of raising an error.Group counts use
numpy.bincount, which is faster on large samples.The API reference documents errors, warnings, formulas and related functions.
woe_tableandpsi_tablelist categorical groups, including the result ofpandas.cut, in category order with missing values last. Other labels keep the order in which they first appear. Previously all groups followed first appearance, andsort_indexwas needed to put intervals in order.
0.3.0 (2026-11-19)#
A rewrite around a small pandas core. Read Migration guide before upgrading code written for 0.2.x.
New#
bin_edgesfits quantile or uniform edges on a reference sample. The outer edges are infinite, so the result can be passed topandas.cutfor any later sample.woe_tableandpsi_tablereturn raw counts, smoothed shares and a contribution for each group, including missing values.Documentation in English and Simplified Chinese.
Changed#
NumPy and pandas are required dependencies. The 0.2.8 wheel placed them behind the
allextra.The
psicolumn holds the contribution of each bin. It previously repeated the overall total.Zero counts are replaced before each distribution is normalized, and reported counts are no longer modified.
Removed#
Spark, SQL, AHP, feature selection, model wrappers, weighted and supervised binning and scorecards. They remain in the repository history.