Credit strategy#
Turn scores and PDs into credit decisions. cutoff_table() shows what each cut-off approves, confusion_table() counts its right and wrong decisions, swap_set() compares the decisions of two scores, and expected_loss() and expected_loss_table() give the expected loss of each exposure and of each grade.
See Credit strategy for examples on the bundled data.
|
Summarize the approved book and the rejected events at each cut-off. |
|
Count the declined events and non-events at each cut-off, with precision, recall and F1. |
|
Compare the decisions of a current and a new score at their cut-offs. |
|
Compute the expected loss of each exposure from its PD, LGD and EAD. |
|
Summarize exposure and expected loss by grade or other group. |
- kivi.strategy.cutoff_table(score, target, *, cutoffs=10, loss=None, revenue=None, weights=None)#
Summarize the approved book and the rejected events at each cut-off.
A cut-off approves every observation whose score is at or below it, so a higher cut-off approves more applicants and lets more events through. Each row shows the size and the event rate of the approved book and the shares of events and non-events that the cut-off rejects, and with loss and revenue the losses, revenue and profit of the approved book.
- Parameters:
- scorearray_like
Finite numeric scores that are higher for a higher risk, such as a PD. Negate scorecard points, which are higher for a lower risk.
- targetarray_like
Binary labels, with 1 indicating the event. Both classes must be present. If score and target are both pandas Series, they must have identical indices; otherwise they are matched by position.
- cutoffsint or array_like, default 10
Number of quantile cut-offs, or increasing cut-off values. An integer n uses the edges of
kivi.binning.bin_edges(score, bins=n)above the lowest, so the rows approve about 1/n, 2/n and so on up to all of the sample, and tied scores can leave fewer rows. Pass explicit values as a sequence, also for a single cut-off, such as[0.1]. With weights, an integer gives weighted quantiles, asbin_edges(score, bins=n, weights=weights)does.- lossarray_like, optional
Non-negative loss of each observation, matched like target, such as its expected loss from expected_loss or the loss realized on a defaulted account. The table then has a column
approved_loss.- revenuearray_like, optional
Non-negative revenue of each observation, matched like target, such as the interest and fees an approved loan earns. The table then has a column
approved_revenue, and with loss alsoprofit. Costs that reduce the revenue, such as funding or acquisition costs, belong in loss.- weightsarray_like, optional
Non-negative weight of each observation, such as the inverse of its sampling rate, matched like target. Counts, losses and revenue become sums of weights. On the same cut-offs, integer weights give the same table as repeating rows; an integer cutoffs can give other cut-offs, because weighted quantiles use the inverted CDF.
- Returns:
- pandas.DataFrame
One row per cut-off, from the lowest to the highest, indexed by the cut-off value. The columns are described in the Notes.
- Raises:
- ValueError
If the inputs are empty or not one-dimensional, their indices or lengths do not match, target has a label other than 0 and 1 or lacks one of them, score is not real and numeric or has a missing or infinite value, or cutoffs is neither a positive integer nor a sequence of increasing numbers. Also if loss or revenue is not numeric or does not give each observation one finite, non-negative amount, or weights is not numeric, does not give each observation one finite, non-negative weight, has an index other than that of score, or leaves a class without weight.
- Warns:
- UserWarning
If cutoffs is an integer and tied scores leave fewer cut-offs than requested, as in kivi.binning.bin_edges.
See also
swap_setCompare the decisions of two scores at their cut-offs.
expected_lossExpected loss of each exposure, to pass as loss.
kivi.metrics.gains_tableEvent rates of the bands between cut-offs.
kivi.metrics.expected_maximum_profitExpected profit of the best cut-off of a score.
Notes
A score equal to the cut-off is approved, so tied scores always get the same decision. With the cut-offs of an integer cutoffs, the approved book of a row consists of the bands of
kivi.metrics.gains_tablewithbins=cutoffsup to that cut-off.The columns are:
approved: observations with a score at or below the cut-off, or the sum of their weights;approval_rate:approveddivided by the whole sample;approved_event: events among the approved observations;approved_event_rate:approved_eventdivided byapproved, the bad rate of the approved book, NaN when nothing is approved;rejected_event_shareandrejected_non_event_share: shares of all events and of all non-events with a score above the cut-off;approved_loss: with loss, the sum of the losses of the approved observations, weighted with weights;approved_revenue: with revenue, the sum of the revenue of the approved observations, weighted with weights;profit: with both loss and revenue,approved_revenueminusapproved_loss.
A higher cut-off raises the approval rate and lowers both rejected shares.
rejected_event_shareis the share of bad outcomes the cut-off avoids, andrejected_non_event_sharethe share of good business it gives up.table["profit"].idxmax()is the most profitable of the cut-offs.Examples
>>> from kivi.strategy import cutoff_table >>> score = [0.1, 0.2, 0.2, 0.3, 0.5, 0.6, 0.8, 0.9] >>> target = [0, 0, 1, 0, 0, 1, 1, 1] >>> table = cutoff_table(score, target, cutoffs=[0.2, 0.5, 1.0]) >>> table[["approved", "approval_rate", "approved_event", "approved_event_rate"]] approved approval_rate approved_event approved_event_rate cutoff 0.2 3 0.375 1 0.333333 0.5 5 0.625 1 0.200000 1.0 8 1.000 4 0.500000 >>> table[["rejected_event_share", "rejected_non_event_share"]] rejected_event_share rejected_non_event_share cutoff 0.2 0.75 0.5 0.5 0.75 0.0 1.0 0.00 0.0
With a loss of 40 on each event and a revenue of 10 on every observation, the cut-off of 0.5 is the most profitable of the three:
>>> loss = [0, 0, 40, 0, 0, 40, 40, 40] >>> table = cutoff_table(score, target, cutoffs=[0.2, 0.5, 1.0], loss=loss, revenue=[10] * 8) >>> table[["approved_loss", "approved_revenue", "profit"]] approved_loss approved_revenue profit cutoff 0.2 40.0 30.0 -10.0 0.5 40.0 50.0 10.0 1.0 160.0 80.0 -80.0 >>> float(table["profit"].idxmax()) 0.5
- kivi.strategy.confusion_table(score, target, *, cutoffs=10, weights=None)#
Count the declined events and non-events at each cut-off, with precision, recall and F1.
A cut-off approves every observation whose score is at or below it and declines the others. Treating a decline as the prediction of an event, each row is the confusion matrix of that decision, with the measures that follow from it.
- Parameters:
- scorearray_like
Finite numeric scores that are higher for a higher risk, such as a PD. Negate scorecard points, which are higher for a lower risk.
- targetarray_like
Binary labels, with 1 indicating the event. Both classes must be present. If score and target are both pandas Series, they must have identical indices; otherwise they are matched by position.
- cutoffsint or array_like, default 10
Number of quantile cut-offs, or increasing cut-off values, as in cutoff_table: an integer n uses the edges of
kivi.binning.bin_edges(score, bins=n)above the lowest, and tied scores can leave fewer rows. Pass explicit values as a sequence, also for a single cut-off, such as[0.1]. With weights, an integer gives weighted quantiles.- weightsarray_like, optional
Non-negative weight of each observation, such as the inverse of its sampling rate, matched like target. The counts become sums of weights. On the same cut-offs, integer weights give the same table as repeating rows; an integer cutoffs can give other cut-offs, because weighted quantiles use the inverted CDF.
- Returns:
- pandas.DataFrame
One row per cut-off, from the lowest to the highest, indexed by the cut-off value in an index named
cutoff, as in cutoff_table. The columns are described in the Notes.
- Raises:
- ValueError
If the inputs are empty or not one-dimensional, their indices or lengths do not match, target has a label other than 0 and 1 or a missing label, or lacks one of the classes, score is not real and numeric or has a missing or infinite value, or cutoffs is neither a positive integer nor a sequence of increasing numbers. Also if weights is not numeric, does not give each observation one finite, non-negative weight, has an index other than that of score, or leaves a class without weight.
- Warns:
- UserWarning
If cutoffs is an integer and tied scores leave fewer cut-offs than requested, as in kivi.binning.bin_edges.
See also
cutoff_tableApproval rate and rejected shares at the same cut-offs.
kivi.metrics.roc_tableThe same counts at every threshold, flagging scores at or above it.
swap_setCompare the decisions of two scores at their cut-offs.
Notes
An event is the positive class and a decline, a score above the cut-off, the positive prediction. A score equal to the cut-off is approved, so tied scores always get the same decision. The columns are:
true_positiveandfalse_positive: events and non-events that the cut-off declines, or the sums of their weights;true_negativeandfalse_negative: non-events and events that the cut-off approves;precision:true_positivedivided by the declined observations, the event rate among them, which is NaN when the cut-off declines nobody;recall:true_positivedivided by all events, the share of events that the cut-off declines;f1: the harmonic mean ofprecisionandrecall, \(2 \mathrm{TP} / (2 \mathrm{TP} + \mathrm{FP} + \mathrm{FN})\), which is 0 when no event is declined, also when nothing is declined;accuracy:true_positiveplustrue_negative, divided by the whole sample.
The rows match the other tables of kivi.
recallequalsrejected_event_shareof cutoff_table,false_positivedivided by all non-events equals itsrejected_non_event_share, andfalse_negativeequals itsapproved_event. Thetrue_positive,false_positive,recallandprecisionof a row also equalcum_event,cum_non_event,true_positive_rateandprecisionof the row of kivi.metrics.roc_table with the lowest threshold above the cut-off, which is infinity when the cut-off is not below any score. The rows are shifted because roc_table flags the scores at or above a threshold, while a cut-off declines only those above it.The measures depend on the share of events in the sample. A cut-off that approves everyone has an accuracy of one minus the event rate, and an event rate of a few per cent gives high accuracy and a low
precisionat almost every cut-off. Compare cut-offs by the shares of events and non-events they decline, as in cutoff_table, or by the costs of the two kinds of error.Examples
>>> from kivi.strategy import confusion_table >>> score = [0.1, 0.2, 0.2, 0.3, 0.5, 0.6, 0.8, 0.9] >>> target = [0, 0, 1, 0, 0, 1, 1, 1] >>> table = confusion_table(score, target, cutoffs=[0.2, 0.5, 1.0]) >>> table[["true_positive", "false_positive", "true_negative", "false_negative"]] true_positive false_positive true_negative false_negative cutoff 0.2 3 2 2 1 0.5 3 0 4 1 1.0 0 0 4 4 >>> table[["precision", "recall", "f1", "accuracy"]].round(3) precision recall f1 accuracy cutoff 0.2 0.6 0.75 0.667 0.625 0.5 1.0 0.75 0.857 0.875 1.0 NaN 0.00 0.000 0.500
- kivi.strategy.swap_set(current, new, target=None, *, current_cutoff, new_cutoff, weights=None)#
Compare the decisions of a current and a new score at their cut-offs.
Each score approves the observations at or below its cut-off. The four rows are the observations both scores approve, the swap-outs that only the current score approves, the swap-ins that only the new score approves, and those both decline.
- Parameters:
- currentarray_like
Finite numeric scores of the current model, higher for a higher risk, such as a PD. Negate scorecard points.
- newarray_like
Finite numeric scores of the new model, of the same length as current and higher for a higher risk. The two scores need not be on the same scale.
- targetarray_like, optional
Binary labels, with 1 indicating the event, and missing values for unknown outcomes, such as the applicants the current score declined. Without target, the table only counts the observations.
- current_cutofffloat
Cut-off of the current score. Observations with a current score at or below it are approved.
- new_cutofffloat
Cut-off of the new score, applied in the same way to new.
- weightsarray_like, optional
Non-negative weight of each observation, such as the inverse of its sampling rate. Counts become sums of weights, so integer weights give the same table as repeating rows.
- Returns:
- pandas.DataFrame
Four rows indexed by the decisions of the two scores,
currentandnew, each"approve"or"decline". The columns aretotalandshare, and with target alsoknown,eventandevent_rate; see the Notes.
- Raises:
- ValueError
If the inputs are empty or not one-dimensional, their lengths differ, or they are Series with different indices; current or new is not real and numeric or has a missing or infinite value; target has a value other than 0, 1 and missing; a cut-off is not a number or is missing; or weights is not numeric, does not give each observation one finite, non-negative weight with a positive total, or has an index other than that of current.
See also
cutoff_tableApproval and event rates over a range of cut-offs.
kivi.reject_inference.fuzzy_augmentationInfer the outcomes of declined applicants.
Notes
The rows
("approve", "decline")and("decline", "approve")are the swap-outs and the swap-ins. Every row is reported, also when it is empty. The columns are:total: observations in the row, or the sum of their weights;share:totaldivided by the whole sample;known: observations in the row with a known outcome;event: events in the row;event_rate:eventdivided byknown, NaN without known outcomes.
The outcomes of the applicants the current score declined are usually unknown, because they never received a loan. The rows of current declines, including the swap-ins, then have no
event_rate, and the swap set alone cannot show whether the new score accepts better applicants than it rejects. Reject inference estimates the missing outcomes; pass the inferred labels, with weights for an augmented sample, to complete the table.Examples
>>> from kivi.strategy import swap_set >>> current = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8] >>> new = [0.1, 0.3, 0.2, 0.6, 0.4, 0.7, 0.5, 0.8] >>> target = [0, 0, 1, 0, 1, 1, 0, 1] >>> swap_set(current, new, target, current_cutoff=0.4, new_cutoff=0.4) total share known event event_rate current new approve approve 3 0.375 3 1 0.333333 decline 1 0.125 1 0 0.000000 decline approve 1 0.125 1 1 1.000000 decline 3 0.375 3 2 0.666667
The current declines usually have no known outcome:
>>> import numpy as np >>> known = np.where(np.array(current) <= 0.4, target, np.nan) >>> swap_set(current, new, known, current_cutoff=0.4, new_cutoff=0.4) total share known event event_rate current new approve approve 3 0.375 3 1 0.333333 decline 1 0.125 1 0 0.000000 decline approve 1 0.125 0 0 NaN decline 3 0.375 0 0 NaN
- kivi.strategy.expected_loss(probability, lgd, ead)#
Compute the expected loss of each exposure from its PD, LGD and EAD.
The expected loss is the product of the probability of default, the loss given default and the exposure at default.
- Parameters:
- probabilityarray_like
Probabilities of default, from 0 to 1. Missing values give missing losses.
- lgdarray_like
Loss given default as a share of the exposure, from 0 to 1, as one value for all exposures or one per exposure.
- eadarray_like
Exposure at default, such as the outstanding balance, finite and non-negative, as one value or one per exposure.
- Returns:
- float, pandas.Series or numpy.ndarray
Expected losses, in the units of ead, with the broadcast shape of the inputs. If an input is a Series, the result is a Series with its index, named
expected_loss; scalar inputs give a float.
- Raises:
- ValueError
If an input is not real and numeric, the inputs cannot be broadcast together, Series inputs have different indices, probability or lgd has a value outside [0, 1], or ead has a negative or infinite value.
See also
expected_loss_tableExposure and expected loss by grade.
cutoff_tablePass the expected losses as loss to sum them by cut-off.
kivi.scorecard.score_to_pdThe PD implied by a scorecard score.
Notes
For an exposure with probability of default \(\mathrm{PD}\), loss given default \(\mathrm{LGD}\) and exposure at default \(\mathrm{EAD}\),
\[\mathrm{EL} = \mathrm{PD} \times \mathrm{LGD} \times \mathrm{EAD}.\]The PD refers to a horizon, usually one year, and the expected loss refers to the same horizon. Missing values are not checked and give a missing loss.
Examples
>>> from kivi.strategy import expected_loss >>> expected_loss([0.02, 0.1, 0.25], 0.45, [1000, 500, 200]) array([ 9. , 22.5, 22.5])
- kivi.strategy.expected_loss_table(groups, probability, lgd, ead, *, weights=None)#
Summarize exposure and expected loss by grade or other group.
Each row adds up the exposures and expected losses of a group, such as a grade of a master scale, and gives their ratio, the expected loss rate.
- Parameters:
- groupsarray_like
Grade or group labels. Missing values form a group.
- probabilityarray_like
Probability of default of each exposure, from 0 to 1, without missing values.
- lgdarray_like
Loss given default, from 0 to 1, as one value for all exposures or one per exposure.
- eadarray_like
Exposure at default, finite and non-negative, as one value or one per exposure. Series inputs must have identical indices; otherwise the inputs are matched by position.
- weightsarray_like, optional
Non-negative weight of each exposure, such as the inverse of its sampling rate, matched like probability. Counts, exposures and losses become sums of weights, so integer weights give the same groups and sums as repeating rows, and groups whose weights sum to zero are left out. Groups that are not categorical keep the order in which they first appear, also in rows of zero weight, so their order can differ from that of repeated rows.
- Returns:
- pandas.DataFrame
One row per group with the columns described in the Notes.
- Raises:
- ValueError
If groups or probability is empty or not one-dimensional, an input does not have one value per exposure or a Series index other than that of the others, probability, lgd or ead is not real and numeric or has a missing value, probability or lgd has a value outside [0, 1], or ead has a negative or infinite value. Also if weights is not numeric, does not give each exposure one finite, non-negative weight with a positive total, or has an index other than that of groups.
See also
expected_lossExpected loss of each exposure.
kivi.calibration.calibration_tableObserved and predicted default rates by grade.
Notes
Groups are counted as in kivi.woe.woe_table. Rows follow the order of the categories when groups is categorical, such as the result of
pandas.cut, with missing values last. Otherwise they follow the order in which the groups first appear. Categories that are never observed are omitted.For the exposures \(i\) of a group, with weights \(w_i\), the columns are:
total: the number of exposures, \(\sum_i w_i\);exposure: \(\sum_i w_i \mathrm{EAD}_i\);exposure_weighted_probability: \(\sum_i w_i \mathrm{EAD}_i \mathrm{PD}_i / \sum_i w_i \mathrm{EAD}_i\);expected_loss: \(\sum_i w_i \mathrm{PD}_i \mathrm{LGD}_i \mathrm{EAD}_i\);expected_loss_rate:expected_lossdivided byexposure.
The two ratios are NaN for a group without exposure. With one LGD for all exposures,
expected_loss_rateis the LGD timesexposure_weighted_probability. The portfolio’s expected loss is the sum of theexpected_losscolumn, and its expected loss rate is that sum divided by the sum ofexposure.Examples
>>> import pandas as pd >>> from kivi.strategy import expected_loss_table >>> grades = pd.Series(["A", "A", "B", "B", "B"]) >>> probability = pd.Series([0.01, 0.03, 0.1, 0.2, 0.2]) >>> ead = pd.Series([1000.0, 3000.0, 500.0, 0.0, 1500.0]) >>> table = expected_loss_table(grades, probability, 0.5, ead) >>> table[["total", "exposure", "expected_loss", "expected_loss_rate"]] total exposure expected_loss expected_loss_rate bin A 2 4000.0 50.0 0.0125 B 3 2000.0 175.0 0.0875 >>> table["exposure_weighted_probability"] bin A 0.025 B 0.175 Name: exposure_weighted_probability, dtype: float64