Example data#

Example data for the guides: the bank marketing data of load_bank(), the synthetic loan panel, loan applications and account transactions of make_loan_panel(), make_applications() and make_transactions(), and the synthetic defaulted loans and cash flows of their workouts of make_defaults() and make_recoveries().

See Example data for their columns and how the synthetic data are simulated.

load_bank()

Load 4,521 observations from UCI Bank Marketing.

make_loan_panel(*[, n_loans, n_months, ...])

Generate a synthetic monthly panel of instalment loans.

make_applications(*[, n_applicants, ...])

Generate synthetic loan applications with an approval decision.

make_transactions(applications, *, ...[, ...])

Generate synthetic account transactions before the application dates.

make_defaults(*[, n_defaults, rng])

Generate synthetic defaulted loans with their exposures and workouts.

make_recoveries(defaults, *[, rng])

Generate synthetic cash flows of the workouts of defaulted loans.

kivi.datasets.load_bank()#

Load 4,521 observations from UCI Bank Marketing.

The y response of the original data is returned as the binary target column.

Returns:
pandas.DataFrame

Sixteen features and the integer target. A value of 1 indicates a term deposit subscription.

See also

kivi.woe.woe_table

Relate a feature to target.

make_loan_panel

Synthetic monthly history of a loan portfolio.

Notes

Bank Marketing by S. Moro, P. Rita and P. Cortez (2014) is distributed under CC BY 4.0. The bundled CSV was converted from the legacy workbook.

References

[1]

S. Moro, P. Rita and P. Cortez, “Bank Marketing”, UCI Machine Learning Repository, 2014. https://doi.org/10.24432/C5K306

Examples

>>> from kivi.datasets import load_bank
>>> data = load_bank()
>>> data.shape
(4521, 17)
>>> data["target"].value_counts().to_dict()
{0: 4000, 1: 521}
kivi.datasets.make_loan_panel(*, n_loans=5000, n_months=24, prepayment=0.0, rng=None)#

Generate a synthetic monthly panel of instalment loans.

The loans are originated over n_months months and observed at the end of every month on book until the month after the last origination month. Delinquency rolls forward when a borrower misses instalments and cures when the arrears are paid, and a loan that reaches 90 days past due stays there. The data is simulated, not drawn from a real portfolio.

Parameters:
n_loansint, default 5000

Number of loans, each assigned to an origination month at random.

n_monthsint, default 24

Number of origination months, starting with January 2024. The oldest cohort is observed for n_months months on book and the youngest for one.

prepaymentfloat, default 0.0

Monthly probability that a current loan repays its whole balance before its last instalment is due, from 0 to 1. The default, 0, gives no early repayments and the same panel as earlier releases.

rng{None, int, numpy.random.Generator}, optional

Seed or generator passed to numpy.random.default_rng. The global NumPy random state is not used, so the same seed always returns the same panel.

Returns:
pandas.DataFrame

One row per loan and month on book, sorted by loan and then by month on book, with the columns described in the Notes.

Raises:
ValueError

If n_loans or n_months is not a positive integer, prepayment is not a number from 0 to 1, or rng is not a seed or generator that numpy.random.default_rng accepts.

See also

kivi.vintage.vintage_table

Cumulative bad rates by cohort and month on book.

kivi.vintage.transition_matrix

Movements between delinquency buckets.

kivi.lifetime.survival_table

PD term structure with early repayments.

load_bank

Real data with a binary target.

Notes

The columns are:

  • loan_id: integer identifier, increasing with the origination month;

  • cohort: the origination month, a monthly pandas.Period;

  • month: the month of the observation, cohort + month_on_book;

  • month_on_book: months since origination, from 1;

  • term: contractual number of monthly instalments, 12, 24 or 36;

  • amount: amount lent;

  • balance: outstanding principal at the end of the month;

  • status: days past due at the end of the month, an ordered categorical with the categories current, 1-29, 30-59, 60-89 and 90+.

Each loan is repaid in equal monthly instalments at 1% interest a month. Its status counts the months since its oldest unpaid instalment fell due: one is 1-29, two 30-59, three 60-89 and four or more 90+. Within the term this is the number of instalments past due, and a loan that is still behind after its term keeps rolling.

Every month, a current loan misses its instalment with a probability that rises over the first six months on book and then declines, scaled by a risk factor of the loan and one of its cohort, so cohorts differ in quality. A delinquent loan pays all its arrears and becomes current, pays one instalment and keeps its status, or pays nothing and rolls to the next bucket; the chance of curing falls and that of rolling rises with the days past due. A 90+ loan makes no further payments, so its balance stays the same. A loan leaves the panel after its last instalment is paid; loans are not charged off.

With prepayment, every month, a loan that was current at the end of the month before, as every loan is at origination, and that has more instalments left than the one now due repays its whole balance with that probability, whatever its risk. Its balance is 0 in that month and it has no rows after it, so a balance of 0 before the term marks an early repayment, while a loan repaid on schedule reaches 0 at or after its term. The early repayments use random numbers of their own, drawn after all the others: with the same rng, every loan follows the same path as without prepayment until it repays early.

Examples

>>> from kivi.datasets import make_loan_panel
>>> panel = make_loan_panel(rng=0)
>>> panel.shape
(59295, 8)
>>> panel.head(3)
   loan_id   cohort    month  month_on_book  term   amount   balance   status
0        1  2024-01  2024-02              1    24  18300.0  17621.56  current
1        1  2024-01  2024-03              2    24  18300.0  16936.33  current
2        1  2024-01  2024-04              3    24  18300.0  16244.25  current
>>> panel["status"].value_counts(sort=False)
status
current    55246
1-29        1490
30-59        506
60-89        320
90+         1733
Name: count, dtype: int64

With a 2% chance a month of repaying early, 962 loans repay before their term, and 182 loans reach 90+ instead of 205:

>>> repaying = make_loan_panel(prepayment=0.02, rng=0)
>>> last = repaying.groupby("loan_id").tail(1)
>>> early = (last["balance"] == 0) & (last["month_on_book"] < last["term"])
>>> int(early.sum()), int((last["status"] == "90+").sum())
(962, 182)
kivi.datasets.make_applications(*, n_applicants=10000, include_risk=False, rng=None)#

Generate synthetic loan applications with an approval decision.

Every applicant has a few numeric and categorical features, the PD of an incumbent scorecard and a true default flag. The incumbent PD and two policy rules decide who is approved, so the data show the selection that reject inference corrects for. The data is simulated, not drawn from a real portfolio.

Parameters:
n_applicantsint, default 10000

Number of applications.

include_riskbool, default False

If True, append the hidden risk factor as the last column risk. Nothing else depends on it, so the same seed gives the same applications with and without the column.

rng{None, int, numpy.random.Generator}, optional

Seed or generator passed to numpy.random.default_rng. The global NumPy random state is not used, so the same seed always returns the same applications.

Returns:
pandas.DataFrame

One row per application with the columns described in the Notes.

Raises:
ValueError

If n_applicants is not a positive integer, include_risk is not True or False, or rng is not a seed or generator that numpy.random.default_rng accepts.

See also

kivi.reject_inference.fuzzy_augmentation

Infer the outcomes of rejected applicants.

make_loan_panel

Synthetic monthly history of a loan portfolio.

make_transactions

Synthetic account transactions of the applicants.

load_bank

Real data with a binary target.

Notes

The columns are:

  • age: age in years, from 18 to 75;

  • income: monthly income, rounded to tens;

  • debt_to_income: monthly debt payments over income, rounded to hundredths;

  • inquiries: number of credit inquiries in the last six months;

  • housing: a categorical with the categories own, mortgage and rent;

  • employment: a categorical with the categories permanent, temporary and self_employed;

  • incumbent_pd: the PD of the scorecard that decided the application, rounded to four decimals;

  • policy_decline: True if a policy rule declined the application, whatever its PD: a debt-to-income ratio above 0.6 or an age below 21;

  • approved: True if incumbent_pd is below 0.15 and no policy rule declined the application;

  • target: 1 if the applicant defaults, else 0;

  • risk: only with include_risk=True, the hidden risk factor, a standard normal draw that is not rounded.

The default probability rises with the debt-to-income ratio and the number of inquiries, falls with age and income, and is higher for renters and for temporary and self-employed applicants. A hidden risk factor that no column holds, unless include_risk is True, also raises it, and the number of inquiries rises with that factor.

The incumbent scorecard weighs the features differently, ignores housing and, like an underwriter with a credit bureau report, sees part of the hidden risk factor. Rejected applicants are therefore riskier than approved applicants with the same features, so a model fitted on the approved applicants alone underestimates their default rate.

In practice, the outcome is known only for approved applicants. Here target is also given for rejected applicants, but only to evaluate reject inference: a model must not be fitted on it, or reject inference would be pointless. The same holds for risk: it is the information that no data set holds, given only to simulate data that depend on it, as make_transactions does.

Examples

>>> from kivi.datasets import make_applications
>>> applications = make_applications(rng=0)
>>> applications.shape
(10000, 10)

The rejected applicants default three times as often as the approved ones, an outcome that only synthetic data can show:

>>> by_decision = applications.groupby(["policy_decline", "approved"])["target"]
>>> by_decision.agg(["size", "mean"]).round(3)
                         size   mean
policy_decline approved
False          False     2467  0.301
               True      6770  0.097
True           False      763  0.274
kivi.datasets.make_transactions(applications, *, application_date, n_months=12, rng=None)#

Generate synthetic account transactions before the application dates.

Every applicant has transactions on an account in each of the n_months months before the application: card purchases, cash withdrawals and instalment repayments. They depend on the hidden risk factor of the applicant and on the income, not on the outcome. Applicants at risk build up stress, withdraw more cash as the application nears and repay less, and the volumes scale with income, so that features of the transactions in time windows carry a clear but imperfect signal about target. The data is simulated, not drawn from a real portfolio.

Parameters:
applicationspandas.DataFrame

One row per applicant with the columns income, debt_to_income, incumbent_pd and risk of kivi.datasets.make_applications, called with include_risk=True, and unique index labels. Other columns, target included, are ignored.

application_date{str, date, array_like}

The date of each application. A string that names a column of applications reads the dates from that column. Any other string, a datetime.date, a numpy.datetime64 or a pandas.Timestamp is one date for every application. A Series with the index of applications, or an array_like with one date per row, gives each application its own. The dates are read as pandas.to_datetime reads them, as in kivi.vintage.delinquency_panel: a time of day is ignored and a time zone is dropped, and numbers and periods raise an error, so convert a period column with .dt.to_timestamp().

n_monthsint, default 12

Number of months before the application date that the transactions cover. The transactions of an applicant lie from n_months calendar months before the application date, counted as pandas.DateOffset counts them, up to but not including the application date.

rng{None, int, numpy.random.Generator}, optional

Seed or generator passed to numpy.random.default_rng. The global NumPy random state is not used, so the same seed always returns the same transactions.

Returns:
pandas.DataFrame

One row per transaction, sorted by applicant, in the order of applications, and then by time, with the columns described in the Notes and a RangeIndex.

Raises:
ValueError

If applications is not a DataFrame, lacks a required column (the message names include_risk when it is risk), has repeated or non-flat index labels, or holds a missing, non-numeric or out-of-range value in a required column. If application_date is not a column name, a date or dates with one value per application, holds a missing value, or is a Series with an index different from that of applications. If n_months is not a positive integer or reaches back before the year 1678, or rng is not a seed or generator that numpy.random.default_rng accepts.

See also

make_applications

Synthetic loan applications with an approval decision.

make_loan_panel

Synthetic monthly history of a loan portfolio.

Notes

The columns of the result are:

  • applicant_id: the index label of the applicant in applications;

  • timestamp: the time of the transaction, to the second, on a day before the application date;

  • amount: the amount, positive and rounded to cents;

  • kind: a categorical with the categories purchase, cash_withdrawal and repayment;

  • merchant_category: a categorical with eight categories such as grocery and travel for a purchase, missing for the other kinds.

The transactions of each month are drawn independently. In a year an applicant has on average about 25 purchases, 8 cash withdrawals and 11 repayments, 44 transactions in all. A purchase costs about 4.5% of the monthly income, a cash withdrawal about 3%, and a repayment is the instalment that income * debt_to_income implies, which varies by about 20% between applicants. Applicants with a higher income make a few more purchases and withdrawals, and purchases are more frequent in the months that start in November and December. An applicant whom the incumbent scorecard rates as riskier withdraws more cash and misses more repayments, and so does an applicant with a higher risk.

The risk also drives a stress that builds up before the application. It starts between three and nine months before the application and is strongest in the last month. Its level rises with the risk plus noise, from almost none to a bounded maximum. Under stress, the cash withdrawals are more frequent and larger, the purchases a little rarer, and a repayment is more likely to be missed, or paid up to a tenth short. The number and sum of the cash withdrawals of the last months, the number of repayments and the change of their sum from the months before therefore carry a signal about risk and, through it, about target, which the same risk raises. The incumbent scorecard sees only part of the risk, so the signal remains within bands of incumbent_pd. The noise and the other differences between applicants keep every feature far from a perfect predictor.

The transactions do not depend on target: they are drawn from the risk before the outcome, as a lender would observe them. risk is information that no lender has, so it exists only in simulated applications.

The observations that the windows end at, one row per application with its date, follow from the applications and their dates, as the examples show.

Examples

>>> import numpy as np
>>> import pandas as pd
>>> from kivi.datasets import make_applications, make_transactions
>>> applications = make_applications(n_applicants=1000, include_risk=True, rng=0)
>>> days = np.arange(1000) * 366 // 1000
>>> applications["application_date"] = pd.Timestamp("2024-01-01") + pd.to_timedelta(
...     days, unit="D"
... )
>>> transactions = make_transactions(
...     applications, application_date="application_date", rng=0
... )
>>> list(transactions.columns)
['applicant_id', 'timestamp', 'amount', 'kind', 'merchant_category']

The observations have one row per application, with its id and date, and the index of the applications, to which the features computed for them join back:

>>> observations = pd.DataFrame(
...     {
...         "applicant_id": applications.index,
...         "application_date": applications["application_date"],
...     },
...     index=applications.index,
... )
>>> observations.head(2)
   applicant_id application_date
0             0       2024-01-01
1             1       2024-01-01

The dates may also be one date for every application, or a Series with the index of the applications:

>>> transactions = make_transactions(
...     applications, application_date="2024-06-30", n_months=6, rng=0
... )
>>> transactions["timestamp"].max() < pd.Timestamp("2024-06-30")
True
kivi.datasets.make_defaults(*, n_defaults=2000, rng=None)#

Generate synthetic defaulted loans with their exposures and workouts.

Every loan defaulted between 2018 and 2024 and is secured by collateral, unsecured or a revolving line of credit. The table holds what a lender knows about the loan at default, the limit and drawn amount of the revolving lines 12 months earlier, and the date the workout ended, if it ended by the data cut-off of 30 June 2025. kivi.datasets.make_recoveries simulates the cash flows of the workouts. The data is simulated, not drawn from a real portfolio.

Parameters:
n_defaultsint, default 2000

Number of defaulted loans.

rng{None, int, numpy.random.Generator}, optional

Seed or generator passed to numpy.random.default_rng. The global NumPy random state is not used, so the same seed always returns the same loans.

Returns:
pandas.DataFrame

One row per defaulted loan, sorted by default date, with the columns described in the Notes and a RangeIndex.

Raises:
ValueError

If n_defaults is not a positive integer, or rng is not a seed or generator that numpy.random.default_rng accepts.

See also

make_recoveries

Synthetic cash flows of the workouts of these loans.

make_loan_panel

Synthetic monthly history of a loan portfolio.

Notes

The columns are:

  • loan_id: integer identifier from 1, increasing with the default date;

  • segment: a categorical with the categories secured, unsecured and revolving, about 40%, 35% and 25% of the loans;

  • default_date: the date of default, from 2018 to 2024;

  • ead: the exposure at default, the amount outstanding on that date, rounded to cents;

  • limit: the limit of a revolving line 12 months before default, the reference date of the CCF, rounded to hundreds, and missing for the other segments;

  • drawn: the amount drawn on a revolving line on the reference date, rounded to cents, and missing for the other segments;

  • collateral_value: the value of the collateral of a secured loan at default, rounded to hundreds, and 0 for the other segments;

  • discount_rate: the annual rate at which to discount the cash flows of the workout to the default date, a simulated three-month money-market rate of the month of default plus five percentage points, as paragraph 143 of EBA/GL/2017/16 prescribes;

  • closing_date: the date the workout ended, with the cure, the sale of the collateral or the write-off of what was not recovered, and missing for the workouts still open at the cut-off of 30 June 2025.

A workout lasts at least three months, the probation of a cure. About 30% of the secured loans, 10% of the unsecured loans and 15% of the revolving lines cure, after seven months on average. A liquidation lasts about two and a half years on average for secured loans, a year and a half for unsecured loans and 15 months for revolving lines, so many of the workouts that started in the last years are still open at the cut-off.

The secured loans have a median exposure of 120,000 and a median loan-to-value ratio of 75% at default, and some owe more than their collateral is worth; the unsecured loans have a median exposure of 12,000. The revolving lines have a median limit of 6,000 and are about 60% drawn on the reference date, while 3% are drawn exactly to their limit and 3% beyond it. Most then draw part of the remaining limit before default, 10% pay down part of their balance and 10% end above their limit, so that the realized CCF, (ead - drawn) / (limit - drawn), mostly lies from 0 to 1, with some values below 0 and above 1; it is undefined for the fully drawn lines.

Examples

>>> from kivi.datasets import make_defaults
>>> defaults = make_defaults(rng=0)
>>> defaults.shape
(2000, 9)
>>> defaults["segment"].value_counts(sort=False)
segment
secured      846
unsecured    665
revolving    489
Name: count, dtype: int64

The workouts of 278 loans, 13.9%, are still open at the cut-off:

>>> int(defaults["closing_date"].isna().sum())
278
kivi.datasets.make_recoveries(defaults, *, rng=None)#

Generate synthetic cash flows of the workouts of defaulted loans.

Every loan of defaults gets the recoveries, costs and cure of its workout, from its default date up to its closing date or, for a workout still open, up to the data cut-off of 30 June 2025. Secured loans mostly recover their exposure from the sale of the collateral, unsecured loans and revolving lines little of it, and cured loans all of it, so the realized LGDs are bimodal. The data is simulated, not drawn from a real portfolio.

Parameters:
defaultspandas.DataFrame

One row per defaulted loan with the columns loan_id, segment, default_date, ead, collateral_value and closing_date of kivi.datasets.make_defaults. The dates must have a datetime64 dtype; a time of day is ignored. Other columns are ignored.

rng{None, int, numpy.random.Generator}, optional

Seed or generator passed to numpy.random.default_rng. The global NumPy random state is not used, so the same seed always returns the same cash flows.

Returns:
pandas.DataFrame

One row per cash flow, sorted by loan, in the order of defaults, and then by date, with the columns described in the Notes and a RangeIndex.

Raises:
ValueError

If defaults is not a DataFrame, lacks a required column or has two columns of that name, has a missing or repeated loan_id, a segment other than secured, unsecured or revolving, an ead that is not finite and positive, a collateral_value that is not finite and non-negative, dates without a datetime64 dtype, a missing default_date, a default_date before 1678 or after the cut-off, or a closing_date before the default_date or after the cut-off. If rng is not a seed or generator that numpy.random.default_rng accepts.

See also

make_defaults

Synthetic defaulted loans with their exposures and workouts.

kivi.calibration.backtest_table

Back-test LGD estimates against realized LGDs.

Notes

The columns of the result are:

  • loan_id: the loan_id of the loan in defaults;

  • date: the date of the cash flow;

  • amount: the amount, rounded to cents, positive for recoveries and cures and negative for costs;

  • kind: a categorical with the categories recovery, cost and cure.

A cure is the amount outstanding on the closing date of a cured loan, which paragraph 135 of EBA/GL/2017/16 treats as if the borrower had repaid it on that date. The realized LGD of a loan is (ead + PV(costs) - PV(recoveries)) / ead, where recoveries include the cure and the present values discount the cash flows to the default date. Discounted with the discount_rate of make_defaults, it is close to 0 for most secured loans and for cured loans, close to 1 for unsecured loans and revolving lines that do not cure, below 0 for a few secured loans whose collateral covered the claim including the default interest, and above 1 for a few loans whose costs exceeded their recoveries.

A workout does not depend on the dates in defaults other than through its length, and short workouts are more likely to be cures:

  • a cured loan pays part of its arrears during the workout, sometimes with a small cost, and the cure follows on the closing date;

  • a secured loan that does not cure pays a little during the workout, and the collateral is sold on the closing date. The bank recovers the proceeds up to its claim, the exposure plus default interest at 4% to 10% a year, and pays 3% of the proceeds as costs of the sale and a few legal costs;

  • an unsecured loan or a revolving line that does not cure recovers about 17% or 22% of its exposure on average, in several payments, with a few collection costs.

About 5% of the loans have a legal cost up to 90 days before default, which paragraph 144 of EBA/GL/2017/16 counts in the economic loss, and 3% of the liquidations have litigation costs of 10% to 40% of the exposure. A workout still open at the cut-off has the cash flows up to the cut-off and none after it, so its LGD so far overstates the LGD it will realize.

Examples

>>> from kivi.datasets import make_defaults, make_recoveries
>>> defaults = make_defaults(rng=0)
>>> flows = make_recoveries(defaults, rng=0)
>>> flows.head(7)
   loan_id       date     amount      kind
0        1 2018-04-10    -808.71      cost
1        1 2018-11-01   -1543.90      cost
2        1 2019-05-14    -552.91      cost
3        1 2019-07-11    3595.22  recovery
4        1 2019-08-02    2012.10  recovery
5        1 2019-08-17  233970.35  recovery
6        1 2019-08-17   -7019.11      cost
>>> flows["kind"].value_counts(sort=False)
kind
recovery    6806
cost        4278
cure         413
Name: count, dtype: int64

The first loan is secured: after a few legal costs and two payments by the borrower, the collateral was sold on the closing date, 17 August 2019, at a cost of 3% of the proceeds.