Conventions#
Every public function of kivi follows the rules on this page. The module pages and the guides take them for granted, and the docstrings mention only where a function departs from them or adds to them.
Imports#
kivi has no top-level imports. Import each function from its module, as in from kivi.woe import woe_table; each module has its own page in this reference.
Only the names that a module lists in __all__ are public. Compatibility says which of them a release may change, and how it announces the change.
kivi needs only NumPy and pandas. kivi.plotting also needs matplotlib, which the plot extra installs (pip install "kivi[plot]"); it imports matplotlib only when it draws a chart, so importing kivi never requires it.
Arguments#
The data come first and the target follows them, as in
woe_table(groups, target),roc_auc(score, target),stepwise(X, target)andfit_spec(frame, target). A function with several data arguments takes all of them before the target, asswap_set(current, new, target)does, and a predicted probability comes after the target, as incalibration_table(groups, target, probability). The back-test of continuous estimates follows the same order, with the realized values in the place of the target and the estimates in that of the probability, as inbacktest_table(groups, realized, estimated), andgeneralized_auc()takes the estimated segments as its data, like a score, and the realized ones as its target, as ingeneralized_auc(estimated, realized). scikit-learn’s metrics take the target first, so check the order when porting code from them.Data that describe other observations, such as the rejected applicants, follow the data and the target of the main sample, as in
parceling(score, target, reject_score)and inreweighting(score, reject_score), which has no target. In the same way, the payments ofdelinquency_panel()follow its schedule, as indelinquency_panel(loan, due_date, amount_due, payment_loan, payment_date, payment_amount), and the cash flows ofworkout_lgd()follow its defaulted loans, as inworkout_lgd(loan, default_date, ead, flow_loan, flow_date, flow_amount, rate=rate), with positive recoveries and negative costs.The functions of
kivi.featurestake tables with named columns, asfit_spec()andprofile_table()do: first the events or the monthly panel, thenobservations, with one row per entity and observation time, such as the applicants and their application dates, as inwindow_features(events, observations, id=..., time=..., observation_time=...). The names of the columns are keyword arguments.idnames the entity in both tables, and its values are matched by equality, so1and"1"are different entities.Xis a numeric model matrix, as instepwise(),logistic_regression(),selection_path(),vif(),vif_filter(),correlation_filter()andfractional_regression(). Theresponseoffractional_regression()is a continuous target from 0 to 1, such as a realized LGD, where a binary one is calledtarget.frameholds raw columns, as infit_spec(),profile_table()andBinningSpec.cut, andwoeis the matrix of WOE values thatwoe_to_points()turns into points.matrixis a square matrix of pairwise comparisons inkivi.expert: a DataFrame whose index and columns hold the same factor labels in the same order, or an array or a nested list, whose factors are numbered from 0. Its diagonal must be 1 and its entries reciprocal, \(a_{ij} a_{ji} = 1\), to the relative tolerance of the keywordrtol, 1e-3 by default, which accepts reciprocals rounded to four decimals, such as 0.3333 for 1 / 3. Thematrixoftransition_pd()is a transition matrix instead, whose rows are probabilities that add up to 1.gradeslists the grades of a rating system from the best to the worst, at least two, inmigration_bandwidth()andmigration_test(). They take the grade of each customer at the beginning of the period and its status at the end, as inmigration_test(before, after, grades=grades), liketransition_matrix(). Every value ofbeforemust be a grade, while a status at the end that is not one, such as"default"or"closed", counts only among the customers of the grade at the beginning.realizedandestimatedare continuous values, such as the realized LGD of a closed default and its estimate, which may lie outside [0, 1]. Forgeneralized_auc()they are ordered segments: numbers in the order of their values or an ordered categorical in the order of its categories.A predicted probability of an event, such as a PD, is always called
probability, as inbrier_score(probability, target),calibration_table(groups, target, probability)andexpected_loss(probability, lgd, ead). What ascoreis depends on the module; see Targets, scores and probabilities. A second probability is named after its meaning, asorigination_probabilityinsignificant_increase().An option with the same meaning has the same name in every module, such as
bins,special,smoothing,unseenandweights.levelis the confidence level of an interval or a bound, a number strictly between 0 and 1 that defaults to 0.95, as inroc_auc_interval(),generalized_auc()andmost_prudent_pd(). Thelevelofcapital_requirement()is the confidence level of the one-factor model, 0.999 by default as the IRB approach sets it, and that ofconditional_pd()the quantile of the economy, given instead of afactor.binsdefaults to 5 for the bins of a variable, as inbin_edges(),fit_spec()andprofile_table(), and to 10 for the bands of a score, as ingains_table(),monitoring_table(),parceling()andreweighting(). Thecutoffsofcutoff_table()andconfusion_table()default to 10 bands as well.asset_classselects the risk-weight function ofkivi.capital:"corporate","hvcre","mortgage","revolving"or"other_retail". It is keyword-only and has no default, because the class decides the formula.correlationthere is an asset correlation of at least 0 and below 1, and above 0 insystematic_factor(), andturnoverandmaturityare given in the units of the rules, such as millions of euros and years.eventis a count of events per group where the rows are groups, as infit_grade_pd()andmost_prudent_pd(), which take it withtotal, and as theeventcolumn of the tables. Insurvival_table()it is a 0/1 flag per account instead, next tocompeting, the flag of an exit for another reason, such as an early repayment; the two are never both 1 on a row.durationis the period in which an account defaulted, left or was last observed, a positive whole number, andentrythe number of periods before it came under observation.specialis a list of codes for a function of one variable, and a dict by column forfit_spec()andprofile_table(), which reject a list.Some options have similar names but different meanings. The
min_shareofcategory_groups()is the share below which a category counts as rare, while themin_bin_shareoftree_edges()andks_edges()and themin_group_shareofchimerge_groups()set the smallest bin or group of the result. Onlymonotonic_edges()acceptsmax_bins=None, which merges bins only until the WOE is monotonic.unseensays what to do with a group that a table lacks and defaults to"raise", whileunseen_pointsis a number of points or None.methodnames the binning method inbin_edges()andfit_spec(), the correlation incorrelation_filter()and the estimate of the weights inahp_weights().rateis a rate per period inexpected_credit_loss()and an annual rate, one for all loans or one per loan, inworkout_lgd().A reference that could be read in two ways has one argument for each. The functions of
kivi.monitoringtake eitherreference_period, a label of the period argument, or a reference sample inreference_scoreorreference_groups, and raise unless exactly one is given.The data, and the fitted results that a function applies, such as the edges of
cut()or the table ofwoe_transform(), are positional arguments. Every option after them is keyword-only. The number of bins ofbin_edges()is the one option that can also be passed by position:
>>> from kivi.binning import bin_edges
>>> bin_edges([1, 2, 3, 4], 2)
array([-inf, 2.5, inf])
>>> bin_edges([1, 2, 3, 4], 2, method="uniform")
array([-inf, 2.5, inf])
>>> bin_edges([1, 2, 3, 4], 2, "uniform")
Traceback (most recent call last):
...
TypeError: bin_edges() takes from 1 to 2 positional arguments but 3 were given
Inputs and results#
A one-dimensional input is array_like: a list, a NumPy array or a pandas Series. A function that works on several columns at once, such as
stepwise()orfit_spec(), takes a DataFrame.The binning functions read their
valueswithpandas.to_numeric, so strings of numbers and booleans count as numbers there. Special codes must not be booleans, becauseTrue == 1, andfit_spec()groups a boolean column as categorical instead of binning it.Dates, such as the due dates and payment dates of
delinquency_panel(), the default and flow dates ofworkout_lgd()and the application dates ofmake_transactions(), are read withpandas.to_datetime, as datetimes or as strings. Numbers raise an error instead of being read as nanoseconds since 1970, the time of day is ignored, and a date with a time zone keeps its local date.workout_lgd()andmake_transactions()also reject periods, which.dt.to_timestamp()converts.The time columns of
kivi.featuresare stricter: they must already hold datetimes, and strings raise an error that suggestspandas.to_datetime, because parsing the strings of a large event table is slow and its format can be ambiguous. They keep the time of day. The times of the events and of the observations are both tz-naive or both in one time zone, compared by name, and any other combination raises; with a time zone, the bounds of a window are computed on the local calendar and the events compared as instants. Themonthofpanel_features()may hold monthly periods or datetimes, and months and observation times are each read on their own calendar, so tz-aware months and tz-aware observation times must share one time zone.A result with one value per input value is shaped like the input. A Series gives a Series with the same index and name, other array_like input gives a NumPy array, and a single number gives a float.
cut()andassign_grades()return groups, so for input other than a Series they return apandas.Categorical:
>>> import pandas as pd
>>> from kivi.calibration import prior_correction
>>> rates = dict(sample_rate=0.5, population_rate=0.02)
>>> prior_correction([0.5, 0.2], **rates).round(4)
array([0.02 , 0.0051])
>>> prior_correction(pd.Series([0.5, 0.2], index=["a", "b"], name="pd"), **rates).round(4)
a 0.0200
b 0.0051
Name: pd, dtype: float64
>>> round(prior_correction(0.5, **rates), 4)
0.02
A Series result takes the name of the first data argument, as the results of
pd_to_score(),cut()andwoe_transform()do, so the scores of a Series namedpdare namedpdtoo. A result that is a new quantity is named after it:woe()names its resultwoe,expected_loss()expected_loss,significant_increase()significant_increase,assign_stages()stage,reweighting(),ahp_weights()andcombine_weights()weight,asset_correlation()correlation,capital_requirement()capital_requirement,conditional_pd()conditional_pd,systematic_factor()factor,most_prudent_pd()most_prudent_pdandconversion_factor()ccf. The value-by-value functions ofkivi.capitalbroadcast their inputs against each other, so one call covers a portfolio with a PD, an LGD and a maturity per exposure and one asset class.Some inputs must be one-dimensional even for one exposure.
significant_increase()andassign_stages()raise for a single number, andexpected_credit_loss()takes one row per account, so pass the single curve ofconvert_pd()ascurve[None, :].Series that describe the same observations, such as the data, the target, the probabilities and the weights, must have identical indices; they are not aligned. Any other combination of these inputs is matched by position. Inputs that describe other observations, such as the two samples of
psi_table(), the rejected applicants ofparceling()or the payments ofdelinquency_panel(), can have any index. Counts per group, as inwoe(),iv()andpsi(), describe the same groups, so two Series of counts must have identical indices too.Tables are DataFrames. A table of the groups passed in, such as that of
woe_table(), is indexed by the group labels, in an index namedbin. Other tables name the index after their rows, such asvariable,grade,cutoff,threshold,statistic,step,period,cohort,state,stage,loanorbefore, and name their columns when these are labels too, such ashorizon,afterormonth_on_book. Compatibility lists the index and the columns of every table. A total is the sum of a column, such aswoe_table(groups, target)["iv"].sum().The features of
kivi.featureskeep the index ofobservations, in its order, so that they join back to the observations. Their names follow from the arguments: the column names and theprefixare kept as given, and only kivi’s own parts of the names, the aggregations and the windows, are in lower case, soAmountandamountgiveAmount_sum_3mandamount_sum_3m.Named statistics come back as a Series or a DataFrame with an index named
statistic, as fromroc_auc_interval(),generalized_auc(),brier_decomposition(),concentration_test(),migration_bandwidth()andahp_consistency(), or as a Series indexed by the names alone, as fromdelong_test(). Parameters that another function applies come back as a tuple, such as the edges and the probabilities thatisotonic_fit()returns forisotonic_predict()and the long-run PD and the correlation thatvasicek_fit()returns forconditional_pd(), and so does the statistic and p-value pair ofhosmer_lemeshow()andspiegelhalter_test().A chart of
kivi.plottingtakes the table that a kivi function returned first, and the Axes to draw on as the keyword-onlyax; withoutaxit draws on a new figure. It returns the Axes, never shows the figure and leaves matplotlib’s global settings alone. The text it writes is only column names, argument names and values, so one image serves every language.Functions do not modify their inputs. Random draws come from a local generator seeded by
rng, so they never change NumPy’s global state, and the same seed gives the same result.rngtakes whatnumpy.random.default_rngtakes, such as None, an integer, aSeedSequenceor aGenerator. AGeneratoris used and advanced rather than copied, so two calls with the sameGeneratorgive different draws, while two calls with the same integer agree.
Targets, scores and probabilities#
A target is 1 for an event, such as a default, and 0 for a non-event. Any other label, and a missing label, raises an error.
swap_set()andmonitoring_table()are the exceptions: they read a missing label as an outcome that is not known, such as that of a declined applicant or of a loan whose outcome window has not ended.The
badargument ofvintage_table()is the status of a loan in a month, such as being 90 days past due, rather than the target of an observation. It takes booleans or 0 and 1, without missing values. Thebadofpanel_features()is the first bad category of an ordered status column instead,"30-59"by default: it and every worse status count as bad. The status column must be an ordered categorical, from the best status to the worst, so that labels such ascurrentare never sorted alphabetically.In
kivi.metrics,kivi.monitoringandkivi.strategy, a score rises with the event probability. Pass a PD as it is, and negate scorecard points, which fall as the risk rises. A cut-off ofkivi.strategyapproves the scores at or below it.In
kivi.scorecard, ascoreis scorecard points, which fall as the risk rises:score_to_pd()gives a lower PD for a higher score.platt_fit()accepts a score in either direction and fits a negative slope to one that falls as the risk rises.isotonic_fit()assumes a rising score unlessincreasing=False.True and False count as 1 and 0 in targets, scores and probabilities, and in the aggregations of
window_features(), where thesumof a flag counts the events that have it. Weights, LGDs, exposures, losses, thedefault_rateofsystematic_factor()andvasicek_fit(), the amounts ofdelinquency_panel(),workout_lgd()andconversion_factor(), theresponseoffractional_regression(), therealizedandestimatedvalues ofbacktest_table()andgeneralized_auc()and the entries of a comparison matrix reject them, and so do most numeric options, such asbins,max_bins,factorand the cut-offs. Six inputs reject them because a boolean there is more likely a mistake: thereference_scoreofmonitoring_table(), which would usually be a row mask, thematrixoftransition_pd(), thestageofstage_table(), thedays_past_dueofassign_stages(), and thedurationandentryofsurvival_table():
>>> import numpy as np
>>> from kivi.metrics import roc_auc
>>> roc_auc([0.1, 0.9, 0.4], [False, True, True])
1.0
>>> from kivi.strategy import expected_loss
>>> expected_loss(np.array([0.1, 0.2]), np.array([True, False]), 100.0)
Traceback (most recent call last):
...
ValueError: lgd must be real and numeric, got dtype bool
Groups and missing values#
The functions that count groups, such as woe_table(), psi_table() and calibration_table(), take the labels as they are: the intervals of pandas.cut or kivi.binning.cut(), strings, numbers or categories.
Missing values form a group of their own.
Only observed groups appear. Unused categories are left out, and so are the groups whose weights sum to zero. Tables with a fixed set of rows are the exception and keep their empty rows:
stage_table()always has stages 1, 2 and 3,swap_set()always has its four rows, and the period tables ofkivi.monitoringkeep a row for every category of a categorical period, so that the rows of all reports line up.Categorical groups, including the intervals of
pandas.cut, follow the order of their categories, with the missing group last. Other labels follow the order in which they first appear.Two samples, as in
psi_table(), follow the order of the categories only when both have the same categorical dtype. Otherwise, as for an ordered and an unordered categorical, their groups follow the order in which they first appear, in the reference sample and then in the current one.
>>> from kivi.woe import woe_table
>>> woe_table(["b", "a", None, "a"], [1, 0, 1, 0])[["non_event", "event"]]
non_event event
bin
b 0 1
a 2 0
NaN 0 1
cut() returns the ordered categorical of pandas.cut when there are no special codes, and an unordered one with special, because the special codes come first and have no order with the intervals.
Categories are matched to a fitted table or grouping by equality, and a category that it does not know raises an error unless unseen says how to treat it. woe_transform(), group_categories() and csi_table() share this rule, the last through unseen_points. reason_codes() matches points rather than categories, and its unseen_points exempts the points that woe_transform gave unseen groups.
The functions that fit edges or groupings, such as bin_edges(), chimerge_edges() and category_groups(), leave missing values out of the fit, and cut() and group_categories() keep them missing, so that they form a group of their own when counted.
The functions that count, rank or fit, such as roc_auc(), calibration_table(), cutoff_table() and platt_fit(), raise an error for a missing score or probability instead, so decide how missing values are scored before passing them in. The functions that convert each value on its own, such as pd_to_score(), platt_predict() and expected_loss(), return NaN for a missing value, and assign_grades() returns a missing grade. The staging functions of kivi.lifetime work value by value but raise for a missing value, because a missing PD or number of days past due must not decide a stage, and the functions of kivi.monitoring raise for a missing period. The value-by-value functions of kivi.capital return NaN for a missing PD, LGD, default rate, factor or level, but raise for a missing turnover, maturity or correlation, which decides the formula. survival_table(), vasicek_fit() and most_prudent_pd() count or fit their inputs as a whole and raise for a missing value. workout_lgd() raises for a missing loan, date, exposure, amount or rate, lgd_table() for a missing LGD and fractional_regression() for a missing driver or response, while conversion_factor() converts each line on its own and returns NaN. delinquency_panel() raises for a missing loan, date or amount, and the functions of kivi.expert for a missing comparison or weight. The validation tests raise for a missing value as well: backtest_table() for a missing realized or estimated value, generalized_auc() for a missing segment, concentration_test() for a missing count, and migration_bandwidth() and migration_test() for a missing grade or status, so give the customers who left the grades a status of their own. The functions of kivi.features raise for a missing entity, time, month or status, and leave the missing values of an aggregated column out of its aggregations, while the events features count every event.
Sample weights#
Most functions that count observations or fit a model take weights: one finite, non-negative number per observation, matched to the data like the target. psi_table() and csi_table() take one set for each sample, reference_weights and current_weights.
weights belongs to the main data, and the weights of another sample are named after it, as the reference_weights of monitoring_table() and stability_table(). vif(), vif_filter(), correlation_filter(), parceling() and reweighting() take no weights and give every row the same weight, and so do the functions of kivi.features, which count each event once. concentration_test() takes the counts or the exposures of the grades instead of rows, and so do most_prudent_pd(), which takes the obligors and defaults of each grade, and vasicek_fit(), which takes one default rate per period. The value-by-value functions of kivi.capital work on single exposures and take no weights. The validation sample of selection_path() counts each row once.
Counts become sums of weights, and observations with zero weight are left out. Integer weights therefore give the same counts as repeating each row that many times.
Weighted quantiles use the inverted CDF, so every interior quantile edge is an observed value, while unweighted quantiles interpolate between observations. Weighted edges therefore agree with repeated rows only where no interpolation is needed, and weights of 1 do not give the same edges as no weights.
smoothingreplaces an empty cell in units of weight and is not rescaled with the weights.logistic_regression(),stepwise(),selection_path(),roc_auc_interval(),delong_test(),generalized_auc(),spiegelhalter_test(),backtest_table()andmigration_test()read the weights as frequency weights, so their standard errors count the total weight as the number of observations.fractional_regression()does too, andlgd_table()averages the LGDs with frequency weights, whileworkout_lgd()andconversion_factor()work on single loans and take no weights. Weights that correct for sampling, such as inverse sampling rates, make these standard errors too small.
Periods and thresholds#
Periods are ordered as their categories when they are categorical and sorted otherwise. Period 1 of a term structure or an expected credit loss is the first period after its starting point, such as the reporting date, and
expected_credit_loss()discounts a default in period \(t\) over \(t\) periods.workout_lgd()discounts a cash flow over the days between the date of default and its own date, divided by 365, and compounds a cost before default in the same way. Insurvival_table(), an account with theentry\(e\) and theduration\(T\) is at risk in the periods \(e < t \le T\), and an account censored in a period still counts as at risk in it, because its censoring comes after the defaults and exits of the period.A threshold is compared as the rule it implements is worded. A cut-off approves the scores at or below it.
significant_increase()flags a PD increase only when it exceeds its thresholds, andassign_stages()moves a loan to stage 2 when it is more thanstage_2_dayspast due and to stage 3 when it is at leaststage_3_dayspast due, as IFRS 9 words its 30-day and 90-day presumptions.The
endofdelinquency_panel()is the last month observed, given as the month, a date in it or a longer period that ends with it, and every month is observed on its last day, so a payment made on that day counts. An instalment is not past due on its due date, and the status90+starts at 90 days past due, as stage 3 does with thestage_3_daysofassign_stages().
Time windows#
A feature of
kivi.featuresuses only what is known at the observation time \(t\), so that it is point in time. A window ofwindow_features()is \([t - k, t)\) by default, so an event at \(t\) or later counts in no window;closed="right"gives \((t - k, t]\) for events that are known at their own time, such as balances at the end of a day, which only the caller can judge. A window ofpanel_features()holds the \(k\) months before the month of \(t\), because the status at the end of that month is not known at \(t\)."3M"counts calendar months, aspandas.DateOffset(months=3)does, so one month before 31 March is 29 February in a leap year, and"90D"counts days. The bounds are written in upper case, andpanel_features()takes months only. In the column names the windows are in lower case, such as3mand90d.windowsis a list, also for one window, as inwindows=["3M"]. A pair of bounds with the same unit, the first further back, is the earlier period between them, as("6M", "3M")is \([t - 6M, t - 3M)\), named6m_3m. A pair is one window only as an item of the list, as inwindows=[("6M", "3M")]:windows=("6M", "3M")is the two windows6mand3m.
Errors and warnings#
Invalid input raises
ValueError, and so does a model that cannot be fitted, such as one with separated classes, which raiseskivi.selection.SeparationError. The message names the argument and, where a single value is at fault, shows the value that was received:
>>> bin_edges([1, 2, 3], bins=0)
Traceback (most recent call last):
...
ValueError: bins must be a positive integer, got 0
>>> roc_auc([0.1, 0.9, 0.4], [0, 1, 2])
Traceback (most recent call last):
...
ValueError: target must contain only 0 and 1, got 2
A
UserWarningmeans that the result differs from the request, for example fewer bins than requested because of tied values, and says what to change.kivi.univariate.profile_table()records such ties in a column instead, so that profiling many columns raises no warnings.A
RuntimeWarningmeans that a fit stopped before it converged.A
FutureWarningannounces a change of the public API. Compatibility says when the change takes effect.The wording of the messages may change in any release, so a test that matches a message may need an update; the types of the errors and warnings stay.