Expected loss: PD, LGD and EAD
Expected loss is a probability, a share and an amount, each counted over a stated horizon. Divide write-offs by the balance instead and the answer arrives late and hides which of the three moved
In the lab's book, 281 of the 1,959 salary advances (14.3%) default, and a defaulted advance is never repaid afterwards. What share of the money lent in salary advances is lost?
Expected loss (EL) is the loss a lender should plan for on a loan or a group of loans, taken as an average over many outcomes. It has three factors:
EL = PD x LGD x EAD
| Factor | The question | Unit | Counted over |
|---|---|---|---|
| PD, probability of default | How likely is it that the borrower defaults? | a probability | a horizon you must state |
| LGD, loss given default | If it does, what share of the exposure do you not get back? | a share of EAD | what happens after default |
| EAD, exposure at default | What is owed on the day it does? | kobo | the day of default, not the day of the loan |
The economics of a loan introduced PD × LGD as the cost of risk, and decisions, limits and pricing used a band’s bad rate as PD, assumed an LGD and set EAD to the amount lent. This chapter measures all three from the book. It also uses the word “expected” strictly: the figure is a mean. A lender that expects to lose 3.5% of a book will lose more in some years and less in others, and the capital it holds against the difference is a different calculation that this chapter leaves aside.
The lab runs on the loan book of Owoleaf, the course’s fictional Lagos wallet company, at scale 1 (data1/: 3,645 loans). Northmere is the example in the prose. Every price, fee and cut-off in the book is illustrative.
Default: the event everything counts
You cannot estimate a probability of an event you have not defined. The lab’s definition is the one the earlier chapters use: a loan defaults when an instalment is still unpaid 90 days after its due date (days past due, as the loan lifecycle chapter defines it). Write-off is a different thing. It is an accounting decision taken later, and in this book 58 of the 368 defaults had been written off by the cut-off.
The Basel Committee’s guidance on expected credit losses, as search results describe it, treats a borrower as in default on either of two tests: the bank judges it unlikely to pay in full without recourse to actions such as realising security, or it is more than 90 days past due on a material obligation; “unlikeliness to pay” can identify default before an exposure becomes delinquent, with 90 days past due as the backstopas of 2026-11. A bank that uses its own internal ratings for capital must apply that reference definition of default when it estimates PD, LGD and EAD, according to the Basel Framework’s chapter on the internal ratings-based approach as a search result summarises itas of 2026-11. Both points come from search summaries, not a reading of the Framework’s text, so check the in-force version. The lab uses only the 90-day test: its book holds no judgement that a borrower is unlikely to pay. How the CBN classifies and provides for loans is the subject of the next chapter, provisioning under IFRS 9, and this chapter does not state it.
Two consequences follow. A lender that uses 90 days has to wait 90 days after the first missed instalment to see a default, so the data’s last quarter is always short of defaults it will later have. And a lender that changes its definition (say, to 60 days) changes every PD, LGD and EAD it has ever estimated. Fix the definition first, in writing.
PD: a rate over a horizon
A PD means nothing without a horizon, and lenders use two.
The 12-month PD is the probability that a loan defaults in the 12 months after the date you measure from. The lifetime PD is the probability that it defaults at any time before the loan and the 90-day wait are over. For a loan whose whole life is under a year the two are equal. For a longer one they are not.
IFRS 9, in the IFRS Foundation’s published text as a search result quotes it, defines 12-month expected credit losses as the part of lifetime expected credit losses that results from default events possible within 12 months of the reporting date; paragraph B5.5.43 adds that they are neither the lifetime losses on instruments predicted to default in the next 12 months nor the cash shortfalls predicted over those 12 monthsas of 2026-11. The next chapter stages the book on that basis. The point for now is that “12-month” counts defaults in a window and then takes the whole loss of each.
The life table
A loan book is a moving mixture of loans of different ages, so one default rate for “the book” mixes ages. The tool for age is a life table. Split each loan’s life into months on book (30 days each, here). For each month, count the loans at risk: not yet defaulted, still inside their contract plus the 90 days, and watched long enough by the data. The hazard for the month is the defaults in it divided by the loans at risk. A loan the data stops watching part-way through the month is censored: it did not default as far as you know, but you did not see all of the month. The actuarial method counts such a loan as half at risk. The chance of no default by the end of month k is the product of (1 − hazard) over the months up to k, and the PD is one minus that.
Step 2 builds the table. Three things appear in it.
The first missed instalment dominates. A default needs an instalment 90 days overdue. For a salary advance, due on day 30, that is day 120: month 4, and no month before it can hold a default. In the lab, 14.34% of salary advances default in month 4 and none can default after. For a personal loan the hazard is 2.00% in month 4 (first instalment missed), then 0.86% and 0.51% in months 5 and 6 (second and third). Of the 368 defaults, 310 missed the very first instalment.
The tail is not observed. No loan is watched for more than 289 days. A 12-month personal loan can default as late as month 15. At the cut-off only 35 of the 451 personal loans have been watched for their whole life plus 90 days. Months 10 to 15 have no loan at risk at all. The lab handles this with a rule written in the code: a month with fewer than 100 effective loans at risk is not believed, and gets the average of the believed months from month 5 on (0.68% for personal loans). Month 7 shows why: one default among 82 effective loans is a rate of 1.22%, which one more or one fewer default would move by 1.2 points. The chosen rule is an assumption. A different one gives a different lifetime PD, and a reader should be told how many months of a PD are assumed. The lab prints that count.
The horizon changes the answer. A 12-month personal loan has a 12-month PD of 7.23% and a lifetime PD of 9.13%, because months 13 to 15 hold defaults that fall after the first year. For a 9-month loan the two are the same, because its life plus 90 days is 12 months.
PD by score band
A PD for the whole product says nothing about who is riskier. Step 3 cuts each product by the bureau-score bands of credit scoring: thin file, under 640, 640 to 699, 700 to 739, 740 and above. It reports each band’s defaults and a 95% Wilson interval, a range for a rate measured on a small sample that stays inside 0% to 100% and does not collapse to zero width at zero defaults.
The salary advance bands are well measured: 740 and above has 24 defaults in 409 loans (5.9%, interval 4.0% to 8.6%) against 72 in 327 (22.0%, 17.9% to 26.8%) for under 640. The personal loan bands are not. The under-640 band has 22 loans and no defaults, and its interval runs from 0% to 14.9%. A PD of 0% for those 22 loans says only that none has defaulted yet.
The lab uses a standard remedy, credibility weighting (also called shrinkage). Each band’s rate is pulled toward its product’s rate by adding 50 pseudo-loans at the product’s rate: (defaults + 50 x product rate) / (loans + 50). A band with thousands of loans barely moves. A band with 22 loans gives its own result a weight of 22 in 72, so its rate moves more than two-thirds of the way to the product’s. The shrunk rates are divided by their loan-weighted mean to give a multiplier on the product’s monthly hazards. For the salary advance’s top band the arithmetic runs:
product rate 281 / 1,959 = 14.34%
shrunk rate, 740+ (24 + 50 x 0.1434) / (409 + 50) = 6.79%
mean of shrunk rates (loan-weighted, five bands) = 14.39%
multiplier 6.79% / 14.39% = 0.4718, shown as 0.47
band hazard in month 4 0.4718 x 14.34% = 6.77%
The 50 is a choice, not a law, and the break step at the end of the lab shows what happens at 0. The method also assumes that a band’s relative riskiness does not change with age, which the data cannot test for the longer loans.
A last point on what these PDs are. They describe one ten-month window of applications and outcomes in one fictional economy. A PD that depends on today’s conditions is point in time; one averaged over a full cycle is through the cycle. The lab’s is closer to point in time, and it cannot tell you what the next downturn does. The next chapter adds scenarios for that.
LGD: what you do not get back
Loss given default is the share of the exposure at default that is never recovered. Its recoveries come after default: collections, an agency, the sale of collateral. Money paid before default is already in the EAD and does not count again.
Step 4 measures it. Over the 368 defaulted loans, the principal received after the default date is ₦10,956.69, against an EAD of ₦13,610,311.40, so LGD is 100% for salary advances, buy-now-pay-later and SME loans, and 99.55% for personal loans. The lab’s README says agency recoveries are 0 at scale 0.1 and tiny at scale 1, and this is the tiny case: two personal loans paid something after the lender placed them with an agency, ₦37,364.00 in cash. Only ₦10,956.69 of that was principal, all of it from one loan. The other ₦26,407.31 was interest, which the lab does not count because its EAD is principal only. Real work counts accrued interest in the EAD and interest recovered in the recoveries.
A zero-recovery book is a rare thing, and it teaches by contrast. Real LGDs usually sit between 0% and 100%, and several things move them:
- Collateral. A loan secured on a vehicle or equipment recovers part of its balance by selling the asset. Secured lending and collateral is a later chapter in this module.
- Time and cost. Recoveries arrive months later and are worth less in today’s money, so an LGD discounts them (at the loan’s rate, in the usual treatment). Collection costs belong somewhere. The lab’s collection actions on loans that went on to default cost ₦1,535,044.00, which is 11.3% of their EAD. If you count that in LGD you must not also count it in operating cost, or it is charged twice.
- The cycle. Recoveries fall in a downturn, at the same time as defaults rise, so a regulator often asks for a downturn LGD. A book observed in one benign window cannot give you one.
LGD is measured on defaulted loans only, and the book has 14 defaulted personal loans and 7 SME loans. Those two LGDs rest on 21 loans.
EAD: what is owed on the day
For a loan paid out in full and repaid in instalments, the exposure at default is the principal outstanding on the day of default. It is not the amount lent, and it is not the balance the schedule would show on the day the loan is called defaulted, because a borrower who has stopped paying has stopped reducing it. Think of the sequence for a monthly loan: instalment j falls due and is missed; the loan reaches 90 days past due three months later, in month j + 3; and the exposure then is the balance before instalment j, since nothing was paid in between.
Take loan L002188, a ₦760,000 personal loan over 12 monthly instalments at 4.5% a month. Instalment 1 is ₦83,346.30 of which ₦34,200.00 is interest (4.5% of ₦760,000) and ₦49,146.30 principal. The borrower pays it and misses instalment 2. The loan defaults on day 150, and its EAD is ₦760,000.00 − ₦49,146.30 = ₦710,853.70. Step 4 prints that number and the same loan’s exposure profile: ₦760,000.00 if the default shows in month 4, falling to ₦79,757.28 in month 15. Where the borrower stops decides the EAD. Over the book’s defaulted loans, EAD is 97.2% of principal for salary advances, 66.5% for buy now pay later, 90.9% for personal loans and 49.3% for SME loans.
The schedule is not the whole story either. Some borrowers pay part of an instalment before they stop, which lowers the exposure below the schedule’s balance. The lab measures a factor: actual EAD divided by the schedule’s balance before the missed instalment. It is 0.972 for salary advances, 0.953 for buy now pay later, 0.980 for personal loans and 1.000 for SME loans, and the expected-loss code multiplies the schedule’s balance by it.
One more idea belongs here. A product with an unused limit (a credit card, an overdraft, a BNPL line) has an exposure that depends on how much more the borrower draws before defaulting. The usual device is a credit conversion factor (CCF): the share of the undrawn limit expected to be drawn by default. Every loan in this book is paid out in full at the start, so it has no undrawn amount and the book cannot estimate a CCF. A limit-based product needs its own EAD study.
Putting the three together
The lab combines the estimates loan by loan. For a loan in band b of product p:
EL = sum over months k of (chance alive at month k) x (hazard in k x multiplier of b)
x (schedule balance for month k x EAD factor of p) x LGD of p
Add the loans up by product and band and you have expected loss by segment. For the salary advance’s top band the month-4 hazard from above is 6.77%, the balance is the whole principal, the EAD factor is 0.972 and the LGD is 100%, so EL is 6.77% × 0.972 × 1.00 = 6.58% of the amount lent. Step 5 prints 6.58%. The same step shows a thin-file salary advance at 16.69% and a personal loan in the top band at 4.77% of principal. The whole book of 3,645 loans and ₦611,757,000.00 lent has a lifetime EL of ₦21,299,152.46, or 3.48%, and a 12-month EL of ₦21,206,975.40. The two differ only on the personal loans with long lives.
Check the model against what happened wherever the whole life has been seen. For salary advances the model says 13.56% of money lent and the book lost 13.13%. The model is about 3% high in relative terms because it applies a band’s default rate to every loan whatever its size, and defaulters borrow less (₦25,071 on average against ₦26,626 for the book). For the 510 finished BNPL loans it says 5.79% against 5.85% realised. This is a check on the arithmetic and on one population, and not a back-test. A proper back-test uses later data than the estimate, which is what step 6 does in outline: fit on applications before 1 April, then judge salary advances from 1 April. The model says 13.69% and the loans lost 13.28%. The split is by application date, so it is out of sample but not what a lender could have done on 1 April, when most of the early loans’ defaults were still to come. A fuller back-test, month by month, belongs to the model-risk chapter later in this module.
The same machinery gives a forward-looking figure for loans that are still running. Step 6 takes the personal and SME loans that were paying on time at the cut-off: 304 personal loans with ₦27,565,309.18 outstanding, and 158 SME loans with ₦45,958,709.76. Their remaining expected loss is ₦590,059.76 (2.14% of balance) and ₦647,071.65 (1.41%). The 12-month and the rest-of-life figures are equal because no loan in this book has more than 12 months left. The 42 loans in arrears, with ₦8,900,715.56 outstanding, are left out on purpose. A loan that has already missed an instalment is likelier to default than one that has not, and treating the two the same understates the arrears. Provisioning under IFRS 9 stages them.
Where it goes wrong
- Dividing write-offs by the balance. It is late, it mixes vintages and it hides which of PD, LGD and EAD moved.
- Using the wrong horizon. A 12-month PD for a loan with 15 months of life, or a lifetime PD in a 12-month calculation.
- Letting a small band speak. Twenty-two loans and no defaults is not a PD of zero. Show the interval, or shrink.
- Counting immature loans as good. A loan not yet watched for its whole life has not had its chance to default. The life table counts it only while it is watched.
- EAD at the amount lent. It overstates the loss on an amortising loan, and in this book it would about double the exposure of SME loans, which default at 49.3% of principal.
- A hidden assumption. Months of PD that nobody observed, a 100% LGD from a book with no collections history, a multiplier that does not change with age. State each one next to the number.
- Reading EL as a forecast of next year’s loss. It is an average. The actual loss will differ, and the capital that absorbs the difference is a separate matter.
Back at Northmere
Adunni and Adesola replace the line in the board pack with a table by product and band: PD for 12 months and for life, LGD, EAD as a share of the amount lent, EL in naira, and for each number how many loans and months it rests on. The new 12-month personal loan has too few defaults and too little age for its own PD, so the table says so, shows the interval and labels the assumed months. The board still gets one headline figure. It now comes with the sentence that says what it is the sum of.
You build one file, el.py, adding to it step by step, in labs/finance. The scripts only read the book. Do not open data1/answers/loans_truth.csv: a real lender has no file that says who was always going to default. Money is integer kobo, and every price, fee and cost is illustrative.
0. Build and check the scale 1 book once. If data1/finance.sqlite is missing, build it. It takes about 40 seconds and writes about 720 MB, so check the disk first.
cd labs/finance
python3 generate.py --scale 1 --out data1 && python3 loans.py --out data1 \
&& python3 cards.py --out data1 && python3 collect.py --out data1
python3 check.py --db data1/finance.sqliteloan book: 3645 loans, 9,771,721,819 kobo of principal outstanding; checks 7-11 run
...
OK: all invariants holdThe check takes about 30 seconds. If you also ran book3.py there is one more line for the signals tables. 3,645 loans is the scale 1 figure the modelling chapters quote.
1. Define default and load every loan. Save this as el.py. It reads the book read-only, rebuilds each loan’s payments, finds the first instalment still unpaid 90 days after its due date, and records what was owed (EAD) and what came back afterwards.
"""el.py: expected loss (PD x LGD x EAD) on the lab's loan book (data1, scale 1).
Standard library only. Money is integer kobo. Every figure is illustrative.
"""
import collections
import datetime as dt
import math
import sqlite3
DB = "data1/finance.sqlite"
CUT_OFF = dt.date(2026, 10, 28) # the loan book is observed to here
DEFAULT_DPD = 90 # default = an instalment still unpaid 90 days after its due date
MONTH = 30 # a "month on book" is 30 days
MIN_EFFECTIVE = 100 # a month's default rate needs this many loans at risk to be believed
SHRINK_K = 50 # credibility weight: a band's rate counts as this many loans of the product rate
PRODUCTS = ("SAL", "BNPL", "PL", "SME")
BANDS = ("thin file", "1: under 640", "2: 640-699", "3: 700-739", "4: 740+")
def day(text):
return dt.date.fromisoformat(text[:10])
def band_of(hit, score):
if not hit:
return "thin file"
return "1: under 640" if score < 640 else "2: 640-699" if score < 700 else "3: 700-739" if score < 740 else "4: 740+"
def naira(kobo):
sign = "-" if kobo < 0 else ""
kobo = abs(kobo)
return f"{sign}₦{kobo // 100:,}.{kobo % 100:02d}"
def load(db_path=DB):
"""One dict per loan: what was known at application, its instalments and, if it defaulted, when,
what was owed (EAD) and what came back afterwards."""
db = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
sched = collections.defaultdict(list)
for loan_id, n, due, principal, total in db.execute(
"SELECT loan_id, instalment, due_date, principal_kobo, total_kobo FROM schedule ORDER BY loan_id, instalment"):
sched[loan_id].append((n, day(due), principal, total))
pays = collections.defaultdict(list)
for loan_id, n, when, amount, late_fee, principal in db.execute(
"SELECT loan_id, instalment, paid_at, amount_kobo, late_fee_kobo, principal_kobo FROM repayments"):
pays[loan_id].append((day(when), n, amount - late_fee, principal)) # late fees are not part of an instalment
loans = []
for (loan_id, product, tenor, principal, disbursed, status, applied, hit, score) in db.execute("""
SELECT l.id, l.product, l.instalments, l.principal_kobo, l.disbursed_at, l.status,
a.applied_at, b.hit, b.score
FROM loans l JOIN applications a ON a.id = l.application_id
JOIN bureau_reports b ON b.id = a.bureau_report_id ORDER BY l.id"""):
start = day(disbursed)
rows = [(n, (due - start).days, p, total, due) for n, due, p, total in sched[loan_id]]
# the first instalment to be 90 days overdue and still unpaid
default_date, missed = None, None
for n, offset, p, total, due in rows:
check = due + dt.timedelta(days=DEFAULT_DPD)
if check <= CUT_OFF and sum(a for w, k, a, pr in pays[loan_id] if k == n and w <= check) < total:
if default_date is None or check < default_date:
default_date, missed = check, n
loan = dict(id=loan_id, product=product, tenor=tenor, principal=principal, start=start, status=status,
applied=applied, band=band_of(hit, score), instalments=[(n, o, p) for n, o, p, t, d in rows],
observed=(CUT_OFF - start).days, horizon=rows[-1][1] + DEFAULT_DPD,
default_day=None, missed=None, ead=0, recovered=0, contract_ead=0)
loan["horizon_m"] = math.ceil(loan["horizon"] / MONTH)
if default_date:
paid_before = sum(pr for w, k, a, pr in pays[loan_id] if w <= default_date)
loan.update(default_day=(default_date - start).days, missed=missed, ead=principal - paid_before,
recovered=sum(pr for w, k, a, pr in pays[loan_id] if w > default_date),
contract_ead=principal - sum(p for n, o, p in loan["instalments"] if n < missed),
default_date=default_date)
loans.append(loan)
return loans
def show_defaults(loans):
print(f"{'':6}{'loans':>6}{'defaulted':>10}{'rate':>7}{'watched to the end':>20} status default or written off")
for p in PRODUCTS:
sel = [x for x in loans if x["product"] == p]
d = sum(x["default_day"] is not None for x in sel)
full = sum(x["horizon"] <= x["observed"] for x in sel)
s = sum(x["status"] in ("default", "written_off") for x in sel)
print(f"{p:<6}{len(sel):>6}{d:>10}{d / len(sel):>7.1%}{full:>20} {s}")
total = sum(x["default_day"] is not None for x in loans)
status = sum(x["status"] in ("default", "written_off") for x in loans)
print(f"all defaults {total}; loans with status default or written_off {status}")
worked = next(x for x in loans if x["id"] == "L002188")
print(f"\nworked loan {worked['id']}: {naira(worked['principal'])} {worked['tenor']} instalments, "
f"defaulted on day {worked['default_day']} after missing instalment {worked['missed']}")
print(f" EAD {naira(worked['ead'])} = {naira(worked['principal'])} less instalment 1's principal "
f"{naira(worked['instalments'][0][2])}; principal recovered after default {naira(worked['recovered'])}")python3 -c "import el; el.show_defaults(el.load())" loans defaulted rate watched to the end status default or written off
SAL 1959 281 14.3% 1959 281
BNPL 766 66 8.6% 510 66
PL 451 14 3.1% 35 14
SME 469 7 1.5% 71 7
all defaults 368; loans with status default or written_off 368
worked loan L002188: ₦760,000.00 12 instalments, defaulted on day 150 after missing instalment 2
EAD ₦710,853.70 = ₦760,000.00 less instalment 1's principal ₦49,146.30; principal recovered after default ₦0.00The 368 defaults match the 368 loans with status default or written_off, so the definition agrees with the book’s own. Only the salary advances have all been watched for their whole life plus 90 days; 35 of 451 personal loans have. L002188 is the chapter’s worked loan: its EAD is ₦760,000.00 less ₦49,146.30.
2. PD: the life table. Add this to the end of el.py. life_table counts loans at risk, censored loans and defaults for each month on book. hazards replaces a month that has too few loans with an assumed rate, and show_life_tables prints both and the 12-month and lifetime PD by tenor.
# ---- PD: a life table by month on book ------------------------------------------------------------
def life_table(loans, product):
"""Per month on book k: loans at risk, loans cut off by the data's end, defaults, hazard.
A loan is at risk in month k if it has not defaulted, its contract plus 90 days reaches into the month and
the book has watched it that long. A loan watched for only part of the month counts half (actuarial)."""
sel = [x for x in loans if x["product"] == product]
rows = []
for k in range(1, max(x["horizon_m"] for x in sel) + 1):
lo, hi = MONTH * (k - 1), MONTH * k
at_risk = [x for x in sel if x["horizon"] > lo and x["observed"] > lo
and (x["default_day"] is None or x["default_day"] > lo)]
events = [x for x in at_risk if x["default_day"] is not None and x["default_day"] <= hi]
cut = [x for x in at_risk if x["default_day"] is None and x["observed"] < min(hi, x["horizon"])]
eff = len(at_risk) - 0.5 * len(cut)
rows.append(dict(k=k, at_risk=len(at_risk), cut=len(cut), eff=eff, events=len(events),
h=len(events) / eff if eff else 0.0))
return rows
def hazards(loans):
"""{product: {month: (hazard, 'observed' or 'assumed')}}. A month with fewer than MIN_EFFECTIVE loans at risk
is not believed: it gets the average of the believed months from month 5 on (month 4 is the first instalment
missed, a different event)."""
out = {}
for p in PRODUCTS:
table = life_table(loans, p)
believed = [r["h"] for r in table if r["eff"] >= MIN_EFFECTIVE and r["k"] >= 5]
fill = sum(believed) / len(believed) if believed else 0.0
out[p] = {r["k"]: (r["h"], "observed") if r["eff"] >= MIN_EFFECTIVE else (fill, "assumed") for r in table}
return out
def survive(hz, upto, scale=1.0):
"""Chance of no default in months 1..upto: product of (1 - hazard)."""
s = 1.0
for k in range(1, upto + 1):
if k in hz:
s *= 1 - min(0.99, scale * hz[k][0])
return s
def show_life_tables(loans, hz):
for p in PRODUCTS:
print(f"{p}: month on book, loans at risk (cut off by the data's end), defaults, default rate in the month")
for r in life_table(loans, p):
if r["events"] or r["k"] >= 4:
h, how = hz[p][r["k"]]
print(f" month {r['k']:>2} at risk {r['at_risk']:>5} ({r['cut']:>3} cut off) effective {r['eff']:>7.1f} "
f"defaults {r['events']:>3} rate {r['h']:>6.2%} used {h:>6.2%} ({how})")
print("\n12-month and lifetime PD of a loan, by product and tenor (all bands pooled)")
print(f" {'':6}{'tenor':>6}{'life, months':>13}{'PD 12m':>8}{'PD life':>9}{'months assumed':>16}")
for p, tenors in (("SAL", (1,)), ("BNPL", (4,)), ("PL", (3, 6, 9, 12)), ("SME", (3, 6))):
for t in tenors:
x = next(y for y in loans if y["product"] == p and y["tenor"] == t)
h = x["horizon_m"]
assumed = sum(1 for k in range(1, h + 1) if hz[p][k][1] == "assumed" and hz[p][k][0] > 0)
print(f" {p:<6}{t:>6}{h:>13}{1 - survive(hz[p], min(12, h)):>8.2%}{1 - survive(hz[p], h):>9.2%}{assumed:>16}")python3 -c "import el; l = el.load(); el.show_life_tables(l, el.hazards(l))"SAL: month on book, loans at risk (cut off by the data's end), defaults, default rate in the month
month 4 at risk 1959 ( 0 cut off) effective 1959.0 defaults 281 rate 14.34% used 14.34% (observed)
BNPL: month on book, loans at risk (cut off by the data's end), defaults, default rate in the month
month 4 at risk 766 ( 0 cut off) effective 766.0 defaults 40 rate 5.22% used 5.22% (observed)
month 5 at risk 726 (242 cut off) effective 605.0 defaults 26 rate 4.30% used 4.30% (observed)
PL: month on book, loans at risk (cut off by the data's end), defaults, default rate in the month
month 4 at risk 451 ( 0 cut off) effective 451.0 defaults 9 rate 2.00% used 2.00% (observed)
month 5 at risk 442 (186 cut off) effective 349.0 defaults 3 rate 0.86% used 0.86% (observed)
month 6 at risk 247 (101 cut off) effective 196.5 defaults 1 rate 0.51% used 0.51% (observed)
month 7 at risk 114 ( 64 cut off) effective 82.0 defaults 1 rate 1.22% used 0.68% (assumed)
month 8 at risk 47 ( 33 cut off) effective 30.5 defaults 0 rate 0.00% used 0.68% (assumed)
month 9 at risk 14 ( 13 cut off) effective 7.5 defaults 0 rate 0.00% used 0.68% (assumed)
month 10 at risk 0 ( 0 cut off) effective 0.0 defaults 0 rate 0.00% used 0.68% (assumed)
month 11 at risk 0 ( 0 cut off) effective 0.0 defaults 0 rate 0.00% used 0.68% (assumed)
month 12 at risk 0 ( 0 cut off) effective 0.0 defaults 0 rate 0.00% used 0.68% (assumed)
month 13 at risk 0 ( 0 cut off) effective 0.0 defaults 0 rate 0.00% used 0.68% (assumed)
month 14 at risk 0 ( 0 cut off) effective 0.0 defaults 0 rate 0.00% used 0.68% (assumed)
month 15 at risk 0 ( 0 cut off) effective 0.0 defaults 0 rate 0.00% used 0.68% (assumed)
SME: month on book, loans at risk (cut off by the data's end), defaults, default rate in the month
month 4 at risk 469 ( 0 cut off) effective 469.0 defaults 1 rate 0.21% used 0.21% (observed)
month 5 at risk 468 (210 cut off) effective 363.0 defaults 2 rate 0.55% used 0.55% (observed)
month 6 at risk 252 (112 cut off) effective 196.0 defaults 3 rate 1.53% used 1.53% (observed)
month 7 at risk 69 ( 35 cut off) effective 51.5 defaults 0 rate 0.00% used 1.04% (assumed)
month 8 at risk 33 ( 22 cut off) effective 22.0 defaults 0 rate 0.00% used 1.04% (assumed)
month 9 at risk 11 ( 7 cut off) effective 7.5 defaults 1 rate 13.33% used 1.04% (assumed)
12-month and lifetime PD of a loan, by product and tenor (all bands pooled)
tenor life, months PD 12m PD life months assumed
SAL 1 4 14.34% 14.34% 0
BNPL 4 5 9.30% 9.30% 0
PL 3 6 3.33% 3.33% 0
PL 6 9 5.30% 5.30% 3
PL 9 12 7.23% 7.23% 6
PL 12 15 7.23% 9.13% 9
SME 3 6 2.28% 2.28% 0
SME 6 9 5.30% 5.30% 3Salary advances default only in month 4 (day 120). Personal loans start at 2.00% in month 4 and fall. Months 7 and later are assumed for personal loans (0.68%) and months 7 to 9 for SME (1.04%): month 7 had one default in 82 effective personal loans, too few to believe. The last block is the horizon at work: a 12-month personal loan has a 12-month PD of 7.23% and a lifetime PD of 9.13%, and the last column counts the assumed months behind each figure.
3. PD by score band. Add this. It prints defaults by band, a Wilson interval and the shrunk multiplier.
# ---- PD by score band: counts, a confidence interval, and a shrunk relative risk -----------------------
def wilson(d, n, z=1.96):
"""95% Wilson interval for a rate d / n."""
p = d / n
centre = (p + z * z / (2 * n)) / (1 + z * z / n)
half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
return centre - half, centre + half
def relative_risk(loans):
"""{(product, band): multiplier on the product's monthly default rates}. The band's observed rate is pulled
toward the product's rate by SHRINK_K pseudo-loans, then divided by the loan-weighted mean, so the
multipliers average to 1 over the product."""
rr = {}
for p in PRODUCTS:
sel = [x for x in loans if x["product"] == p]
overall = sum(x["default_day"] is not None for x in sel) / len(sel)
shrunk = {}
for b in BANDS:
part = [x for x in sel if x["band"] == b]
if part:
d = sum(x["default_day"] is not None for x in part)
shrunk[b] = (len(part), (d + SHRINK_K * overall) / (len(part) + SHRINK_K))
mean = sum(n * r for n, r in shrunk.values()) / len(sel)
for b, (n, r) in shrunk.items():
rr[(p, b)] = r / mean
return rr
def show_bands(loans, rr):
print(f"{'product':<8}{'band':<14}{'loans':>6}{'defaults':>9}{'rate':>7}{'95% interval':>16}{'multiplier':>12}")
for p in PRODUCTS:
for b in BANDS:
part = [x for x in loans if x["product"] == p and x["band"] == b]
if not part:
continue
d = sum(x["default_day"] is not None for x in part)
lo, hi = wilson(d, len(part))
print(f"{p:<8}{b:<14}{len(part):>6}{d:>9}{d / len(part):>7.1%}{f'{lo:.1%} to {hi:.1%}':>16}{rr[(p, b)]:>12.2f}")python3 -c "import el; l = el.load(); el.show_bands(l, el.relative_risk(l))"product band loans defaults rate 95% interval multiplier
SAL thin file 578 101 17.5% 14.6% to 20.8% 1.20
SAL 1: under 640 327 72 22.0% 17.9% to 26.8% 1.46
SAL 2: 640-699 416 66 15.9% 12.7% to 19.7% 1.09
SAL 3: 700-739 229 18 7.9% 5.0% to 12.1% 0.63
SAL 4: 740+ 409 24 5.9% 4.0% to 8.6% 0.47
BNPL thin file 182 19 10.4% 6.8% to 15.7% 1.17
BNPL 1: under 640 121 14 11.6% 7.0% to 18.5% 1.25
BNPL 2: 640-699 176 18 10.2% 6.6% to 15.6% 1.15
BNPL 3: 700-739 87 7 8.0% 4.0% to 15.7% 0.96
BNPL 4: 740+ 200 8 4.0% 2.0% to 7.7% 0.57
PL thin file 90 4 4.4% 1.7% to 10.9% 1.26
PL 1: under 640 22 0 0.0% 0.0% to 14.9% 0.69
PL 2: 640-699 122 3 2.5% 0.8% to 7.0% 0.84
PL 3: 700-739 62 2 3.2% 0.9% to 11.0% 1.01
PL 4: 740+ 155 5 3.2% 1.4% to 7.3% 1.02
SME 1: under 640 33 1 3.0% 0.5% to 15.3% 1.52
SME 2: 640-699 90 3 3.3% 1.1% to 9.3% 1.93
SME 3: 700-739 83 1 1.2% 0.2% to 6.5% 0.95
SME 4: 740+ 263 2 0.8% 0.2% to 2.7% 0.63Check the salary advance’s 740+ row by hand against the chapter: 24 defaults in 409 loans is 5.9%; shrunk to 6.79% and divided by the mean 14.39% gives 0.47. The personal-loan band under 640 has 22 loans, no defaults and an interval from 0% to 14.9%. Its shrunk rate is 50 x 3.10% / 72 = 2.16%, and its multiplier of 0.69 is that rate over the mean of 3.15%. Shrinking did not invent the 0.69: it pulled the band’s raw 0% most of the way back toward the product’s rate, and what is left is the weak evidence of 22 clean loans.
4. LGD and EAD. Add this. It measures recoveries after default, the EAD factor, the collection cost and the exposure profile of L002188.
# ---- LGD and EAD -----------------------------------------------------------------------------------
def lgd_by_product(loans):
"""LGD = 1 - principal recovered after default / EAD, over the product's defaulted loans (EAD-weighted)."""
out = {}
for p in PRODUCTS:
bad = [x for x in loans if x["product"] == p and x["default_day"] is not None]
out[p] = 1 - sum(x["recovered"] for x in bad) / sum(x["ead"] for x in bad)
return out
def ead_factor_by_product(loans):
"""Actual EAD at default / the schedule's balance before the missed instalment. Below 1 when borrowers
paid part of an instalment before they stopped."""
out = {}
for p in PRODUCTS:
bad = [x for x in loans if x["product"] == p and x["default_day"] is not None]
out[p] = sum(x["ead"] for x in bad) / sum(x["contract_ead"] for x in bad)
return out
def contract_ead_by_month(loan):
"""{month k: schedule balance before the instalment whose default would show in month k}. When two
instalments map to one month (BNPL is fortnightly) the month gets their average."""
by_month = collections.defaultdict(list)
balance = loan["principal"]
for n, offset, principal in loan["instalments"]:
by_month[math.ceil((offset + DEFAULT_DPD) / MONTH)].append(balance)
balance -= principal
return {k: sum(v) / len(v) for k, v in by_month.items()}
def show_lgd_ead(loans, db_path=DB):
lgd, factor = lgd_by_product(loans), ead_factor_by_product(loans)
db = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
defaulted = {x["id"] for x in loans if x["default_day"] is not None}
cost = collections.defaultdict(int)
for loan_id, product, c in db.execute(
"SELECT l.id, l.product, c.cost_kobo FROM collection_actions c JOIN loans l ON l.id = c.loan_id"):
if loan_id in defaulted:
cost[product] += c
print(f"{'':6}{'defaulted':>10}{'EAD':>18}{'recovered':>16}{'LGD':>8}{'EAD / schedule':>16}{'collection cost':>17}")
for p in PRODUCTS:
bad = [x for x in loans if x["product"] == p and x["default_day"] is not None]
ead, rec = sum(x["ead"] for x in bad), sum(x["recovered"] for x in bad)
print(f"{p:<6}{len(bad):>10}{naira(ead):>18}{naira(rec):>16}{lgd[p]:>8.2%}{factor[p]:>16.3f}{naira(cost[p]):>17}")
ead = sum(x["ead"] for x in loans if x["default_day"] is not None)
print(f"all: EAD {naira(ead)}, recovered principal {naira(sum(x['recovered'] for x in loans))}, "
f"collection cost on these loans {naira(sum(cost.values()))} = {sum(cost.values()) / ead:.1%} of EAD")
placed = db.execute("SELECT COUNT(*), SUM(recovered_kobo > 0), SUM(recovered_kobo) FROM placements").fetchone()
print(f"placements: {placed[0]}, with a recovery {placed[1]}, cash received after placement {naira(placed[2])}")
def show_ead_profile(loans, loan_id="L002188"):
x = next(y for y in loans if y["id"] == loan_id)
profile = contract_ead_by_month(x)
print(f"{loan_id}: {naira(x['principal'])}, {x['tenor']} instalments; contract EAD if a default shows in month k "
f"(balance before the instalment missed three months earlier)")
for k in sorted(profile):
print(f" month {k:>2} {naira(round(profile[k])):>16} {profile[k] / x['principal']:>6.1%} of principal")
for p in PRODUCTS:
bad = [y for y in loans if y["product"] == p and y["default_day"] is not None]
print(f"{p:<5} defaulted loans: EAD / principal {sum(y['ead'] for y in bad) / sum(y['principal'] for y in bad):.1%}")python3 -c "import el; l = el.load(); el.show_lgd_ead(l); print(); el.show_ead_profile(l)" defaulted EAD recovered LGD EAD / schedule collection cost
SAL 281 ₦6,848,659.00 ₦0.00 100.00% 0.972 ₦1,170,270.00
BNPL 66 ₦1,775,883.00 ₦0.00 100.00% 0.953 ₦279,834.00
PL 14 ₦2,411,684.64 ₦10,956.69 99.55% 0.980 ₦52,680.00
SME 7 ₦2,574,084.76 ₦0.00 100.00% 1.000 ₦32,260.00
all: EAD ₦13,610,311.40, recovered principal ₦10,956.69, collection cost on these loans ₦1,535,044.00 = 11.3% of EAD
placements: 368, with a recovery 2, cash received after placement ₦37,364.00
L002188: ₦760,000.00, 12 instalments; contract EAD if a default shows in month k (balance before the instalment missed three months earlier)
month 4 ₦760,000.00 100.0% of principal
month 5 ₦710,853.70 93.5% of principal
month 6 ₦659,495.82 86.8% of principal
month 7 ₦605,826.83 79.7% of principal
month 8 ₦549,742.74 72.3% of principal
month 9 ₦491,134.86 64.6% of principal
month 10 ₦429,889.63 56.6% of principal
month 11 ₦365,888.36 48.1% of principal
month 12 ₦299,007.04 39.3% of principal
month 13 ₦229,116.06 30.1% of principal
month 14 ₦156,079.98 20.5% of principal
month 15 ₦79,757.28 10.5% of principal
SAL defaulted loans: EAD / principal 97.2%
BNPL defaulted loans: EAD / principal 66.5%
PL defaulted loans: EAD / principal 90.9%
SME defaulted loans: EAD / principal 49.3%Personal loans recover ₦10,956.69 of principal on an EAD of ₦2,411,684.64: LGD 99.55%. The other three products recover nothing. Two of the 368 placements brought cash back (₦37,364.00 in all), and part of it was interest. L002188 at month 5 is ₦710,853.70, the EAD you worked out by hand.
5. Expected loss by segment, and a check. Add this. fit gathers every estimate, loan_el sums a loan’s expected loss month by month, and show_el adds up segments. show_check compares the model with the loss that happened where the whole life has been seen.
# ---- expected loss: PD x LGD x EAD, month by month ---------------------------------------------------
def fit(loans):
"""Everything estimated from a set of loans: monthly hazards, band multipliers, LGD, EAD factor."""
return dict(hz=hazards(loans), rr=relative_risk(loans), lgd=lgd_by_product(loans),
factor=ead_factor_by_product(loans))
def loan_el(model, x, months=None, first=1):
"""(PD, expected loss in kobo) for one loan over months first..months (default: to the end of its life).
EL = sum over months of P(survive to the month) x P(default in it) x EAD x LGD.
Survival is counted from month `first`, so a loan already part-way through its life starts from there."""
p, b = x["product"], x["band"]
hz, scale = model["hz"][p], model["rr"][(p, b)]
profile = contract_ead_by_month(x)
last = x["horizon_m"] if months is None else min(months, x["horizon_m"])
alive, pd_, el = 1.0, 0.0, 0.0
for k in range(first, last + 1):
h = min(0.99, scale * hz[k][0]) if k in hz else 0.0
if k in profile:
pd_ += alive * h
el += alive * h * profile[k] * model["factor"][p] * model["lgd"][p]
alive *= 1 - h
return pd_, el
def segment_el(model, loans, horizon=None):
"""{(product, band): n, principal, mean PD, EL in kobo}, summing each loan's own EL."""
seg = collections.defaultdict(lambda: [0, 0, 0.0, 0])
for x in loans:
pd_, el = loan_el(model, x, horizon)
s = seg[(x["product"], x["band"])]
s[0] += 1
s[1] += x["principal"]
s[2] += pd_
s[3] += round(el)
return seg
def show_el(model, loans):
life, year = segment_el(model, loans), segment_el(model, loans, 12)
print(f"{'product':<8}{'band':<14}{'loans':>6}{'lent':>17}{'PD 12m':>8}{'PD life':>9}{'LGD':>7}"
f"{'EL 12m':>16}{'EL life':>16}{'EL life %':>10}")
tot = [0, 0, 0, 0]
for p in PRODUCTS:
sub = [0, 0, 0, 0]
for b in BANDS:
if (p, b) not in life:
continue
n, principal, pd_life, el_life = life[(p, b)]
_, _, pd_year, el_year = year[(p, b)]
print(f"{p:<8}{b:<14}{n:>6}{naira(principal):>17}{pd_year / n:>8.1%}{pd_life / n:>9.1%}{model['lgd'][p]:>7.1%}"
f"{naira(el_year):>16}{naira(el_life):>16}{el_life / principal:>10.2%}")
for i, v in enumerate((n, principal, el_year, el_life)):
sub[i] += v
print(f"{p + ' all':<22}{sub[0]:>6}{naira(sub[1]):>17}{'':>8}{'':>9}{'':>7}{naira(sub[2]):>16}{naira(sub[3]):>16}"
f"{sub[3] / sub[1]:>10.2%}")
for i in range(4):
tot[i] += sub[i]
print(f"{'book':<22}{tot[0]:>6}{naira(tot[1]):>17}{'':>24}{naira(tot[2]):>16}{naira(tot[3]):>16}{tot[3] / tot[1]:>10.2%}")
def show_check(model, loans):
"""Where the whole life is observed (SAL, and BNPL's finished loans) set the model's EL against the loss that happened."""
print(f"{'':20}{'loans':>6}{'modelled EL':>15}{'realised loss':>15}{'modelled %':>12}{'realised %':>12}")
for label, sel in (("SAL, all", [x for x in loans if x["product"] == "SAL"]),
("BNPL, finished", [x for x in loans if x["product"] == "BNPL" and x["horizon"] <= x["observed"]])):
el = sum(round(loan_el(model, x)[1]) for x in sel)
lent = sum(x["principal"] for x in sel)
lost = sum(x["ead"] - x["recovered"] for x in sel if x["default_day"] is not None)
print(f"{label:<20}{len(sel):>6}{naira(el):>15}{naira(lost):>15}{el / lent:>12.2%}{lost / lent:>12.2%}")python3 -c "import el; l = el.load(); m = el.fit(l); el.show_el(m, l); print(); el.show_check(m, l)"product band loans lent PD 12m PD life LGD EL 12m EL life EL life %
SAL thin file 578 ₦13,405,000.00 17.2% 17.2% 100.0% ₦2,236,762.50 ₦2,236,762.50 16.69%
SAL 1: under 640 327 ₦8,646,000.00 20.9% 20.9% 100.0% ₦1,758,909.01 ₦1,758,909.01 20.34%
SAL 2: 640-699 416 ₦11,090,000.00 15.6% 15.6% 100.0% ₦1,686,896.91 ₦1,686,896.91 15.21%
SAL 3: 700-739 229 ₦6,461,000.00 9.0% 9.0% 100.0% ₦564,691.49 ₦564,691.49 8.74%
SAL 4: 740+ 409 ₦12,559,000.00 6.8% 6.8% 100.0% ₦826,238.09 ₦826,238.09 6.58%
SAL all 1959 ₦52,161,000.00 ₦7,073,498.00 ₦7,073,498.00 13.56%
BNPL thin file 182 ₦6,397,000.00 10.9% 10.9% 100.0% ₦434,704.60 ₦434,704.60 6.80%
BNPL 1: under 640 121 ₦5,344,000.00 11.5% 11.5% 100.0% ₦386,589.44 ₦386,589.44 7.23%
BNPL 2: 640-699 176 ₦9,289,000.00 10.7% 10.7% 100.0% ₦620,362.71 ₦620,362.71 6.68%
BNPL 3: 700-739 87 ₦4,275,000.00 9.0% 9.0% 100.0% ₦239,364.46 ₦239,364.46 5.60%
BNPL 4: 740+ 200 ₦10,679,000.00 5.4% 5.4% 100.0% ₦358,557.36 ₦358,557.36 3.36%
BNPL all 766 ₦35,984,000.00 ₦2,039,578.57 ₦2,039,578.57 5.67%
PL thin file 90 ₦4,500,000.00 7.7% 8.5% 99.5% ₦247,330.32 ₦254,546.50 5.66%
PL 1: under 640 22 ₦5,073,000.00 4.0% 4.3% 99.5% ₦151,663.98 ₦155,933.31 3.07%
PL 2: 640-699 122 ₦21,769,000.00 4.9% 5.2% 99.5% ₦766,775.46 ₦783,596.80 3.60%
PL 3: 700-739 62 ₦12,335,000.00 6.2% 6.8% 99.5% ₦572,967.11 ₦590,091.50 4.78%
PL 4: 740+ 155 ₦30,391,000.00 6.1% 6.7% 99.5% ₦1,403,341.56 ₦1,450,087.38 4.77%
PL all 451 ₦74,068,000.00 ₦3,142,078.43 ₦3,234,255.49 4.37%
SME 1: under 640 33 ₦28,163,000.00 6.0% 6.0% 100.0% ₦971,020.89 ₦971,020.89 3.45%
SME 2: 640-699 90 ₦75,015,000.00 7.3% 7.3% 100.0% ₦2,998,471.53 ₦2,998,471.53 4.00%
SME 3: 700-739 83 ₦71,141,000.00 3.5% 3.5% 100.0% ₦1,342,715.44 ₦1,342,715.44 1.89%
SME 4: 740+ 263 ₦275,225,000.00 2.4% 2.4% 100.0% ₦3,639,612.54 ₦3,639,612.54 1.32%
SME all 469 ₦449,544,000.00 ₦8,951,820.40 ₦8,951,820.40 1.99%
book 3645 ₦611,757,000.00 ₦21,206,975.40 ₦21,299,152.46 3.48%
loans modelled EL realised loss modelled % realised %
SAL, all 1959 ₦7,073,498.00 ₦6,848,659.00 13.56% 13.13%
BNPL, finished 510 ₦1,425,032.66 ₦1,441,630.00 5.79% 5.85%For SAL 740+, 6.77% hazard × 0.972 × 100% = 6.58%, which is the EL life % on the row. The book’s lifetime EL is ₦21,299,152.46 on ₦611,757,000.00 lent (3.48%). The salary advance model is 13.56% against 13.13% realised: defaulters borrowed less than the average. BNPL is 5.79% against 5.85%.
6. The open book, an out-of-time check, and the whole run. Add this to the end. main runs every step in order, so python3 el.py prints the lot.
def show_open_book(model, loans, db_path=DB):
"""Loans still running and paying on time at the cut-off: what each could lose from here. The first month
in which one could reach 90 days past due is the month after its next instalment's due date plus 90 days."""
print(f"{'':6}{'loans':>6}{'balance now':>18}{'EL next 12 months':>19}{'EL rest of life':>17}{'% of balance':>14}")
for p in ("PL", "SME"):
sel = [x for x in loans if x["product"] == p and x["status"] == "current"]
balance = el12 = el_life = 0
for x in sel:
due_now = sum(1 for n, o, pr in x["instalments"] if o <= x["observed"])
balance += x["principal"] - sum(pr for n, o, pr in x["instalments"] if o <= x["observed"])
first = due_now + 4 # instalment due_now + 1, plus 90 days
ahead = (x["observed"] + 360) // MONTH # defaults that show within 12 months of the cut-off
el12 += round(loan_el(model, x, ahead, first)[1])
el_life += round(loan_el(model, x, None, first)[1])
print(f"{p:<6}{len(sel):>6}{naira(balance):>18}{naira(el12):>19}{naira(el_life):>17}{el_life / balance:>14.2%}")
db = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
n, bal = db.execute("SELECT COUNT(*), SUM(outstanding_principal_kobo) FROM loans WHERE status = 'arrears'").fetchone()
print(f"left out: {n} loans in arrears with {naira(bal)} outstanding (they are not 'paying on time': the next chapter stages them)")
def show_first_quarter(loans):
"""Estimate on applications before April only; judge on salary advances applied for from April."""
early = [x for x in loans if x["applied"] < "2026-04-01"]
later = [x for x in loans if x["applied"] >= "2026-04-01" and x["product"] == "SAL"]
print(f"estimated on {len(early)} loans applied for before 1 April; judged on {len(later)} salary advances from 1 April")
print(f"{'model fitted on':<22}{'modelled EL':>16}{'realised loss':>16}{'modelled %':>12}{'realised %':>12}")
lent = sum(x["principal"] for x in later)
lost = sum(x["ead"] - x["recovered"] for x in later if x["default_day"] is not None)
for label, fit_on in (("before 1 April", early), ("all loans", loans)):
m = fit(fit_on)
el = sum(round(loan_el(m, x)[1]) for x in later)
print(f"{label:<22}{naira(el):>16}{naira(lost):>16}{el / lent:>12.2%}{lost / lent:>12.2%}")
def main():
loans = load()
print("== 1. defaults ==")
show_defaults(loans)
hz = hazards(loans)
print("\n== 2. PD: the life table ==")
show_life_tables(loans, hz)
rr = relative_risk(loans)
print("\n== 3. PD by score band ==")
show_bands(loans, rr)
print("\n== 4. LGD and EAD ==")
show_lgd_ead(loans)
print()
show_ead_profile(loans)
model = fit(loans)
print("\n== 5. expected loss at origination, by segment ==")
show_el(model, loans)
print()
show_check(model, loans)
print("\n== 6. the open book, and an out-of-time check ==")
show_open_book(model, loans)
print()
show_first_quarter(loans)
if __name__ == "__main__":
main()python3 -c "import el; l = el.load(); m = el.fit(l); el.show_open_book(m, l); print(); el.show_first_quarter(l)"
python3 el.py | wc -l loans balance now EL next 12 months EL rest of life % of balance
PL 304 ₦27,565,309.18 ₦590,059.76 ₦590,059.76 2.14%
SME 158 ₦45,958,709.76 ₦647,071.65 ₦647,071.65 1.41%
left out: 42 loans in arrears with ₦8,900,715.56 outstanding (they are not 'paying on time': the next chapter stages them)
estimated on 543 loans applied for before 1 April; judged on 1658 salary advances from 1 April
model fitted on modelled EL realised loss modelled % realised %
before 1 April ₦6,019,887.85 ₦5,839,657.00 13.69% 13.28%
all loans ₦5,974,631.09 ₦5,839,657.00 13.59% 13.28%
139The loans still paying on time carry an EL of ₦590,059.76 (personal) and ₦647,071.65 (SME). The 12-month and rest-of-life figures match because no loan has more than 12 months left. The model fitted on applications before 1 April says 13.69% for the later salary advances and they lost 13.28%. python3 el.py prints the same numbers as the steps above, and wc -l counts 139 lines.
Set SHRINK_K = 0 at the top of el.py (no credibility weighting) and rerun step 5’s command. The personal-loan band under 640, with 22 loans and no defaults, now has a multiplier of 0, a PD of 0.0% and an expected loss of ₦0.00, and the book’s EL falls from 3.48% to 3.44%. A band with no defaults has been told it has no risk. Put SHRINK_K back to 50. Then try MIN_EFFECTIVE = 30 and look at months 7 to 9 of the hazards. Fewer months are assumed. The 12-month personal loan’s lifetime PD falls from 9.13% to 8.75%, and the 6-month SME loan’s from 5.30% to 3.63%, because SME month 7 (no defaults among 51.5 effective loans) is now believed and lowers the rate used for the months still assumed. One threshold moves those PDs by 0.4 and 1.7 points. Put MIN_EFFECTIVE back to 100.
Template
# Expected loss: <product>, <band>
Prepared by <analyst>, credit risk. Signed by <head of credit risk>. Data: <book, cut-off, definition of default>.
## 1. Segment
<loans> loans, <₦ lent>. Default means: <definition>. Horizon: <12 months or lifetime, and why>.
## 2. The three estimates
| Factor | Value | Source (lab step or assumption) | Loans or months it rests on |
| PD | <rate> | | |
| LGD | <rate> | | |
| EAD | <share of amount lent, or ₦> | | |
## 3. Expected loss
PD x LGD x EAD = <₦>, which is <share> of the amount lent. Show the arithmetic.
## 4. Sensitivity
| Change | Expected loss | Difference |
Move one factor at a time. Say which factor matters most.
## 5. Limits
What is assumed, what the data cannot see, and one way this could be wrong and what would show it.
## 6. Decision and sign-off
Decision needed: <what, from whom, by when>. Out of scope: <what this memo does not cover>.
Prepared <name, date>. Approved <name, date>. WORKED EXAMPLE
An analyst on Adesola’s team writes this memo; Adesola, the credit risk manager at Northmere, signs it. Adunni drafts it for the salary advances with a bureau score of 740 and above, from the lab’s step 3 and step 5 output.
Segment. 409 loans, ₦12,559,000.00 lent. Default means an instalment unpaid 90 days after its due date. A salary advance is due on day 30, so a default can only show in month 4 and the 12-month and lifetime horizons are the same.
Estimates. PD 6.77%, measured in month 4 and shrunk toward the product’s 14.34% with 50 pseudo-loans, because the band’s own rate is 24 defaults in 409. LGD 100%, measured on 281 defaulted salary advances, none of which paid anything afterwards. EAD factor 0.972: defaulters had paid a little, so they owed 97.2% of principal.
Expected loss. 6.77% × 0.972 × 100% = 6.58% of the amount lent. Step 5 prints ₦826,238.09.
Sensitivity (my arithmetic, one factor at a time). Each figure keeps the other two factors as above (EAD ₦12,559,000 × 0.972). If PD were the ends of step 3’s 4.0% to 8.6% interval, which is on the raw 5.9% rate, not the shrunk 6.77%, EL would be about ₦488,000 or ₦1,050,000. If collections recovered an assumed 10% of EAD, so LGD were 90%, it would be about ₦743,600. PD matters most.
Limits. One benign window, no downturn LGD, and a 100% LGD from a book with no collections history. A first recovery above zero would show it.
Decision. Adesola is asked to approve ₦826,238.09 as this band’s expected loss for the pricing review. Provisioning stages and capital are out of scope.
Now you
You are a credit analyst at a buy-now-pay-later lender in Lagos whose book looks like the lab’s BNPL rows, and your head of credit risk signs what you write. Write the expected-loss memo for the thin-file BNPL segment. Step 3 prints the band’s defaults and its Wilson interval, step 4 the LGD and the EAD factor for BNPL, and step 5 the band’s row: 182 loans, ₦6,397,000.00 lent, an expected loss of ₦434,704.60 over life. BNPL loans have a schedule, so EAD falls month by month; say how step 5 handles that. Decide which of the three factors you trust least, and vary it. Your head of credit risk reads the memo to decide whether the thin-file limit and price should stay as they are before next month’s review.
Self-check
Northmere's new 12-month personal loan has been on sale for nine months. In an illustrative pilot there are 450 loans and 14 defaults so far, and no loan has yet been watched for its whole life plus 90 days. The board wants one figure for expected loss on the product. Adesola must choose how Adunni computes it.
- DOC Guidance on credit risk and accounting for expected credit losses (BCBS d350) Basel Committee on Banking Supervision, 2015
The supervisors' view of how a bank should apply expected credit loss accounting, in 11 principles. Read the principles on credit risk assessment and measurement first.
- DOC BIS: Expected credit losses (Basel consolidated framework, PAP20) Basel Committee on Banking Supervision
The Basel consolidated framework's chapter on expected credit losses. Read it for how the definition of default ties to expected loss, and check the in-force date before you rely on a paragraph.
- DOC IFRS 9 Financial Instruments IFRS Foundation
The IFRS Foundation's page for the standard. Read its impairment section, the definitions of 12-month and lifetime expected credit losses, and paragraph B5.5.43.
- BOOK Credit Scoring and Its Applications, second edition Lyn Thomas, Jonathan Crook and David Edelman, 2017
A standard textbook on credit scoring. Reviews describe new material in this edition on the Basel Accords and on survival analysis; this link is a university record of the book, so use the table of contents to find those chapters. Read: the material on the Basel Accords and on survival analysis for credit scoring.
- PAPER Loss given default models incorporating macroeconomic variables for credit cards Tony Bellotti and Jonathan Crook, 2012
An account-level study of loss given default on UK credit cards, in which models with macroeconomic variables forecast best. It is the kind of evidence a downturn LGD needs, which a book seen in one benign window cannot give. Read: the abstract.
- PAPER Interval Estimation for a Binomial Proportion Lawrence Brown, Tony Cai and Anirban DasGupta, 2001
Compares interval methods for a rate measured on a sample, and shows that the usual normal interval can behave badly for small samples. The Wilson interval used in step 3 is one of the alternatives it examines. Read: the abstract and the sections on the Wilson interval.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.