Project: build and validate a scorecard on the loan book
Choose the target, build a points table from salary-advance loans, test it on a later period, and write the validation report that a second analyst can re-run and check
This chapter is a project. You build one application scorecard for Owoleaf’s salary advance from the finance lab’s loan book at scale 1 (data1), test it on later applications, and write the validation report. Chapter 2.2, Credit scoring: scorecards and logistic regression, teaches the method. If you have read it, this is the whole method end to end. If you have not, every term is defined where it first appears and the code is complete, so you can work from this page alone. This project makes different choices from that chapter’s lab, so its figures differ from that chapter’s, on purpose. That lab builds one card across all four products on a 120-day window, trains on applications before 1 April (543 loans, 53 bad), uses four variables and anchors 600 points at 20 to 1 odds; its test Gini is 0.356. This project models the salary advance alone, trains on applications before 1 May (636 loans, 98 bad), uses three variables and anchors 600 points at 10 to 1; its out-of-time Gini is 0.265. Different samples, splits and variables give different numbers, and neither set is wrong. In module 1’s AI in lending you scored loans with a hand-made points table; here the points are fitted and tested. Everything is standard-library Python. The numbers are illustrative: Owoleaf is fictional and so are its borrowers, and nothing here is a lender’s or a regulator’s rule.
The assignment
You play both people. As Erhuvwu you build: a modelling table, a points table and a first set of figures. As Iyabode you validate: you set the acceptance bars before you look at the out-of-time rows, then re-compute the headline numbers by a different route and decide whether to sign. Three things come out of it.
- A modelling table, one row per loan, with the features Owoleaf knew on the application date and an outcome known at the cut-off.
- A scorecard: a table of points that adds to a score, and a rule that turns a score into a probability of default.
- A validation report that states the target, the sample, the bins, the figures, the acceptance bars and a signed conclusion, so that someone who was not there can check every number.
The bars are fixed first. A bar written after you have seen the number is a description, not a test. These are the bars this project uses; they are Owoleaf’s illustrative model-owner choices, not a regulator’s:
| # | Acceptance bar |
|---|---|
| 1 | Out-of-time Gini at least 0.20 |
| 2 | Out-of-time KS at least 0.15 |
| 3 | Gini falls by no more than 0.10 from development to out of time |
| 4 | Overall predicted bad rate within 2 points of the observed rate |
| 5 | Predicted probability of default inside the observed 95% interval in at least 4 of 5 score bands |
| 6 | Observed bad rate never rises as the score rises |
| 7 | Score PSI below 0.10 |
| 8 | Every input variable’s PSI below 0.25 |
One product, and why
The loan book has four products, and the obvious first move is to model them together. The lab’s first step shows why that misleads. The share of loans 90 or more days past due at the cut-off is 14.3% for the salary advance and 0.8% for the 12-instalment personal loan. That is not a safer product. A loan can only show 90 days past due once 90 days have passed since an unpaid instalment. A personal loan opened in June has had at most four instalments fall due, so a borrower who will stop at the ninth has not had time to show it. A single model fitted across the products would learn that short loans are risky and long loans are safe, from the calendar and not from the borrowers.
The salary advance avoids this. It has one repayment, due 30 days after disbursement, and the last advance was paid out on 2026-06-28. The latest advance fell due on 2026-07-28, 92 days before the cut-off of 2026-10-28, so every salary advance has had the full 90 days to go bad. Its 1,959 loans, 281 of them bad, are the sample. One product per scorecard is also what lenders do in practice, because a different product is a different population. Other products need their own target and window; chapter 2.4, Decisions: cut-offs, limits and risk-based pricing, returns to how scores feed decisions across products.
Target, window and split
The target. A loan is bad if it is 90 or more days past due at the cut-off, which in the book means its status is default or written_off (the status ladder is in the loan lifecycle). It is good if nothing is past due. A loan 1 to 89 days past due is indeterminate: it may still cure or go bad, so it is left out. A loan is immature if its last instalment is less than 90 days old at the cut-off: it has not had time to show 90 days past due, so it is left out as well. The code applies both rules in general and counts what each removes. For the salary advance both counts are zero. You check that and do not assume it.
The split. The scorecard is built on development loans and tested on out-of-time loans: applications from a later period that the build never touched. A random hold-out would put May’s customers into the training data and would not mimic what happens in production, which is a card fitted on the past scoring the future. The cut is the application date of 1 May. January to March alone has 301 loans and 44 bads, too few to fit three variables with several bins each. January to April has 636 loans and 98 bads, and May to June leaves 1,323 loans and 183 bads to test on. That is a trade-off: more development data makes the fit steadier and the test smaller. State it in the report.
Features known on the application date
A feature qualifies only if Owoleaf could compute it on the day it decided. The nine candidates are the bureau score (blank for a thin file, a customer the bureau knows little about, which gets its own bin), KYC tier (the level of identity verification a customer has completed; tier 1 is the lowest), wallet inflows in the 90 days before the application date and strictly before it, delinquencies in the last 12 months, enquiries in the last 90 days, years of credit history, open loans, the channel and the wallet’s age. The bureau fields are explained in credit data in Nigeria.
Two kinds of column stay out on principle. Anything from the loan table after approval, such as status, days past due or the principal repaid, is the outcome or a consequence of it. Using one is leakage, and the lab’s break shows what it does to the numbers. The customer’s state stays out too, because a place can stand in for who someone is. Whether that is acceptable is a fairness question that module 3’s chapters on fairness in AI credit and on model risk take up.
One more fact about the sample matters. Owoleaf’s old rule has already used delinquencies and enquiries: an applicant with two delinquencies, or too many enquiries, was declined and never reached the sample. Those variables have little left to say among the people who were approved, and the lab shows it. This is selection: the scorecard learns only from people the old rule approved, so it has never been tested on the people it would change. Module 3’s model risk chapter covers reject inference, the methods for estimating how declined applicants would have behaved. This project states the limit and does not try to fix it.
Binning, weight of evidence and information value
A scorecard works on bins, not raw numbers: bureau score 700 to 739 is one row. Each bin gets a weight of evidence (WoE), the log of how much more common good loans are in the bin than bad loans:
WoE = ln( share of all goods that are in the bin ÷ share of all bads that are in the bin )
A positive WoE means the bin is safer than average. The information value (IV) of a variable adds up each bin’s contribution, (share of goods − share of bads) × WoE, and says how much the variable separates good from bad. The code adds half a loan to each count so that an empty cell cannot divide by zero.
Work one bin by hand. In development there are 636 loans and 98 bads, so 538 goods. The 700 to 739 bureau-score bin holds 65 loans, 5 bad and 60 good. With five bins the half-counts make the denominators 538 + 2.5 = 540.5 and 98 + 2.5 = 100.5:
share of goods = 60.5 ÷ 540.5 = 0.1119, share of bads = 5.5 ÷ 100.5 = 0.0547, WoE = ln(0.1119 ÷ 0.0547) = ln 2.045 = +0.72.
That bin’s contribution to IV is (0.1119 − 0.0547) × 0.72 = 0.041. Five bads is a thin cell; the half-count only stops the arithmetic failing, it does not make five bads reliable. Watch for this bin in the validation.
You choose bins on the development rows only. Two rules keep the choice honest. A variable must reach an IV of 0.01, and its WoE must move in one direction along the bins (it rises, or it falls, but it does not zigzag) so that you can say why it behaves as it does. The floor of 0.01 is lower than the 0.02 some analysts use as the line for “not predictive”, because with 98 bads every IV is noisy. The lab’s first run of the bureau score in six bins zigzags: the 620 to 659 bin has a WoE of +0.18 and the 660 to 699 bin has −0.17, which no business story explains. You merge them. Three other variables pass the IV test but zigzag, so they go: open loans, years of history and wallet age. Wallet inflows in three bins zigzag too, so they are merged into two. The three that survive are the bureau score, KYC tier and wallet inflows.
Logistic regression, scaled to points
Logistic regression fits the probability of an outcome as a weighted sum passed through an S-shaped curve. Here the inputs are the WoE of each applicant’s bin, and the model is for the log-odds of good: ln(good ÷ bad) = b0 + b1 × WoE(score) + b2 × WoE(tier) + b3 × WoE(inflow). The fit uses Newton’s method, which repeatedly solves a weighted least-squares problem until the coefficients stop moving. The code is short arithmetic. Because WoE is already signed so that higher is safer, every coefficient should be positive. A negative one means two variables overlap and are fighting each other, and the code stops if that happens. On the development rows the fit gives b0 = 1.708 and coefficients of 0.932, 0.652 and 0.402.
Points turn the log-odds into numbers people read. You pick an anchor: 600 points at good-to-bad odds of 10 to 1, and 20 points to double the odds (PDO). Then:
factor = PDO ÷ ln 2 = 20 ÷ 0.6931 = 28.85
offset = 600 − factor × ln 10 = 600 − 28.85 × 2.3026 = 533.56
score = offset + factor × log-odds of good
The base points every applicant starts with are offset + factor × b0 = 533.56 + 28.85 × 1.708 = 582.84, which rounds to 583. Each bin then adds or removes factor × coefficient × WoE, rounded to a whole point. For bureau score 740 or more: 28.85 × 0.932 × 0.99 = 26.6, so +27. For tier 2 or 3: 28.85 × 0.652 × 0.41 = 7.7, so +8.
Reading a score back as a probability inverts the scaling: the odds of good are exp((score − offset) ÷ factor) and the probability of bad is 1 ÷ (1 + odds). Take loan L000004, a thin file in tier 2 or 3 with ₦150,000 or more of inflows in the 90 days before. Its score is 583 − 10 + 8 + 3 = 584. The odds are exp((584 − 533.56) ÷ 28.85) = exp(1.748) = 5.74, so the probability of bad is 1 ÷ 6.74 = 14.8%. Anyone can redo that from the points table, which is what a scorecard is for.
Validation: what a second analyst checks
Validation asks whether the card works on loans it was not fitted to. Six checks, in the order the lab runs them.
- Gini is
2 × AUC − 1. AUC is the chance that a randomly chosen bad loan scores lower than a randomly chosen good one, counting ties as half. 0.5 is a coin flip, so Gini 0 is no skill and Gini 1 is perfect. - KS, the Kolmogorov-Smirnov statistic, is the largest gap, at any score, between the share of bads at or below it and the share of goods at or below it.
- A bootstrap interval for the Gini. With 183 bads in the test, the Gini would move if you had drawn different months. Resampling the test loans with replacement 1,000 times, and reading the 2.5th and 97.5th percentiles, shows by how much.
- Calibration by band. Gini and KS see only order. They would not notice if every predicted probability were doubled. Calibration cuts the scores into five bands at the development scores’ 20th, 40th, 60th and 80th percentiles, and compares the probability the score implies with the bad rate observed out of time, with a 95% Wilson interval, a standard range for a proportion that behaves well when a band has few bads.
- PSI, the population stability index, compares the share of loans in each bin before and after:
sum of (later − earlier) × ln(later ÷ earlier). Below 0.10 is usually read as stable, 0.10 to 0.25 as worth watching and above 0.25 as a changed population. These are rules of thumb among scorecard builders and not any regulator’s thresholds. You compute it for the score bands and for each input variable. - A re-computation by a second route.
recheck.pycounts every bad-good pair for the Gini, tries every score as the KS threshold, rebuilds the target from the loan table’s status, and adds up one applicant’s score by hand. If two routes agree to nine decimals, a coding slip is unlikely.
What the lab finds
The reference run, with the choices above, passes seven of the eight bars and fails one. That is the useful part. A validation that always passes is not validating. The figures are in the lab’s expected output, and each is worth reading before you run the code.
- The out-of-time Gini is 0.265 and passes the bar of 0.20, but its 95% bootstrap interval runs from 0.181 to 0.344. The lower end sits below the bar. With 183 bads, the project cannot prove at 95% that the true Gini is above 0.20. It passes on the point estimate and the report says so.
- The development Gini is 0.332. The fall to 0.265 is 0.067, inside the bar of 0.10, and normal: the fitted card always looks best on the rows it was fitted to.
- In the lowest score band the card predicts a 25.5% bad rate and the loans show 18.9%, outside the interval of 14.6% to 24.2%. It is the one band outside its interval, so bar 5 passes with four bands of five, and the same band causes the failure of bar 6: the next band up has a higher bad rate, 22.2%.
diagnose.pyshows why. The thin-file bin had a development bad rate of 20.9% and an out-of-time rate of 15.9%. The difference between the two lowest bands is −3.3 points with a 95% interval of −10.5 to +3.9, so it cannot be told apart from chance.
The report then needs a judgement and not a computation: this is a conditional pass. Bar 6 failed, the cause is a gap inside the noise, and the score ranks well enough to use. The conditions are monitoring the thin-file bin and the lowest band, and refitting once more bads are available. The reference wording is in the lab. You may disagree with it. What you may not do is skip the failed bar.
What this scorecard cannot see
- People the old rule declined. The sample holds only approved applicants. If Owoleaf lowered its cut-off, the card would score people it has never seen.
- Other products and other times. It is a salary-advance card built on six months of applications, January to June, from one fictional lender.
- The lifetime outcome. Bad here means 90 days past due by the cut-off, not what the loan eventually costs.
- Why. A scorecard predicts who is likely to default. It does not say whether lending to them is a good decision at a given price; chapter 2.4 takes that up. Gradient-boosted models, the subject of chapter 2.8, Gradient-boosted credit models and explaining a decline to the customer, test what a more flexible model finds that this card cannot.
Lab
You work in a new folder, labs/finance/scorecard. It holds the code you write and the files it produces. Run every command from inside it. The data is data1, generated at seed 42 and scale 1, so your numbers match the ones below if you make the same choices. If you choose differently, say a different bin edge, yours will differ slightly, and that is allowed as long as the report says what you chose and why.
1. Check the data and see why one product.
cd labs/finance
ls data1/loans.csv data1/transactions.csv data1/finance.sqlite 2>/dev/null || \
(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.sqlite | tail -1
mkdir -p scorecard && cd scorecard
python3 - <<'PY'
import csv, collections
t = collections.defaultdict(lambda: [0, 0])
for l in csv.DictReader(open("../data1/loans.csv")):
k = (l["product"], int(l["instalments"]))
t[k][0] += 1
t[k][1] += int(l["days_past_due"]) >= 90
print("product instalments loans 90+ days past due rate")
for (p, n), (loans, bad) in sorted(t.items()):
print(f"{p:<8} {n:>11} {loans:>6} {bad:>18} {bad / loans:>6.1%}")
PYIf data1 exists the ls prints three paths and nothing is built. If it is missing, the four generators run first (the lab README lists them; about 40 seconds). The check ends with OK: all invariants hold, and the table follows:
OK: all invariants hold
product instalments loans 90+ days past due rate
BNPL 4 766 66 8.6%
PL 3 88 8 9.1%
PL 6 111 2 1.8%
PL 9 121 3 2.5%
PL 12 131 1 0.8%
SAL 1 1959 281 14.3%
SME 3 231 4 1.7%
SME 6 238 3 1.3%The 12-instalment personal loan looks about 18 times safer than the salary advance. It is not: its loans have had too little time to go 90 days past due. Only the single-repayment salary advance has a clean window.
2. Build the modelling table. Save this as sample.py. It reads data1 and writes sample.csv and sample_notes.json. The wallet inflow is summed from transactions.csv for the 90 days before the application date, never including the application day or later.
cat > sample.py <<'EOF'
"""Step 1: the modelling table.
One row per salary-advance (SAL) loan. Features are what Owoleaf knew on the application date;
the target is what had happened by the cut-off. Standard library only."""
import csv, collections, datetime as dt, json, sqlite3
DATA = "../data1/"
rd = lambda name: list(csv.DictReader(open(DATA + name)))
db = sqlite3.connect("file:" + DATA + "finance.sqlite?mode=ro", uri=True)
meta = dict(db.execute("SELECT key, value FROM loan_book_meta"))
CUTOFF = dt.date.fromisoformat(meta["cut_off"])
SPLIT = "2026-05-01" # applications before this are development, from this date out of time
MATURITY_DAYS = 90 # a loan is mature when its last instalment has had 90 days to go bad
print("cut-off", CUTOFF)
apps = {a["id"]: a for a in rd("applications.csv")}
bureau = {b["id"]: b for b in rd("bureau_reports.csv")}
cust = {c["id"]: c for c in rd("customers.csv")}
loans = [l for l in rd("loans.csv") if l["product"] == "SAL"]
last_due = {}
for s in rd("schedule.csv"):
last_due[s["loan_id"]] = max(last_due.get(s["loan_id"], ""), s["due_date"])
# Wallet inflows by customer: funding by transfer or card that succeeded, as loans.py's inflow rule.
inflows = collections.defaultdict(list)
for t in csv.DictReader(open(DATA + "transactions.csv")):
if t["status"] == "succeeded" and t["kind"] in ("funding_transfer", "funding_card"):
inflows[t["customer_id"]].append((t["created_at"][:10], int(t["amount_kobo"])))
kept, why = [], collections.Counter()
for l in loans:
a, b, c = apps[l["application_id"]], bureau[apps[l["application_id"]]["bureau_report_id"]], cust[l["customer_id"]]
mature_on = dt.date.fromisoformat(last_due[l["id"]]) + dt.timedelta(days=MATURITY_DAYS)
dpd = int(l["days_past_due"])
if mature_on > CUTOFF:
why["immature"] += 1
continue
if dpd >= 90:
bad = 1
elif dpd == 0:
bad = 0
else:
why["indeterminate (1-89 days past due)"] += 1
continue
applied = dt.date.fromisoformat(a["applied_at"])
lo = (applied - dt.timedelta(days=90)).isoformat()
inflow = sum(k for d, k in inflows[l["customer_id"]] if lo <= d < a["applied_at"]) # strictly before the application
kept.append(dict(
loan_id=l["id"], applied_at=a["applied_at"], split="dev" if a["applied_at"] < SPLIT else "oot", bad=bad,
score=b["score"], thin=1 - int(b["hit"]), delinq_12m=b["delinquent_12m"], enquiries_90d=b["enquiries_90d"],
history_years=b["history_years"], open_loans=b["open_loans"], tier=c["kyc_tier"], channel=a["channel"],
inflow_90d_kobo=inflow, wallet_age_days=(applied - dt.date.fromisoformat(c["signup_at"][:10])).days,
principal_kobo=l["principal_kobo"]))
with open("sample.csv", "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(kept[0]))
w.writeheader()
w.writerows(kept)
json.dump(dict(cutoff=CUTOFF.isoformat(), split=SPLIT, maturity_days=MATURITY_DAYS, loans=len(loans), excluded=dict(why)),
open("sample_notes.json", "w"))
print(f"SAL loans {len(loans)}; excluded {dict(why) or 'none'}; kept {len(kept)}")
for sp in ("dev", "oot"):
rs = [r for r in kept if r["split"] == sp]
print(f"{sp}: {len(rs)} loans, {sum(r['bad'] for r in rs)} bad, bad rate {sum(r['bad'] for r in rs) / len(rs):.1%}")
for m in sorted({r["applied_at"][:7] for r in kept}):
rs = [r for r in kept if r["applied_at"][:7] == m]
print(f" {m}: {len(rs):>4} loans, {sum(r['bad'] for r in rs):>3} bad")
EOF
python3 sample.pycut-off 2026-10-28
SAL loans 1959; excluded none; kept 1959
dev: 636 loans, 98 bad, bad rate 15.4%
oot: 1323 loans, 183 bad, bad rate 13.8%
2026-01: 22 loans, 1 bad
2026-02: 81 loans, 10 bad
2026-03: 198 loans, 33 bad
2026-04: 335 loans, 54 bad
2026-05: 561 loans, 77 bad
2026-06: 762 loans, 106 badNo loan is excluded, which you can now state as a fact: every salary advance is mature and none is between 1 and 89 days past due. The development set has 636 loans and 98 bads and the out-of-time set 1,323 and 183. The count grows month on month because wallet customers sign up through the period and then apply.
3. Write the helpers and bin the variables. Save lib.py: the bins, weight of evidence, the logistic regression, Gini, KS and PSI. Everything later imports it.
cat > lib.py <<'EOF'
"""Shared helpers: load the sample, bins, weight of evidence, logistic regression, Gini, KS, PSI.
Standard library only. Nothing here looks at the out-of-time rows unless a function is handed them."""
import csv, math
def load(path="sample.csv"):
rows = list(csv.DictReader(open(path)))
for r in rows:
for k in ("bad", "thin", "delinq_12m", "enquiries_90d", "history_years", "open_loans", "tier",
"inflow_90d_kobo", "wallet_age_days", "principal_kobo"):
r[k] = int(r[k])
r["score"] = int(r["score"]) if r["score"] else None
return rows
# Each variable: a function that puts a row in a named bin, and the bins in order.
BINNERS = {
"bureau_score_fine": lambda r: "thin file" if r["score"] is None else
("<620" if r["score"] < 620 else "620-659" if r["score"] < 660 else "660-699" if r["score"] < 700
else "700-739" if r["score"] < 740 else "740+"),
"bureau_score": lambda r: "thin file" if r["score"] is None else
("<620" if r["score"] < 620 else "620-699" if r["score"] < 700 else "700-739" if r["score"] < 740 else "740+"),
"kyc_tier": lambda r: "tier 1" if r["tier"] == 1 else "tier 2-3",
"inflow_3bins": lambda r: "under N50k" if r["inflow_90d_kobo"] < 5_000_000 else "N50k-N150k" if r["inflow_90d_kobo"] < 15_000_000
else "N150k or more",
"inflow_90d": lambda r: "under N150k" if r["inflow_90d_kobo"] < 15_000_000 else "N150k or more",
"delinq_12m": lambda r: "none" if r["delinq_12m"] == 0 else "1 or more",
"enquiries_90d": lambda r: "0-2" if r["enquiries_90d"] <= 2 else "3 or more",
"history_years": lambda r: "<2" if r["history_years"] < 2 else "2-5" if r["history_years"] <= 5 else "6+",
"open_loans": lambda r: "0" if r["open_loans"] == 0 else "1-2" if r["open_loans"] <= 2 else "3+",
"channel": lambda r: r["channel"],
"wallet_age": lambda r: "<30 days" if r["wallet_age_days"] < 30 else "30-59" if r["wallet_age_days"] < 60 else "60+",
}
ORDER = {
"bureau_score_fine": ["thin file", "<620", "620-659", "660-699", "700-739", "740+"],
"inflow_3bins": ["under N50k", "N50k-N150k", "N150k or more"],
"bureau_score": ["thin file", "<620", "620-699", "700-739", "740+"],
"kyc_tier": ["tier 1", "tier 2-3"],
"inflow_90d": ["under N150k", "N150k or more"],
"delinq_12m": ["none", "1 or more"],
"enquiries_90d": ["0-2", "3 or more"],
"history_years": ["<2", "2-5", "6+"],
"open_loans": ["0", "1-2", "3+"],
"channel": ["app", "ussd"],
"wallet_age": ["<30 days", "30-59", "60+"],
}
def woe_table(rows, var):
"""Weight of evidence and information value of one binned variable, computed on `rows` only.
WoE = ln(share of goods in the bin / share of bads in the bin); a half is added to each count
so an empty cell cannot divide by zero. Positive WoE = safer than average."""
f, bins = BINNERS[var], ORDER[var]
G = sum(1 - r["bad"] for r in rows); B = sum(r["bad"] for r in rows)
out, iv = {}, 0.0
for b in bins:
g = sum(1 - r["bad"] for r in rows if f(r) == b); bd = sum(r["bad"] for r in rows if f(r) == b)
pg, pb = (g + 0.5) / (G + 0.5 * len(bins)), (bd + 0.5) / (B + 0.5 * len(bins))
w = math.log(pg / pb)
iv += (pg - pb) * w
out[b] = dict(n=g + bd, bad=bd, woe=w)
return out, iv
def monotone(table, var):
"""True when WoE only rises (or only falls) along the bins. A thin file has no place in the order,
and a nominal variable (channel) has no order, so both are left out of the test."""
w = [t["woe"] for b, t in table.items() if b != "thin file"]
return var == "channel" or all(a <= b for a, b in zip(w, w[1:])) or all(a >= b for a, b in zip(w, w[1:]))
IV_FLOOR = 0.01 # keep a variable if its development IV reaches this and its WoE is monotone (the chapter says why)
def solve(A, b):
"""Solve A x = b by Gaussian elimination with partial pivoting."""
n = len(b); M = [row[:] + [b[i]] for i, row in enumerate(A)]
for c in range(n):
p = max(range(c, n), key=lambda i: abs(M[i][c])); M[c], M[p] = M[p], M[c]
for i in range(c + 1, n):
k = M[i][c] / M[c][c]
for j in range(c, n + 1):
M[i][j] -= k * M[c][j]
x = [0.0] * n
for i in reversed(range(n)):
x[i] = (M[i][n] - sum(M[i][j] * x[j] for j in range(i + 1, n))) / M[i][i]
return x
def fit_logistic(X, y, iters=50):
"""Logistic regression by Newton-Raphson (iteratively reweighted least squares). X rows start
with a 1 for the intercept; y is 1 for the outcome being modelled. Returns the coefficients."""
k = len(X[0]); beta = [0.0] * k
for _ in range(iters):
grad, hess = [0.0] * k, [[0.0] * k for _ in range(k)]
for xi, yi in zip(X, y):
z = sum(b * v for b, v in zip(beta, xi))
p = 1 / (1 + math.exp(-z)); w = p * (1 - p)
for a in range(k):
grad[a] += (yi - p) * xi[a]
for c in range(k):
hess[a][c] += w * xi[a] * xi[c]
step = solve(hess, grad)
beta = [b + s for b, s in zip(beta, step)]
if max(abs(s) for s in step) < 1e-9:
break
return beta
def auc(scores, bad):
"""Probability that a random bad has a lower score than a random good (ties count half),
from the ranks of the scores. Gini = 2 AUC - 1."""
order = sorted(range(len(scores)), key=lambda i: scores[i])
ranks, i = [0.0] * len(scores), 0
while i < len(order):
j = i
while j + 1 < len(order) and scores[order[j + 1]] == scores[order[i]]:
j += 1
for t in range(i, j + 1):
ranks[order[t]] = (i + j) / 2 + 1
i = j + 1
nb = sum(bad); ng = len(bad) - nb
rank_sum_bad = sum(rk for rk, b in zip(ranks, bad) if b)
return 1 - (rank_sum_bad - nb * (nb + 1) / 2) / (nb * ng) # share of (bad, good) pairs with bad scoring lower
def ks(scores, bad):
"""Largest gap between the cumulative share of bads and of goods as the score rises."""
nb = sum(bad); ng = len(bad) - nb
cb = cg = 0; best = 0.0
pairs = sorted(zip(scores, bad))
for i, (s, b) in enumerate(pairs):
cb += b; cg += 1 - b
if i + 1 == len(pairs) or pairs[i + 1][0] != s:
best = max(best, abs(cb / nb - cg / ng))
return best
def psi(expected, actual):
"""Population stability index over matching shares: sum (a - e) ln(a / e)."""
return sum((a - e) * math.log(a / e) for e, a in zip(expected, actual))
EOFThen save binning.py, which reads the development rows only:
cat > binning.py <<'EOF'
"""Step 2: weight of evidence and information value on the DEVELOPMENT rows only.
python3 binning.py one line per candidate variable
python3 binning.py bureau_score kyc_tier the bins of the named variables"""
import sys
from lib import load, woe_table, monotone, BINNERS, IV_FLOOR
rows = [r for r in load() if r["split"] == "dev"]
print(f"development rows: {len(rows)}, bad {sum(r['bad'] for r in rows)}")
tables = {v: woe_table(rows, v) for v in BINNERS}
if len(sys.argv) == 1:
print(f"{'variable':<18}{'bins':>5}{'IV':>8} monotone verdict (IV >= {IV_FLOOR} and monotone)")
for v, (t, iv) in sorted(tables.items(), key=lambda kv: -kv[1][1]):
ok = iv >= IV_FLOOR and monotone(t, v)
print(f"{v:<18}{len(t):>5}{iv:>8.3f} {'yes' if monotone(t, v) else 'no':<9} {'keep' if ok else 'drop'}")
for v in sys.argv[1:]:
t, iv = tables[v]
print(f"\n{v} IV {iv:.3f}")
for b, x in t.items():
print(f" {b:<14} loans {x['n']:>4} bad {x['bad']:>3} bad rate {x['bad'] / x['n']:>6.1%} WoE {x['woe']:+.2f}")
EOF
python3 binning.py
python3 binning.py bureau_score_fine bureau_score kyc_tier inflow_90dThe first command rates every candidate. The second shows the bins of four of them:
development rows: 636, bad 98
variable bins IV monotone verdict (IV >= 0.01 and monotone)
bureau_score_fine 6 0.287 no drop
bureau_score 5 0.279 yes keep
kyc_tier 2 0.121 yes keep
open_loans 3 0.043 no drop
history_years 3 0.020 no drop
wallet_age 3 0.019 no drop
inflow_3bins 3 0.018 no drop
inflow_90d 2 0.017 yes keep
enquiries_90d 2 0.007 yes drop
channel 2 0.001 yes drop
delinq_12m 2 0.001 yes drop
development rows: 636, bad 98
bureau_score_fine IV 0.287
thin file loans 187 bad 39 bad rate 20.9% WoE -0.35
<620 loans 71 bad 18 bad rate 25.4% WoE -0.62
620-659 loans 92 bad 12 bad rate 13.0% WoE +0.18
660-699 loans 90 bad 16 bad rate 17.8% WoE -0.17
700-739 loans 65 bad 5 bad rate 7.7% WoE +0.72
740+ loans 131 bad 8 bad rate 6.1% WoE +1.00
bureau_score IV 0.279
thin file loans 187 bad 39 bad rate 20.9% WoE -0.36
<620 loans 71 bad 18 bad rate 25.4% WoE -0.62
620-699 loans 182 bad 28 bad rate 15.4% WoE +0.01
700-739 loans 65 bad 5 bad rate 7.7% WoE +0.72
740+ loans 131 bad 8 bad rate 6.1% WoE +0.99
kyc_tier IV 0.121
tier 1 loans 329 bad 65 bad rate 19.8% WoE -0.30
tier 2-3 loans 307 bad 33 bad rate 10.7% WoE +0.41
inflow_90d IV 0.017
under N150k loans 482 bad 79 bad rate 16.4% WoE -0.07
N150k or more loans 154 bad 19 bad rate 12.3% WoE +0.24bureau_score_fine has a higher IV than bureau_score and still fails: its WoE zigzags at 620 to 659 (+0.18) and 660 to 699 (−0.17). Merging them gives bureau_score, which is monotone and loses almost no IV (0.279 against 0.287). The thin file’s bad rate (20.9%) sits between the two lowest score bands, so it keeps its own bin and stays outside the monotone test. open_loans, history_years and wallet_age pass the IV floor and zigzag. enquiries_90d and delinq_12m show almost nothing, because the old approval rule has already removed the people who would separate them. Check one number by hand: the WoE of 700 to 739 is ln(0.1119 ÷ 0.0547) = +0.72, as worked in the chapter.
4. Fit the model and scale to points. Save this as model.py. It fits on development rows and writes scorecard.json and scores.csv.
cat > model.py <<'EOF'
"""Step 3: choose variables, fit the logistic regression on DEVELOPMENT rows, scale to points."""
import csv, json, math
from lib import load, woe_table, fit_logistic, monotone, BINNERS, IV_FLOOR
VARS = ["bureau_score", "kyc_tier", "inflow_90d"] # chosen from step 2's table: see the chapter for the rule
BASE_SCORE, BASE_ODDS, PDO = 600, 10, 20 # 600 points at 10 good for every 1 bad; +20 points doubles the odds
FACTOR = PDO / math.log(2)
OFFSET = BASE_SCORE - FACTOR * math.log(BASE_ODDS)
rows = load()
dev = [r for r in rows if r["split"] == "dev"]
tables = {v: woe_table(dev, v)[0] for v in VARS}
for v in VARS:
assert woe_table(dev, v)[1] >= IV_FLOOR and monotone(tables[v], v), v + " fails the variable rule"
X = [[1.0] + [tables[v][BINNERS[v](r)]["woe"] for v in VARS] for r in dev]
beta = fit_logistic(X, [1 - r["bad"] for r in dev]) # model the log-odds of GOOD, so more points = safer
print("intercept", round(beta[0], 3), {v: round(b, 3) for v, b in zip(VARS, beta[1:])})
assert all(b > 0 for b in beta[1:]), "a negative coefficient on a WoE input means the variable is fighting the others"
# Points: score = OFFSET + FACTOR * (b0 + sum b_i * WoE_i). The first two terms are a base every applicant
# gets; each variable then adds or takes away FACTOR * b_i * WoE points, rounded to a whole point.
BASE = round(OFFSET + FACTOR * beta[0])
card = {}
print("base points", BASE)
for v, b in zip(VARS, beta[1:]):
card[v] = {bn: round(FACTOR * b * t["woe"]) for bn, t in tables[v].items()}
print(f"{v}: " + ", ".join(f"{bn} {p:+d}" for bn, p in card[v].items()))
def score(r):
return BASE + sum(card[v][BINNERS[v](r)] for v in VARS)
def pd_of(points):
"""Probability of bad implied by a score: the odds of good are exp((score - OFFSET) / FACTOR)."""
return 1 / (1 + math.exp((points - OFFSET) / FACTOR))
with open("scores.csv", "w", newline="") as f:
w = csv.writer(f)
w.writerow(["loan_id", "split", "bad", "score", "pd"])
for r in rows:
s = score(r)
w.writerow([r["loan_id"], r["split"], r["bad"], s, f"{pd_of(s):.6f}"])
json.dump(dict(vars=VARS, base_points=BASE, base_score=BASE_SCORE, base_odds=BASE_ODDS, pdo=PDO, offset=OFFSET, factor=FACTOR,
intercept=beta[0], coefficients=dict(zip(VARS, beta[1:])), points=card,
woe={v: {b: t["woe"] for b, t in tables[v].items()} for v in VARS}),
open("scorecard.json", "w"), indent=1)
lo, hi = min(score(r) for r in rows), max(score(r) for r in rows)
print(f"scores run from {lo} to {hi}; {len({score(r) for r in rows})} distinct values")
r0 = next(r for r in rows if r["split"] == "oot")
print("worked example", r0["loan_id"], {v: BINNERS[v](r0) for v in VARS}, "->", score(r0), "points, PD", f"{pd_of(score(r0)):.1%}")
EOF
python3 model.pyintercept 1.708 {'bureau_score': 0.932, 'kyc_tier': 0.652, 'inflow_90d': 0.402}
base points 583
bureau_score: thin file -10, <620 -17, 620-699 +0, 700-739 +19, 740+ +27
kyc_tier: tier 1 -6, tier 2-3 +8
inflow_90d: under N150k -1, N150k or more +3
scores run from 559 to 621; 19 distinct values
worked example L000004 {'bureau_score': 'thin file', 'kyc_tier': 'tier 2-3', 'inflow_90d': 'N150k or more'} -> 584 points, PD 14.8%Redo the base by hand: 533.56 + 28.85 × 1.708 = 582.84, so 583. Redo the worked applicant: 583 − 10 + 8 + 3 = 584 points, and exp((584 − 533.56) ÷ 28.85) = 5.74, so a probability of bad of 1 ÷ 6.74 = 14.8%. The 620 to 699 bin earns 0 points because its WoE (+0.01) is the average, which is what a bin at the overall bad rate should earn.
5. Validate out of time. Save this as validate.py. It is the first code to look at the out-of-time rows. It computes the figures, applies the eight bars written above and writes report.md.
cat > validate.py <<'EOF'
"""Step 4: validate out of time. The scorecard was fitted on development rows; the out-of-time rows
are used here for the first time. Writes metrics.json and report.md."""
import csv, json, math, random
from lib import load, auc, ks, psi, BINNERS
card = json.load(open("scorecard.json"))
notes = json.load(open("sample_notes.json"))
immature = notes["excluded"].get("immature", 0)
indeterminate = notes["excluded"].get("indeterminate (1-89 days past due)", 0)
OFFSET, FACTOR = card["offset"], card["factor"]
pd_of = lambda s: 1 / (1 + math.exp((s - OFFSET) / FACTOR))
sample = {r["loan_id"]: r for r in load()}
rows = [dict(sample[r["loan_id"]], score_pts=int(r["score"])) for r in csv.DictReader(open("scores.csv"))]
dev = [r for r in rows if r["split"] == "dev"]
oot = [r for r in rows if r["split"] == "oot"]
col = lambda rs, k: [r[k] for r in rs]
# Score bands: cut at the development score's 20th, 40th, 60th and 80th percentiles; ties stay together.
ds = sorted(col(dev, "score_pts"))
EDGES = [ds[int(len(ds) * q) - 1] for q in (0.2, 0.4, 0.6, 0.8)]
band = lambda s: sum(s > e for e in EDGES)
names = [f"<= {EDGES[0]}"] + [f"{EDGES[i] + 1}-{EDGES[i + 1]}" for i in range(3)] + [f"{EDGES[3] + 1}+"]
def wilson(k, n, z=1.96):
p = k / n
c = (p + z * z / (2 * n)) / (1 + z * z / n)
h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
return c - h, c + h
m = {}
for name, rs in (("dev", dev), ("oot", oot)):
s, b = col(rs, "score_pts"), col(rs, "bad")
m[name] = dict(n=len(rs), bad=sum(b), bad_rate=sum(b) / len(rs), gini=2 * auc(s, b) - 1, ks=ks(s, b),
mean_pd=sum(pd_of(x) for x in s) / len(s))
# Bootstrap the out-of-time Gini: how much could it move with a different 1,323 loans of the same kind?
rng, ginis = random.Random(42), []
for _ in range(1000):
pick = [oot[rng.randrange(len(oot))] for _ in oot]
ginis.append(2 * auc(col(pick, "score_pts"), col(pick, "bad")) - 1)
ginis.sort()
m["oot"]["gini_95"] = [ginis[24], ginis[974]]
for mo in ("2026-05", "2026-06"):
rs = [r for r in oot if r["applied_at"].startswith(mo)]
m["oot"][f"gini_{mo}"] = 2 * auc(col(rs, "score_pts"), col(rs, "bad")) - 1
# Calibration by band: predicted PD from the score against the observed bad rate.
cal = []
for i, nm in enumerate(names):
rs = [r for r in oot if band(r["score_pts"]) == i]
k, n = sum(col(rs, "bad")), len(rs)
lo, hi = wilson(k, n)
pred = sum(pd_of(r["score_pts"]) for r in rs) / n
dv = [r for r in dev if band(r["score_pts"]) == i]
cal.append(dict(band=nm, n=n, bad=k, observed=k / n, low=lo, high=hi, predicted=pred, inside=lo <= pred <= hi,
dev_n=len(dv), dev_observed=sum(col(dv, "bad")) / len(dv)))
m["calibration"] = cal
m["bands_inside"] = sum(c["inside"] for c in cal)
m["monotone"] = all(cal[i]["observed"] >= cal[i + 1]["observed"] for i in range(len(cal) - 1))
# Population stability: share of loans in each band, development against out of time; and each input variable.
share = lambda rs, f, nbins: [max(sum(f(r) == i for r in rs) / len(rs), 1e-4) for i in range(nbins)]
m["psi_score"] = psi(share(dev, lambda r: band(r["score_pts"]), 5), share(oot, lambda r: band(r["score_pts"]), 5))
m["psi_vars"] = {}
for v in card["vars"]:
bins = list(card["points"][v])
f = lambda r, v=v, bins=bins: bins.index(BINNERS[v](r))
m["psi_vars"][v] = psi(share(dev, f, len(bins)), share(oot, f, len(bins)))
# Acceptance figures, set by Owoleaf's model owner before the run (ILLUSTRATIVE).
checks = [
("Out-of-time Gini at least 0.20", m["oot"]["gini"] >= 0.20),
("Out-of-time KS at least 0.15", m["oot"]["ks"] >= 0.15),
("Gini falls by no more than 0.10 from development to out of time", m["dev"]["gini"] - m["oot"]["gini"] <= 0.10),
("Overall predicted bad rate within 2 points of observed", abs(m["oot"]["mean_pd"] - m["oot"]["bad_rate"]) <= 0.02),
("Predicted PD inside the observed 95% interval in at least 4 of 5 bands", m["bands_inside"] >= 4),
("Observed bad rate never rises as the score rises", m["monotone"]),
("Score PSI below 0.10", m["psi_score"] < 0.10),
("Every input variable's PSI below 0.25", all(x < 0.25 for x in m["psi_vars"].values())),
]
m["checks"] = [(t, ok) for t, ok in checks]
json.dump(m, open("metrics.json", "w"), indent=1)
out = ["# Validation report: Owoleaf salary-advance application scorecard", "",
"ILLUSTRATIVE: fictional lender, generated data (finance lab, seed 42, scale 1).", "",
"## Population and target", "",
f"Salary advance (SAL) loans, one repayment 30 days after disbursement. Bad: 90 or more days past due at the "
f"cut-off ({notes['cutoff']}). Good: nothing past due. Excluded: {immature} loans whose last instalment is under "
f"{notes['maturity_days']} days old at the cut-off, and {indeterminate} loans 1 to 89 days past due. "
f"Development: applications before {notes['split']}. Out of time: from {notes['split']}.", "",
f"| | loans | bad | bad rate | Gini | KS |", "|---|---|---|---|---|---|"]
for nm in ("dev", "oot"):
x = m[nm]
out.append(f"| {'Development' if nm == 'dev' else 'Out of time'} | {x['n']} | {x['bad']} | {x['bad_rate']:.1%} | {x['gini']:.3f} | {x['ks']:.3f} |")
out += ["", f"Out-of-time Gini 95% bootstrap interval: {m['oot']['gini_95'][0]:.3f} to {m['oot']['gini_95'][1]:.3f} "
f"(1,000 resamples, seed 42). By month: May {m['oot']['gini_2026-05']:.3f}, June {m['oot']['gini_2026-06']:.3f}.", "",
"## Scorecard", "", f"Base {card['base_points']} points; {card['pdo']} points double the odds of good to bad; "
f"600 points is {card['base_odds']} to 1.", "", "| variable | bin | points |", "|---|---|---|"]
for v in card["vars"]:
for b, p in card["points"][v].items():
out.append(f"| {v} | {b} | {p:+d} |")
out += ["", "## Calibration by score band, out of time", "",
"| band | loans | bad | observed | 95% interval | predicted | inside |", "|---|---|---|---|---|---|---|"]
for c in cal:
out.append(f"| {c['band']} | {c['n']} | {c['bad']} | {c['observed']:.1%} | {c['low']:.1%} to {c['high']:.1%} | {c['predicted']:.1%} | {'yes' if c['inside'] else 'NO'} |")
out += ["", f"Overall: predicted {m['oot']['mean_pd']:.1%}, observed {m['oot']['bad_rate']:.1%}.", "",
"## Population stability (development against out of time)", "", f"Score bands: PSI {m['psi_score']:.3f}.", ""]
for v, x in m["psi_vars"].items():
out.append(f"- {v}: PSI {x:.3f}")
out += ["", "## Acceptance", "", "| check | result |", "|---|---|"]
for t, ok in checks:
out.append(f"| {t} | {'PASS' if ok else 'FAIL'} |")
out += ["", "## Limits", "",
"Built on approved loans only: declined applicants have no outcome, so the card has never been tested on the people it would change. "
"One product, applications from January to June only. The bad rate is a bad-by-cut-off rate, not a lifetime one."]
open("report.md", "w").write("\n".join(out) + "\n")
for nm, label in (("dev", "development"), ("oot", "out of time")):
x = m[nm]
print(f"{label:<12} {x['n']:>5} loans {x['bad']:>4} bad ({x['bad_rate']:.1%}) Gini {x['gini']:.3f} KS {x['ks']:.3f}")
print(f"out-of-time Gini, 95% bootstrap interval {m['oot']['gini_95'][0]:.3f} to {m['oot']['gini_95'][1]:.3f}; "
f"May {m['oot']['gini_2026-05']:.3f}, June {m['oot']['gini_2026-06']:.3f}")
print(f"\nband edges from the development scores: {EDGES}")
print("band loans bad observed 95% interval predicted inside")
for c in cal:
print(f"{c['band']:<10} {c['n']:>5} {c['bad']:>4} {c['observed']:>8.1%} {c['low']:>5.1%} to {c['high']:>5.1%} {c['predicted']:>8.1%} {'yes' if c['inside'] else 'NO'}")
print(f"overall: predicted {m['oot']['mean_pd']:.1%}, observed {m['oot']['bad_rate']:.1%}")
print(f"\nPSI: score bands {m['psi_score']:.3f}; " + "; ".join(f"{v} {x:.3f}" for v, x in m["psi_vars"].items()))
print()
for t, ok in checks:
print(("PASS " if ok else "FAIL ") + t)
print("\nwrote metrics.json and report.md")
EOF
python3 validate.pydevelopment 636 loans 98 bad (15.4%) Gini 0.332 KS 0.290
out of time 1323 loans 183 bad (13.8%) Gini 0.265 KS 0.215
out-of-time Gini, 95% bootstrap interval 0.181 to 0.344; May 0.208, June 0.308
band edges from the development scores: [566, 576, 590, 607]
band loans bad observed 95% interval predicted inside
<= 566 254 48 18.9% 14.6% to 24.2% 25.5% NO
567-576 230 51 22.2% 17.3% to 28.0% 19.8% yes
577-590 305 44 14.4% 10.9% to 18.8% 14.9% yes
591-607 231 22 9.5% 6.4% to 14.0% 9.8% yes
608+ 303 18 5.9% 3.8% to 9.2% 5.4% yes
overall: predicted 14.7%, observed 13.8%
PSI: score bands 0.018; bureau_score 0.008; kyc_tier 0.009; inflow_90d 0.066
PASS Out-of-time Gini at least 0.20
PASS Out-of-time KS at least 0.15
PASS Gini falls by no more than 0.10 from development to out of time
PASS Overall predicted bad rate within 2 points of observed
PASS Predicted PD inside the observed 95% interval in at least 4 of 5 bands
FAIL Observed bad rate never rises as the score rises
PASS Score PSI below 0.10
PASS Every input variable's PSI below 0.25
wrote metrics.json and report.mdSeven bars pass and one fails. Read the failed one before the rest: the lowest band’s observed rate (18.9%) is below the next band’s (22.2%), so bar 6 fails, and the lowest band’s predicted 25.5% sits outside its interval, which is why bar 5 passes with exactly four bands of five. The PSI of 0.066 for inflows is the largest of the three input variables: more wallets reach ₦150,000 of inflows as they age. It is far under 0.25.
6. Re-compute it by a second route. This is Iyabode’s step. Save recheck.py. It does not import lib.py, so a mistake in the helpers cannot hide in both.
cat > recheck.py <<'EOF'
"""Step 5: a second analyst's check. Recompute the headline numbers a different way and compare
with metrics.json. Nothing here imports lib.py."""
import csv, json, math
m = json.load(open("metrics.json"))
scores = list(csv.DictReader(open("scores.csv")))
loans = {r["id"]: r for r in csv.DictReader(open("../data1/loans.csv"))}
# 1. The target, rebuilt from the loan table's status: bad is default or written off.
wrong = [r["loan_id"] for r in scores if int(r["bad"]) != (loans[r["loan_id"]]["status"] in ("default", "written_off"))]
print("target disagrees with loans.status on", len(wrong), "loans")
for split in ("dev", "oot"):
rs = [(int(r["score"]), int(r["bad"])) for r in scores if r["split"] == split]
bads = [s for s, b in rs if b]; goods = [s for s, b in rs if not b]
# 2. Gini by counting every bad-good pair: a pair is concordant when the bad scores lower; ties count half.
conc = sum((g > b) + 0.5 * (g == b) for b in bads for g in goods)
gini = 2 * conc / (len(bads) * len(goods)) - 1
# 3. KS by trying every score as the threshold: share of bads at or below it against share of goods.
k = max(abs(sum(b <= t for b in bads) / len(bads) - sum(g <= t for g in goods) / len(goods)) for t in {s for s, _ in rs})
print(f"{split}: Gini {gini:.6f} (report {m[split]['gini']:.6f}), KS {k:.6f} (report {m[split]['ks']:.6f})")
assert abs(gini - m[split]["gini"]) < 1e-9 and abs(k - m[split]["ks"]) < 1e-9
# 4. A score rebuilt by hand from the points table for one applicant.
card = json.load(open("scorecard.json"))
hand = card["base_points"] + card["points"]["bureau_score"]["thin file"] + card["points"]["kyc_tier"]["tier 2-3"] \
+ card["points"]["inflow_90d"]["N150k or more"]
p = 1 / (1 + math.exp((hand - card["offset"]) / card["factor"]))
print(f"hand score for L000004: {hand} points, PD {p:.4f}")
print("L000004 in scores.csv:", next(r["score"] for r in scores if r["loan_id"] == "L000004"))
print("all agree" if not wrong else "DISAGREE")
EOF
python3 recheck.pytarget disagrees with loans.status on 0 loans
dev: Gini 0.332278 (report 0.332278), KS 0.289621 (report 0.289621)
oot: Gini 0.265176 (report 0.265176), KS 0.214754 (report 0.214754)
hand score for L000004: 584 points, PD 0.1483
L000004 in scores.csv: 584
all agreeThe pair-counting Gini and the every-threshold KS agree with the report to nine decimals, and the by-hand score for L000004 matches scores.csv. If a line disagrees, fix the code before looking at the model.
7. Diagnose the failed bar, then write the sign-off. Save diagnose.py:
cat > diagnose.py <<'EOF'
"""Step 6: diagnose the failed check. Is the inversion between the two lowest bands real, or noise?"""
import csv, json, math
from lib import load, BINNERS
card = json.load(open("scorecard.json"))
rows = load()
dev = [r for r in rows if r["split"] == "dev"]
oot = [r for r in rows if r["split"] == "oot"]
score = {r["loan_id"]: int(r["score"]) for r in csv.DictReader(open("scores.csv"))}
print("bad rate by bin, development against out of time")
for v in card["vars"]:
for b, pts in card["points"][v].items():
d = [r for r in dev if BINNERS[v](r) == b]
o = [r for r in oot if BINNERS[v](r) == b]
print(f" {v:<13} {b:<14} {pts:+3d} pts dev {len(d):>4} loans {sum(r['bad'] for r in d) / len(d):>6.1%} "
f"oot {len(o):>4} loans {sum(r['bad'] for r in o) / len(o):>6.1%}")
# The two lowest bands out of time: is the gap bigger than chance? (difference of two proportions)
ds = sorted(score[r["loan_id"]] for r in dev)
e1, e2 = ds[int(len(ds) * 0.2) - 1], ds[int(len(ds) * 0.4) - 1]
b1 = [r for r in oot if score[r["loan_id"]] <= e1]
b2 = [r for r in oot if e1 < score[r["loan_id"]] <= e2]
p1, p2 = sum(r["bad"] for r in b1) / len(b1), sum(r["bad"] for r in b2) / len(b2)
se = math.sqrt(p1 * (1 - p1) / len(b1) + p2 * (1 - p2) / len(b2))
print(f"\nband <= {e1}: {p1:.1%} of {len(b1)}; band {e1 + 1}-{e2}: {p2:.1%} of {len(b2)}")
print(f"lower band minus next band: {p1 - p2:+.1%}, 95% interval {p1 - p2 - 1.96 * se:+.1%} to {p1 - p2 + 1.96 * se:+.1%}")
EOF
python3 diagnose.pybad rate by bin, development against out of time
bureau_score thin file -10 pts dev 187 loans 20.9% oot 391 loans 15.9%
bureau_score <620 -17 pts dev 71 loans 25.4% oot 123 loans 24.4%
bureau_score 620-699 +0 pts dev 182 loans 15.4% oot 367 loans 16.9%
bureau_score 700-739 +19 pts dev 65 loans 7.7% oot 164 loans 7.9%
bureau_score 740+ +27 pts dev 131 loans 6.1% oot 278 loans 5.8%
kyc_tier tier 1 -6 pts dev 329 loans 19.8% oot 621 loans 16.3%
kyc_tier tier 2-3 +8 pts dev 307 loans 10.7% oot 702 loans 11.7%
inflow_90d under N150k -1 pts dev 482 loans 16.4% oot 847 loans 15.9%
inflow_90d N150k or more +3 pts dev 154 loans 12.3% oot 476 loans 10.1%
band <= 566: 18.9% of 254; band 567-576: 22.2% of 230
lower band minus next band: -3.3%, 95% interval -10.5% to +3.9%The thin-file bin was 20.9% bad in development and 15.9% out of time, the main reason the lowest band is over-predicted. The two lowest bands differ by −3.3 points, with an interval of −10.5 to +3.9 that includes zero: the inversion is not distinguishable from chance. Every other bin is within a few points of its development rate.
Now append a section headed ## Findings and sign-off to report.md by hand (for example with cat >> report.md). Write in your own words, and cover: which bars passed and failed, with the figures; the bootstrap interval and what it means for bar 1; the diagnosis of bar 6 with its interval; your conclusion (sign, sign with conditions, or do not sign); the conditions; and what you would re-run when more loans mature. A reference version for these numbers, to compare with and not to copy:
Conditional pass. Seven of eight bars pass. Out-of-time Gini 0.265 (95% bootstrap interval 0.181 to 0.344) and KS 0.215; the Gini bar is met on the point estimate only. Bar 6 fails: the lowest band’s observed bad rate (18.9%) is below the next band’s (22.2%), a gap of −3.3 points with a 95% interval of −10.5 to +3.9, so it is not distinguishable from chance. The thin-file bin was 20.9% bad in development and 15.9% out of time, so the card over-predicts the lowest band (25.5% against 18.9%). Conditions: monitor the thin-file bin and the lowest band monthly; refit when at least twice the present number of bads is available; use for the salary advance only; the card has not been tested on applicants the old rule declined.
8. Optional, and only after the report is written: check against the answer key. A real lender has no answer key. The lab does: data1/answers/loans_truth.csv holds each loan’s lifetime probability of stopping payment. Save truth.py and compare, by band, what you observed, what the card predicted and the generator’s true average.
cat > truth.py <<'EOF'
"""Optional, after validation: compare with the generator's answer key. A real lender has no such file."""
import csv, json, math
from collections import defaultdict
from lib import load, auc
card = json.load(open("scorecard.json"))
pd_of = lambda s: 1 / (1 + math.exp((s - card["offset"]) / card["factor"]))
truth = {r["loan_id"]: float(r["lifetime_pd"]) for r in csv.DictReader(open("../data1/answers/loans_truth.csv"))}
score = {r["loan_id"]: int(r["score"]) for r in csv.DictReader(open("scores.csv"))}
oot = [r for r in load() if r["split"] == "oot"]
ds = sorted(score[r["loan_id"]] for r in load() if r["split"] == "dev")
edges = [ds[int(len(ds) * q) - 1] for q in (0.2, 0.4, 0.6, 0.8)]
by = defaultdict(list)
for r in oot:
by[sum(score[r["loan_id"]] > e for e in edges)].append(r)
print("band loans observed predicted true PD")
for i in sorted(by):
rs = by[i]
print(f"{i + 1:>4} {len(rs):>6} {sum(r['bad'] for r in rs) / len(rs):>9.1%} "
f"{sum(pd_of(score[r['loan_id']]) for r in rs) / len(rs):>10.1%} {sum(truth[r['loan_id']] for r in rs) / len(rs):>8.1%}")
bad = [r["bad"] for r in oot]
print("Gini of the scorecard:", round(2 * auc([score[r["loan_id"]] for r in oot], bad) - 1, 3))
print("Gini of the true PD (the ceiling for any model on these outcomes):", round(2 * auc([-truth[r["loan_id"]] for r in oot], bad) - 1, 3))
EOF
python3 truth.pyband loans observed predicted true PD
1 254 18.9% 25.5% 22.1%
2 230 22.2% 19.8% 19.6%
3 305 14.4% 14.9% 14.3%
4 231 9.5% 9.8% 11.3%
5 303 5.9% 5.4% 6.1%
Gini of the scorecard: 0.265
Gini of the true PD (the ceiling for any model on these outcomes): 0.489In the lowest band the truth is 22.1%: the card’s 25.5% was too high, the observed 18.9% was too low, and the true ordering of the two lowest bands (22.1% above 19.6%) is the right one. The inversion was sampling noise, which is what the validation said. The true probability gives a Gini of 0.489 on these outcomes, a ceiling no model can pass on these loans. The three-variable card reaches 0.265, so there is room, which is what chapter 2.8 and the alternative-data chapter (2.3) explore. Do not tune the card to this file: you would be fitting to an answer nobody has in production.
Leak the future into the features and watch the numbers lie. Save this as leak.py. It scores every loan by the share of its principal repaid by the cut-off, a column that exists only after the outcome:
cat > leak.py <<'EOF'
"""Break it: score with a column the lender would not have on the application date."""
import csv
from lib import load, auc
loans = {r["id"]: r for r in csv.DictReader(open("../data1/loans.csv"))}
for split in ("dev", "oot"):
rs = [r for r in load() if r["split"] == split]
# the share of the principal repaid by the cut-off: known only afterwards
s = [int(loans[r["loan_id"]]["paid_principal_kobo"]) / int(loans[r["loan_id"]]["principal_kobo"]) for r in rs]
print(split, "Gini using principal repaid by the cut-off:", round(2 * auc(s, [r["bad"] for r in rs]) - 1, 3))
EOF
python3 leak.pyThe output is two lines:
dev Gini using principal repaid by the cut-off: 1.0
oot Gini using principal repaid by the cut-off: 1.0A Gini of 1.000 on development and on out-of-time loans is perfect, which is the warning: no application-time feature separates good from bad perfectly. A borrower who defaulted repaid nothing and a good one repaid everything, so the column is the outcome under another name. Out-of-time testing does not catch this, because the leak is in both periods. Only the rule “a feature must exist on the application date” and a check for numbers that are too good catch it. Then say which of the eight bars, if any, would have flagged the leaked model before it went live, and why not.
Template
# Independent validation report: <model name>, <version>
Validator: <name, team>. Model owner: <name>. Approver: <name, role>. Date: <date>.
Decision needed: <go live / go live with conditions / wait>, from <approver>, by <date>.
## 1. Scope
Model, product and decision it supports. Data and cut-off date. Target definition.
Split (development / out of time) and why. Out of scope: <what this report does not cover>.
## 2. Tests run
| Test | Bar (fixed before the run) | Result | Pass or fail |
Include a second-route re-computation and say whether it agreed.
## 3. Findings, most severe first
| # | Severity (high / medium / low) | Finding | Evidence | Owner |
## 4. How this report could be wrong
<one way, and what would show it>
## 5. Conditions of approval
| Condition | Owner | Due, or trigger |
## 6. Opinion and sign-off
Opinion: <approve / approve with conditions / do not approve>, for <use>.
Validated by <name, date>. Approved by <name, role, date>. WORKED EXAMPLE
At a real lender a validator who did not build the model writes this, and the head of risk, or a model risk committee, approves it. Here Iyabode writes it for Erhuvwu’s salary-advance card; Owoleaf’s head of risk approves.
Scope. The card scores Owoleaf’s salary advance, 1,959 loans, none excluded. Bad is 90 or more days past due at the cut-off of 2026-10-28. Development is applications before 2026-05-01 (636 loans, 98 bad); out of time is the rest (1,323 loans, 183 bad). Out of scope: declined applicants, other products and fairness.
Tests. Seven of eight bars pass. Out-of-time Gini is 0.265 (bar 0.20) and KS 0.215 (bar 0.15); development Gini was 0.332. Predicted bad rate is 14.7% against 13.8% observed. Score PSI is 0.018. Bar 6, observed bad rate never rising with the score, fails. A second route, counting every bad-good pair, agrees with the report to nine decimals.
Findings.
- Medium. The Gini bar is met on the point estimate only: the 95% bootstrap interval is 0.181 to 0.344. Owner: Erhuvwu.
- Medium. The lowest band predicts 25.5% and shows 18.9% (254 loans, interval 14.6% to 24.2%). It sits 3.3 points below the next band, with an interval of −10.5 to +3.9, so it cannot be told from chance. The thin-file bin fell from 20.9% bad to 15.9%.
- Low. The inflow input has the largest PSI, 0.066, well under 0.25.
Could be wrong. Every loan was approved by the old rule, so the card has never seen declined applicants. Outcomes on a small trial of applicants below the old cut-off would show it.
Conditions. Monitor the thin-file bin and the lowest band monthly; refit when bads have doubled; salary advance only.
Opinion. Approve with conditions. Iyabode signs; the head of risk approves.
Now you
You are the validator at an unnamed payday lender in Abuja. Its model owner has built a salary-advance scorecard and wants to replace the hand-made approval rule with it. Use your own run of the lab (or the printed output of steps 2 to 7) as the owner’s submission: sample.py, validate.py, diagnose.py and the recheck.py result. Write the independent validation report on it, with your own bars fixed before you look at the out-of-time rows. The owner’s cover note quotes only the development Gini of 0.332, so decide how your report treats that. Rank every finding, including any bar that fails, and say which conditions you would attach and who owns each. The lender’s credit committee reads the report on Monday and decides whether the card goes live for approvals, goes live with conditions, or waits.
Self-check
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.