Project: a monthly portfolio review with provisions
Rebuild the book at two month-ends, compute the metrics and the IFRS 9 provision, reconcile the allowance to the kobo and write the commentary that explains why it fell while arrears rose
This is a project, not a lesson. You build one month-end pack for Owoleaf’s loan book from the finance lab’s scale 1 data (data1): the metrics, an expected-credit-loss provision under IFRS 9, the movement in that provision between two month-ends, a ledger copy that agrees with it, and the commentary a credit committee reads. Then you run eleven acceptance checks. It uses ideas that three other chapters in this module teach in depth: Portfolio metrics (vintages, roll rates, PAR and the NPL ratio), Expected loss (probability of default, loss given default and exposure) and Provisioning under IFRS 9. This page defines every term where it first appears and its code is complete, so you can work from it alone, and it says where its choices differ from theirs. Everything is standard-library Python, money is integer kobo, and every number is illustrative: Owoleaf is fictional, and nothing here is a regulator’s rule or a lender’s method.
The assignment
You play two people. As Feranmi you build the pack. As Gbolahan you break it: you check that it reconciles, that it uses nothing dated after the day it describes, and that the commentary says nothing the pack does not.
Three things come out.
- A pack for the month ended 30 September 2026: book and flows, arrears, roll rates, vintages, the provision by stage and product, and a sensitivity.
- A reconciliation of the loss allowance from 31 August to 30 September, and of gross principal over the same month, both to the kobo, and a ledger copy that agrees with them.
- A commentary of about 250 words, in which every figure can be found in the pack.
The acceptance checks come first, because a bar written after you have seen the number is a description and not a test. The reference solution passes all eleven. Your figures should match to the kobo if you make the same choices.
| # | Check |
|---|---|
| 1 | The snapshot code, run at the lab’s cut-off of 28 October 2026, reproduces loans.csv (days past due, balance, status) for every loan |
| 2 | Gross principal: opening + disbursed − repaid − written off = closing |
| 3 | Allowance: opening + the movement lines = closing |
| 4 | Both identities hold in every month-end pair from January to September, including months with new lending |
| 5 | Coverage rises with the stage |
| 6 | Stage 3 is exactly the loans 90 or more days past due |
| 7 | No loan carries more loss than its balance |
| 8 | Stage totals add to the pack totals |
| 9 | The ledger copy: trial balance zero, receivable and allowance agree with the pack |
| 10 | The opening figures ignore everything dated after 31 August |
| 11 | The closing figures ignore everything dated after 30 September |
Two dates and one convention
A month-end pack describes the book as it stood on a date. The lab’s loan table describes it on one date only, the cut-off of 28 October 2026, so you rebuild every other date from the schedule and the repayments. The convention matters, so state it once. The book is as at the close of day D: a payment counts if it is dated D or earlier, and an instalment is late only if it fell due before D. Days past due (DPD, defined in the loan lifecycle) is D minus the due date of the oldest instalment not yet paid in full. A late fee does not pay an instalment down. The test of the convention is the cut-off: run at 28 October, the code must reproduce the loan table for all 3,645 loans. If it does, the same code is right at any other date, because nothing in it is specific to the cut-off.
The review month is September 2026, opening 31 August. One fact about the data shapes the whole pack: the last loan was disbursed on 28 June, so in September nothing is lent. The book is in run-off: a book that is collecting what it is owed and lending no more. Run-off is why the denominators in this month’s ratios shrink, and it is a useful test, because the code must handle months with new lending too. Check 4 runs the same code on every month-end pair, five of which have disbursements.
The metrics
The pack uses a handful of measures. Each has a trap.
- Gross principal is the principal still owed on loans that are open: not closed and not written off. Portfolio metrics keeps written-off loans in its portfolio, so its 30 September figures differ from this pack’s: with the 18 written-off loans (₦821,520.19 of principal) left in, gross is ₦136,730,014.68, PAR30 12.06% and the NPL ratio 6.13%, against 11.52% and 5.56% here. This project takes a written-off loan out because the ledger does, and provisioning follows the same convention. The pack ignores interest receivable, so it is gross principal and not the full carrying amount an accountant reports; the tax and accounting chapter in module 4, Tax and accounting for lenders, adds interest on the effective-interest basis.
- PAR1, PAR30 and PAR90, portfolio at risk, are the principal on loans more than 0, more than 30 and 90 or more days past due, divided by gross principal. The 30-day line here is more than 30, matching the IFRS 9 presumption below; portfolio-metrics counts 30 or more, which on this book moves PAR30 only from 11.52% to 11.53%. The NPL ratio, non-performing loans over gross, is PAR90 here because Owoleaf treats 90 days as non-performing. The trap: all three are ratios, so a falling denominator raises them. In run-off they rise whatever the borrowers do.
- Roll rates show where the loans in each arrears bucket at the start of the month are at the end: still there, better, worse, repaid or written off. They separate a worsening book from a shrinking one. The cure and roll ideas are the ones collections measured on actions.
- Vintages group loans by the month they were disbursed. The trap: a young vintage has had little time to go 90 days past due, so its bad share is low because it is young and not because it is good. Compare vintages at the same age, or say that you did not.
- Written off is the policy in
loans.py: 180 or more days past due. The pack applies it at each month-end, so a loan is written off in the month in which it is first at or past 180 days at the close.
Staging under IFRS 9
The provision follows IFRS 9, the international accounting standard for financial instruments, whose impairment model replaced the incurred-loss approach with expected credit loss, or ECL, the probability-weighted estimate of credit losses. A lender sorts each loan into one of three stages and provides accordingly.
IFRS 9 applies to annual periods beginning on or after 1 January 2018. It requires 12-month expected credit loss for a loan whose credit risk has not increased significantly since it was recognised, and lifetime expected credit loss where it has. It presumes, rebuttably, that credit risk has increased significantly when contractual payments are more than 30 days past due, and that default does not occur later than 90 days past dueas of 2026-11. The search for this chapter found the standard’s page and commentary describing the two presumptions, but not the paragraphs themselves. The usual references are paragraphs 5.5.3, 5.5.11 and B5.5.37: read them in the standard before you quote one.
The stages the project uses:
| Stage | Rule | Loss measured |
|---|---|---|
| 1 | 0 to 30 days past due, and no trigger | 12-month ECL |
| 2 | 31 to 89 days past due, or a performing loan whose customer has another loan, not closed, more than 30 days past due (a cross-default trigger) | lifetime ECL |
| 3 | 90 or more days past due | lifetime ECL, with a probability of default of 100% |
The trigger is the project’s own choice and its one qualitative test of significant increase in credit risk (SICR); IFRS 9 does not prescribe it. A loan already written off counts as the late loan that sets it off. Its limit is thin evidence: it is a judgement that other loans of a customer share the risk, and the book supports it with only 10 observations (below). Days past due is a backstop, not the only evidence: a customer who has stopped paying one Owoleaf loan is a worse risk on the others while they are still on time. Every loan in this book matures within 12 months, so for a loan at stage 1 the 12-month and lifetime horizons are nearly the same; the stage still decides which probability you use and what the movement table calls the change.
Measuring the loss
ECL for one loan is three numbers multiplied: exposure at default, EAD (the principal outstanding, here), the probability of default, PD, and the loss given default, LGD, the share of the exposure not recovered. Decisions, limits and pricing used PD and LGD to price a band; here they set a provision. The estimates must come from the book, and only from what was known on the date.
- PD by migration. A loan’s PD is the share of loans in its class that were 90 or more days past due (or written off) some months later. For stage 1, by product, the look-ahead is four months; so is the trigger class’s. For stage 2 by days past due it is two months, since a loan 31 days late and still unpaid is 90 days late 61 days on. The four months are the project’s own choice, not an IFRS 9 requirement: nine month-ends give only five starting months for a four-month look-ahead, and a longer one leaves fewer. Only pairs of month-ends that end on or before the as-of date are used. A floor of 0.5% stops a performing loan getting a PD of zero. A 12-month ECL asks for defaults over the next 12 months, so a four-month look-ahead understates the PD of a loan with many instalments left, such as a 12-instalment personal loan. That limit is the project’s, and the commentary should name it.
- LGD from recoveries. Of the principal outstanding on the day each defaulted loan reached 90 days past due, how much came back afterwards? In this book almost none, so LGD is about 99.9%. That is a property of the generator, in which borrowers who stop paying rarely pay again, and not a fact about lending.
- Two scenarios. IFRS 9 asks for unbiased, probability-weighted loss that reflects reasonable and supportable forecasts. The project uses two illustrative macro scenarios, base (weight 60%, PD × 1.00) and downside (weight 40%, PD × 1.50), and weights the PD. The weights and multipliers are management inputs that the committee would approve, not facts.
- Integer arithmetic. ECL in kobo is EAD × weighted PD × LGD, with PD in parts per million and LGD in basis points, rounded half up. No floating-point money anywhere.
A worked loan is in the lab, so a reviewer can redo it by hand.
The movement, and why the order of steps is policy
The allowance at 30 September is not the allowance at 31 August plus a charge you can read off. IFRS 7, the standard on financial-instrument disclosures, asks lenders to explain the change.
IFRS 7 requires a lender to explain the changes in its loss allowance over the period (paragraph 35H), as a reconciliation from opening to closing allowance by class of instrument, shown separately for 12-month and lifetime expected credit lossas of 2026-11. Search results showed the requirement through a copy of the standard and vendor guides, not the official paragraph text, so check paragraph 35H before you adopt the layout. The project’s stage columns are a simplification of it.
For each loan the project walks the opening loss to the closing loss in four steps, in a fixed order. A loan repaid in full releases its opening loss. A loan that stays moves in three steps: balance change, the new balance at the old stage and old parameters; transfer, the new stage at the old parameters; PD and LGD update, the new parameters. A loan new in the month enters at its closing loss, and a loan written off is first measured at 90-plus, then its allowance is used up. Each step is a difference of two numbers, so the steps telescope and the lines add up to the change exactly, per loan and in total. The order is a judgement: change the order and the same total is split differently between lines. That is why the order is part of the policy and the pack states it.
Two reconciliations follow, and a ledger proves them. Gross principal moves by disbursements, repayments and write-offs. The allowance moves by the lines above. The ledger copy posts opening balances, the month’s repayments, the allowance charge and the write-offs as balanced journals in SQLite, using the double entry that Payments built: receivable, allowance, cash and impairment expense. If its balances equal the pack’s, the pack and the books agree.
What the pack cannot see
- A forecast. PDs are migration rates from five starting months of history. The trigger’s PD rests on 10 observations (9 different loans, 5 of which went 90+), so it is close to a guess, and the SME PD rests on one bad loan in 469 observations.
- Interest and fees. The pack provides on principal. Interest receivable and effective-interest income are left to Tax and accounting for lenders in module 4.
- Rescheduled loans. Nothing in the lab’s book is restructured. Restructuring and forbearance, another chapter in this module, covers how a restructure resets days past due and affects staging.
- A regulator’s provisioning. Whether Owoleaf’s licence also requires a prudential provision beside the IFRS 9 one is a licensing question for module 4, and the module 3 chapter on IFRS 9 compares the two.
- A closed cohort. Every loan was made in the first half of the year, so there is no mix of old and new vintages to learn from.
Lab
You work in a new folder, labs/finance/review. Run every command from inside it. The data is data1 at seed 42 and scale 1, so your numbers match the ones below if you make the same choices. Each script prints its checks; read the output before moving on.
1. Check the data.
cd labs/finance
ls data1/loans.csv data1/schedule.csv data1/repayments.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 book3.py --out data1)
python3 check.py --db data1/finance.sqlite | tail -1
mkdir -p review && cd reviewIf data1 exists, ls prints four paths and nothing is built; otherwise the generators run (about 40 seconds). The check ends with:
OK: all invariants hold2. The library, and the proof of the snapshot. lib.py holds everything the other scripts share: the loader, the snapshot at any date, staging, the PDs and the LGD, and the ECL. It never reads status, days_past_due or any balance column of loans.csv; it rebuilds them from the schedule and the repayments. Save it, then save snapcheck.py, which rebuilds the book at the cut-off and compares it with the loan table.
cat > lib.py <<'EOF'
"""Shared code for the monthly portfolio review. Standard library only. Money is integer kobo.
Nothing here reads loans.status, days_past_due or any *_outstanding / paid_* column: every figure is
rebuilt from the schedule and the repayments dated on or before the as-of date."""
import csv, collections, datetime as dt, os
DATA = os.environ.get("DATA", "../data1/")
d = dt.date.fromisoformat
STAGE2_DPD, STAGE3_DPD, WRITE_OFF_DPD = 30, 90, 180 # Owoleaf policy (loans.py) and the IFRS 9 backstops
H1, H2 = 4, 2 # months of look-ahead used for the stage 1 and stage 2 PDs
SCENARIOS = [("base", 60, 100), ("downside", 40, 150)] # ILLUSTRATIVE: name, weight %, PD multiplier %
MONTH_ENDS = ["2026-01-31", "2026-02-28", "2026-03-31", "2026-04-30", "2026-05-31",
"2026-06-30", "2026-07-31", "2026-08-31", "2026-09-30"]
PRODUCTS = ["SAL", "BNPL", "PL", "SME"]
PD_FLOOR_PPM = 5_000 # ILLUSTRATIVE: no performing loan gets a PD below 0.5%
MIN_TRIGGER_N = 5 # fewer observations than this: use the stage 2 PD
def naira(k):
sign = "-" if k < 0 else ""
return f"{sign}₦{abs(k) // 100:,}.{abs(k) % 100:02d}"
def load(asof=None):
"""Read the book. With asof, drop everything dated after it (the truncation test)."""
rd = lambda n: csv.DictReader(open(DATA + n))
loans = {}
for r in rd("loans.csv"):
if asof and d(r["disbursed_at"]) > asof:
continue
loans[r["id"]] = dict(id=r["id"], customer=r["customer_id"], product=r["product"],
principal=int(r["principal_kobo"]), disbursed=d(r["disbursed_at"]))
sched, reps = collections.defaultdict(list), collections.defaultdict(list)
for r in rd("schedule.csv"):
if r["loan_id"] in loans:
sched[r["loan_id"]].append((int(r["instalment"]), d(r["due_date"]), int(r["total_kobo"])))
for r in rd("repayments.csv"):
if r["loan_id"] in loans and (not asof or d(r["paid_at"]) <= asof):
reps[r["loan_id"]].append((d(r["paid_at"]), int(r["instalment"]), int(r["amount_kobo"]) - int(r["late_fee_kobo"]),
int(r["principal_kobo"]), int(r["interest_kobo"]), int(r["late_fee_kobo"])))
return dict(loans=loans, sched=sched, reps=reps)
def snapshot(data, asof):
"""The book as at the close of asof: payments dated on or before it count; an instalment is late
only if it fell due before it. Returns {loan_id: row}."""
out = {}
for lid, l in data["loans"].items():
if l["disbursed"] > asof:
continue
rec, paid_p = collections.Counter(), 0
for paid, n, pi, p, i, f in data["reps"][lid]:
if paid <= asof:
rec[n] += pi
paid_p += p
unpaid = [due for n, due, tot in data["sched"][lid] if due < asof and rec[n] < tot]
oldest = min(unpaid) if unpaid else None
dpd = (asof - oldest).days if oldest else 0
o = l["principal"] - paid_p
state = "closed" if o == 0 else ("written_off" if dpd >= WRITE_OFF_DPD else "open")
out[lid] = dict(id=lid, product=l["product"], customer=l["customer"], disbursed=l["disbursed"],
principal=l["principal"], dpd=dpd, out=o, oldest=oldest, state=state)
return out
def add_stages(snap):
"""Stage 3: 90+ days past due. Stage 2: 31-89 days past due, or a loan that is still performing whose
customer has another open loan more than 30 days past due (cross-default trigger). Otherwise stage 1."""
worse = set()
byc = collections.defaultdict(list)
for r in snap.values():
if r["state"] != "closed":
byc[r["customer"]].append(r)
for rs in byc.values():
if any(x["dpd"] > STAGE2_DPD for x in rs):
worse |= {x["id"] for x in rs if x["dpd"] <= STAGE2_DPD}
for r in snap.values():
if r["state"] == "closed":
r["stage"], r["cls"] = "-", "-"
elif r["dpd"] >= STAGE3_DPD:
r["stage"], r["cls"] = "3", "3"
elif r["dpd"] > STAGE2_DPD:
r["stage"], r["cls"] = "2", "2dpd"
elif r["id"] in worse:
r["stage"], r["cls"] = "2", "2trigger"
else:
r["stage"], r["cls"] = "1", "1:" + r["product"]
return snap
def months_before(asof):
return [m for m in MONTH_ENDS if d(m) <= asof]
def params(data, asof):
"""PD by class and the LGD, using only month-ends and payments on or before asof. A PD is the share of
loans in a class at month-end t that were 90+ days past due (or written off) h months later."""
ends = months_before(asof)
snaps = {m: add_stages(snapshot(data, d(m))) for m in ends}
obs = collections.defaultdict(lambda: [0, 0])
for i, a in enumerate(ends):
for lid, r in snaps[a].items():
if r["cls"] in ("-", "3"):
continue
h = H2 if r["cls"] == "2dpd" else H1
if i + h >= len(ends):
continue
later = snaps[ends[i + h]][lid]
obs[r["cls"]][0] += 1
obs[r["cls"]][1] += later["out"] > 0 and later["dpd"] >= STAGE3_DPD
pd = {}
for c, (n, bad) in obs.items():
ppm = (bad * 1_000_000 * 2 + n) // (2 * n)
pd[c] = dict(n=n, bad=bad, ppm=ppm if c == "2dpd" else max(ppm, PD_FLOOR_PPM))
for c in ["1:" + x for x in PRODUCTS]: # early months: nothing observed yet, so the floor
pd.setdefault(c, dict(n=0, bad=0, ppm=PD_FLOOR_PPM, note="no data"))
pd.setdefault("2dpd", dict(n=0, bad=0, ppm=1_000_000, note="no data")) # and 'stage 2 goes bad' until shown otherwise
if pd.get("2trigger", {"n": 0})["n"] < MIN_TRIGGER_N: # too few observed: treat like stage 2 by days
pd["2trigger"] = dict(pd["2dpd"], note="fallback")
pd["3"] = dict(n=0, bad=0, ppm=1_000_000)
# LGD: of the principal outstanding the day each loan reached 90 days past due, how much came back after?
ead = rec = 0
last = snaps[ends[-1]]
for lid, r in last.items():
if r["dpd"] >= STAGE3_DPD:
dd = asof - dt.timedelta(days=r["dpd"] - STAGE3_DPD)
paid_by_dd = sum(p for pd_, n, pi, p, i, f in data["reps"][lid] if pd_ <= dd)
paid_by_asof = sum(p for pd_, n, pi, p, i, f in data["reps"][lid] if pd_ <= asof)
ead += data["loans"][lid]["principal"] - paid_by_dd
rec += paid_by_asof - paid_by_dd
lgd_bp = 10_000 - (rec * 10_000 * 2 + ead) // (2 * ead) if ead else 10_000
return dict(pd=pd, lgd_bp=lgd_bp, lgd_ead=ead, lgd_rec=rec)
def weighted_pd(ppm, scenarios=None):
"""Probability-weighted PD over the scenarios, each capped at 100%. Integer parts per million."""
return sum(w * min(1_000_000, ppm * mult // 100) for _, w, mult in (scenarios or SCENARIOS)) // 100
def ecl(out, cls, p, scenarios=None):
"""Expected credit loss in kobo: EAD x weighted PD x LGD, rounded half up, integers only."""
pdw = weighted_pd(p["pd"][cls]["ppm"], scenarios)
return (out * pdw * p["lgd_bp"] + 5 * 10**9) // 10**10
def measure(data, asof, p=None):
snap = add_stages(snapshot(data, asof))
p = p or params(data, asof)
for r in snap.values():
r["ecl"] = ecl(r["out"], r["cls"], p) if r["state"] == "open" else 0
if r["state"] == "written_off": # as if still carried, before the write-off
r["ecl_pre"] = ecl(r["out"], "3", p)
return snap, p
EOF
cat > snapcheck.py <<'EOF'
"""Prove the snapshot code: rebuilt at the cut-off it must equal the loans table, loan by loan."""
import csv
from lib import *
data = load()
cut = d("2026-10-28")
snap = snapshot(data, cut)
bad = 0
for r in csv.DictReader(open(DATA + "loans.csv")):
s = snap[r["id"]]
status = {"closed": "closed", "written_off": "written_off"}.get(s["state"])
if status is None:
status = "default" if s["dpd"] >= 90 else "arrears" if s["dpd"] > 0 else "current"
if (s["dpd"], s["out"], status) != (int(r["days_past_due"]), int(r["outstanding_principal_kobo"]), r["status"]):
bad += 1
print(f"cut-off {cut}: {len(snap)} loans rebuilt, {bad} differ from loans.csv (days past due, balance, status)")
print()
print(f"{'month-end':<11}{'open':>6}{'closed':>8}{'wr-off':>8}{'0':>6}{'1-30':>6}{'31-89':>7}{'90+':>5}{'gross principal':>20}")
for m in MONTH_ENDS:
s = snapshot(data, d(m))
o = [r for r in s.values() if r["state"] == "open"]
c = collections.Counter(("current" if r["dpd"] == 0 else "1-30" if r["dpd"] <= 30 else "31-89" if r["dpd"] < 90 else "90+") for r in o)
print(f"{m:<11}{len(o):>6}{sum(r['state']=='closed' for r in s.values()):>8}{sum(r['state']=='written_off' for r in s.values()):>8}"
f"{c['current']:>6}{c['1-30']:>6}{c['31-89']:>7}{c['90+']:>5}{naira(sum(r['out'] for r in o)):>20}")
EOF
python3 snapcheck.pycut-off 2026-10-28: 3645 loans rebuilt, 0 differ from loans.csv (days past due, balance, status)
month-end open closed wr-off 0 1-30 31-89 90+ gross principal
2026-01-31 35 0 0 34 1 0 0 ₦7,176,750.00
2026-02-28 153 20 0 151 2 0 0 ₦27,794,989.40
2026-03-31 443 95 0 416 25 2 0 ₦84,388,892.05
2026-04-30 886 280 0 811 59 16 0 ₦165,883,224.26
2026-05-31 1514 660 0 1337 121 53 3 ₦277,807,140.14
2026-06-30 2369 1276 0 2071 169 112 17 ₦438,468,149.27
2026-07-31 1440 2205 0 990 217 173 60 ₦307,134,617.39
2026-08-31 1089 2553 3 685 34 236 134 ₦207,639,828.76
2026-09-30 905 2722 18 521 22 142 220 ₦135,908,494.49The first line is check 1: all 3,645 loans rebuilt from the schedule and repayments match the loan table, so the snapshot convention is right. The table is the book at each month-end. Open loans grow to 2,369 at the end of June and then run off to 905 at the end of September. The 90+ column is stage 3, and the wr-off column holds loans 180 or more days past due, which leave the gross principal.
3. The metrics half of the pack. review.py holds the pack’s functions: flows, metrics, roll rates, vintages, the allowance movement and a build that returns them all. pack.py prints the first half.
cat > review.py <<'EOF'
"""The month-end pack: metrics, provision, movement and the two reconciliations. Standard library only."""
import collections
from lib import *
def bucket(dpd):
return "current" if dpd == 0 else "1-30" if dpd <= 30 else "31-89" if dpd < 90 else "90+"
BUCKETS = ["current", "1-30", "31-89", "90+"]
def gross(snap):
return sum(r["out"] for r in snap.values() if r["state"] == "open")
def flows(data, a, b, s0, s1):
"""Gross principal movement from a to b, in kobo. Written off at b means 180+ days past due at b."""
disb = [r for r in s1.values() if a < r["disbursed"] <= b]
repaid = rec = interest = fees = 0
for lid, rows in data["reps"].items():
wo0 = lid in s0 and s0[lid]["state"] == "written_off"
for paid, n, pi, p, i, f in rows:
if a < paid <= b:
interest += i
fees += f
if wo0:
rec += p
else:
repaid += p
wo = [r for r in s1.values() if r["state"] == "written_off" and not (r["id"] in s0 and s0[r["id"]]["state"] == "written_off")]
return dict(disbursed_n=len(disb), disbursed=sum(r["principal"] for r in disb), repaid=repaid,
written_off_n=len(wo), written_off=sum(r["out"] for r in wo), recovered=rec,
interest=interest, fees=fees)
def metrics(s1):
g = gross(s1)
by = collections.Counter()
n = collections.Counter()
prod = collections.defaultdict(int)
for r in s1.values():
if r["state"] == "open":
by[bucket(r["dpd"])] += r["out"]
n[bucket(r["dpd"])] += 1
prod[r["product"]] += r["out"]
par = lambda lo: sum(r["out"] for r in s1.values() if r["state"] == "open" and r["dpd"] >= lo)
return dict(gross=g, loans=sum(n.values()), by_bucket=dict(by), n_bucket=dict(n), by_product=dict(prod),
par1=par(1), par30=par(31), par90=par(90),
par1_pct=round(100 * par(1) / g, 2), par30_pct=round(100 * par(31) / g, 2), par90_pct=round(100 * par(90) / g, 2))
def roll(s0, s1):
"""Count and opening balance by opening bucket and closing outcome, loans open at a."""
cnt = {b: collections.Counter() for b in BUCKETS}
bal = {b: collections.Counter() for b in BUCKETS}
for lid, r in s0.items():
if r["state"] != "open":
continue
z = s1[lid]
to = "repaid" if z["state"] == "closed" else "written off" if z["state"] == "written_off" else bucket(z["dpd"])
cnt[bucket(r["dpd"])][to] += 1
bal[bucket(r["dpd"])][to] += r["out"]
return cnt, bal
def vintages(s1):
v = collections.defaultdict(lambda: [0, 0, 0, 0])
for r in s1.values():
k = r["disbursed"].strftime("%Y-%m")
v[k][0] += 1
v[k][1] += r["principal"]
if r["dpd"] >= STAGE3_DPD and r["out"] > 0:
v[k][2] += 1
v[k][3] += r["principal"]
return dict(v)
def movement(s0, s1, p0, p1):
"""Allowance movement a -> b. Per loan the steps telescope, so the lines add to the change exactly:
exposure (new balance, old stage, old PD) -> stage transfer (new stage, old PD) -> PD and LGD update."""
L = collections.OrderedDict()
add = lambda k, v: L.__setitem__(k, L.get(k, 0) + v)
opening = sum(r["ecl"] for r in s0.values())
for k in ("repaid in full", "balance change (repayments)", "transfers", "PD and LGD update", "new loans", "written off"):
L[k] = 0
trans = collections.Counter()
for lid, r0 in s0.items():
if r0["state"] != "open":
continue
r1 = s1[lid]
if r1["state"] == "closed":
add("repaid in full", -r0["ecl"])
continue
wo = r1["state"] == "written_off"
cls1 = "3" if wo else r1["cls"]
o1 = r1["out"]
e_exp = ecl(o1, r0["cls"], p0)
e_tr = ecl(o1, cls1, p0)
e_end = r1["ecl_pre"] if wo else r1["ecl"]
add("balance change (repayments)", e_exp - r0["ecl"])
if e_tr - e_exp or r0["stage"] != cls1[0]:
trans[f"{r0['stage']}->{cls1[0]}"] += e_tr - e_exp
add("transfers", e_tr - e_exp)
add("PD and LGD update", e_end - e_tr)
if wo:
add("written off", -e_end)
for lid, r1 in s1.items():
if lid not in s0 and r1["state"] == "open":
add("new loans", r1["ecl"])
closing = sum(r["ecl"] for r in s1.values())
return dict(opening=opening, lines=dict(L), transfers=dict(trans), closing=closing,
ties=opening + sum(L.values()) == closing)
def by_stage(s1):
out = collections.defaultdict(lambda: [0, 0, 0])
for r in s1.values():
if r["state"] == "open":
o = out[r["stage"]]
o[0] += 1
o[1] += r["out"]
o[2] += r["ecl"]
return dict(out)
def build(data, a, b):
s0, p0 = measure(data, a)
s1, p1 = measure(data, b)
return dict(a=a, b=b, s0=s0, s1=s1, p0=p0, p1=p1, flows=flows(data, a, b, s0, s1), metrics=metrics(s1),
roll=roll(s0, s1), mv=movement(s0, s1, p0, p1), stages=by_stage(s1), stages0=by_stage(s0))
EOF
cat > pack.py <<'EOF'
"""Print the metrics half of the month-end pack for September 2026."""
import json, sys
from review import *
A, B = d("2026-08-31"), d("2026-09-30")
data = load()
R = build(data, A, B)
M, F = R["metrics"], R["flows"]
g0 = gross(R["s0"])
print(f"MONTH-END PACK {B} (opening {A})")
print("\n1. Book and flows (principal)")
print(f" opening gross principal {naira(g0):>20}")
print(f" + disbursed {naira(F['disbursed']):>20} {F['disbursed_n']} loans")
print(f" - principal repaid {naira(F['repaid']):>20}")
print(f" - written off {naira(F['written_off']):>20} {F['written_off_n']} loans")
print(f" closing gross principal {naira(M['gross']):>20} {M['loans']} loans")
print(f" identity: {g0 + F['disbursed'] - F['repaid'] - F['written_off'] == M['gross']} "
f"(recoveries on loans already written off: {naira(F['recovered'])}; interest received {naira(F['interest'])}; late fees {naira(F['fees'])})")
print("\n2. Gross principal by product")
for p in PRODUCTS:
v = M["by_product"].get(p, 0)
print(f" {p:<5}{naira(v):>20} {100 * v / M['gross']:5.1f}%")
print("\n3. Arrears")
for b in BUCKETS:
v = M["by_bucket"].get(b, 0)
print(f" {b:<8}{M['n_bucket'].get(b, 0):>5} loans {naira(v):>20} {100 * v / M['gross']:5.1f}%")
M0 = metrics(R["s0"])
print(f" {'':<24}{'31 Aug':>10}{'30 Sep':>10}")
for k, label in (("par1_pct", "PAR1"), ("par30_pct", "PAR30"), ("par90_pct", "PAR90 / NPL ratio")):
print(f" {label:<24}{M0[k]:>9}%{M[k]:>9}%")
print(f" {'90+ balance':<24}{naira(M0['par90']):>20}{naira(M['par90']):>20}")
print("\n4. Roll rates, loans open at 31 August: where they were at 30 September (share of loans)")
cnt, bal = R["roll"]
cols = BUCKETS + ["repaid", "written off"]
print(f" {'from':<9}{'n':>5}" + "".join(f"{c:>12}" for c in cols))
for b in BUCKETS:
n = sum(cnt[b].values())
print(f" {b:<9}{n:>5}" + "".join(f"{100 * cnt[b][c] / n:>11.1f}%" for c in cols))
print("\n5. Vintages: share of each month's disbursed principal that is 90+ days past due or written off")
V = vintages({k: v for k, v in R["s1"].items()})
for k in sorted(V):
n, pr, bn, bp = V[k]
print(f" {k} {n:>4} loans {naira(pr):>20} 90+: {bn:>3} loans, {100 * bp / pr:5.1f}% of principal")
EOF
python3 pack.pyMONTH-END PACK 2026-09-30 (opening 2026-08-31)
1. Book and flows (principal)
opening gross principal ₦207,639,828.76
+ disbursed ₦0.00 0 loans
- principal repaid ₦71,264,819.51
- written off ₦466,514.76 15 loans
closing gross principal ₦135,908,494.49 905 loans
identity: True (recoveries on loans already written off: ₦0.00; interest received ₦7,121,087.99; late fees ₦55,000.00)
2. Gross principal by product
SAL ₦6,572,259.00 4.8%
BNPL ₦1,730,008.00 1.3%
PL ₦37,316,377.81 27.5%
SME ₦90,289,849.68 66.4%
3. Arrears
current 521 loans ₦115,872,833.46 85.3%
1-30 22 loans ₦4,382,281.39 3.2%
31-89 142 loans ₦8,094,977.29 6.0%
90+ 220 loans ₦7,558,402.35 5.6%
31 Aug 30 Sep
PAR1 10.16% 14.74%
PAR30 6.74% 11.52%
PAR90 / NPL ratio 2.28% 5.56%
90+ balance ₦4,727,098.46 ₦7,558,402.35
4. Roll rates, loans open at 31 August: where they were at 30 September (share of loans)
from n current 1-30 31-89 90+ repaid written off
current 685 74.2% 3.1% 0.0% 0.0% 22.8% 0.0%
1-30 34 32.4% 2.9% 32.4% 0.0% 32.4% 0.0%
31-89 236 0.8% 0.0% 55.5% 42.8% 0.8% 0.0%
90+ 134 0.0% 0.0% 0.0% 88.8% 0.0% 11.2%
5. Vintages: share of each month's disbursed principal that is 90+ days past due or written off
2026-01 35 loans ₦7,182,000.00 90+: 2 loans, 4.9% of principal
2026-02 138 loans ₦22,021,000.00 90+: 14 loans, 5.3% of principal
2026-03 365 loans ₦64,902,000.00 90+: 44 loans, 2.6% of principal
2026-04 628 loans ₦105,667,000.00 90+: 69 loans, 2.2% of principal
2026-05 1008 loans ₦165,317,000.00 90+: 96 loans, 2.0% of principal
2026-06 1471 loans ₦246,668,000.00 90+: 13 loans, 0.2% of principalRead it as Gbolahan. Nothing was disbursed. Gross principal falls by ₦71,264,819.51 of repayments and ₦466,514.76 of write-offs, and the identity is true. PAR30 and the NPL ratio both rise, yet the 90+ balance rose by about ₦2.8m while gross principal fell by about ₦71.7m, so both effects are at work. The roll rates show what is real: 42.8% of the loans 31 to 89 days past due went 90+, and 11.2% of the loans already 90+ were written off. Vintage 2026-06 shows 0.2% only because it is young.
4. Stage the book and measure the provision. provision.py prints the PDs and LGD estimated from data up to 30 September, the ECL by stage and product, a sensitivity, and one loan worked out in full.
cat > provision.py <<'EOF'
"""IFRS 9 staging and expected credit loss at 30 September 2026, with the parameters and a sensitivity."""
import collections
from review import *
B = d("2026-09-30")
data = load()
s1, p = measure(data, B)
print(f"PARAMETERS at {B}: only month-ends and payments on or before it were used")
print(f" {'class':<10}{'observed':>9}{'went 90+':>10}{'PD (ppm)':>10}{'PD':>8} weighted PD")
for c in sorted(p["pd"]):
v = p["pd"][c]
print(f" {c:<10}{v['n']:>9}{v['bad']:>10}{v['ppm']:>10}{v['ppm'] / 10000:>7.2f}% {weighted_pd(v['ppm']) / 10000:6.2f}%" + (" (fallback: too few observations)" if v.get("note") else ""))
print(f" LGD {p['lgd_bp'] / 100:.2f}%: of {naira(p['lgd_ead'])} outstanding when loans reached 90 days past due, {naira(p['lgd_rec'])} came back")
print(" scenarios: " + ", ".join(f"{n} weight {w}% PD x{m / 100:.2f}" for n, w, m in SCENARIOS))
print("\nECL BY STAGE")
print(f" {'stage':<6}{'loans':>6}{'gross principal':>20}{'ECL':>18}{'coverage':>10}")
st = by_stage(s1)
tot = [0, 0, 0]
for k in "123":
n, g, e = st[k]
tot = [tot[0] + n, tot[1] + g, tot[2] + e]
print(f" {k:<6}{n:>6}{naira(g):>20}{naira(e):>18}{100 * e / g:>9.2f}%")
print(f" {'total':<6}{tot[0]:>6}{naira(tot[1]):>20}{naira(tot[2]):>18}{100 * tot[2] / tot[1]:>9.2f}%")
print("\nECL BY PRODUCT AND STAGE")
bp = collections.defaultdict(lambda: [0, 0])
for r in s1.values():
if r["state"] == "open":
bp[(r["product"], r["stage"])][0] += r["out"]
bp[(r["product"], r["stage"])][1] += r["ecl"]
for pr in PRODUCTS:
print(" " + f"{pr:<5}" + "".join(f" s{k}: {naira(bp[(pr, k)][1]):>16}" for k in "123"))
# Sensitivity: the same loans and the same PDs under one scenario at a time (no weighting).
print("\nSENSITIVITY (total ECL)")
for name, w, m in [("as reported (weighted)", None, None)] + SCENARIOS:
if w is None:
e = tot[2]
else:
e = sum(ecl(r["out"], r["cls"], p, [(name, 100, m)]) for r in s1.values() if r["state"] == "open")
print(f" {name:<24}{naira(e):>18}")
# What if the SME stage 1 PD, which rests on one bad loan in 469 observations, were 2% and not the 0.5% floor?
q = dict(p, pd=dict(p["pd"], **{"1:SME": dict(p["pd"]["1:SME"], ppm=20_000)}))
e = sum(ecl(r["out"], r["cls"], q) for r in s1.values() if r["state"] == "open")
print(f" {'SME stage 1 PD at 2%':<24}{naira(e):>18} (+{naira(e - tot[2])})")
# One loan worked by hand, so a reviewer can redo it.
w = next(r for r in s1.values() if r["state"] == "open" and r["cls"] == "1:PL")
ppm = p["pd"][w["cls"]]["ppm"]
print(f"\nWORKED LOAN {w['id']} ({w['product']}, stage {w['stage']}, class {w['cls']}, {w['dpd']} days past due)")
print(f" exposure (outstanding principal) {w['out']} kobo = {naira(w['out'])}")
for name, wt, mult in SCENARIOS:
print(f" {name}: PD {ppm} ppm x {mult}% = {min(1_000_000, ppm * mult // 100)} ppm, weight {wt}%")
pdw = weighted_pd(ppm)
print(f" weighted PD = {pdw} ppm; LGD = {p['lgd_bp']} bp")
print(f" ECL = {w['out']} x {pdw} x {p['lgd_bp']} / 10^10, half up = {ecl(w['out'], w['cls'], p)} kobo = {naira(ecl(w['out'], w['cls'], p))}")
EOF
python3 provision.pyPARAMETERS at 2026-09-30: only month-ends and payments on or before it were used
class observed went 90+ PD (ppm) PD weighted PD
1:BNPL 699 62 88698 8.87% 10.64%
1:PL 487 15 30801 3.08% 3.70%
1:SAL 1292 263 203560 20.36% 24.43%
1:SME 469 1 5000 0.50% 0.60%
2dpd 356 351 985955 98.60% 99.16%
2trigger 10 6 600000 60.00% 72.00%
3 0 0 1000000 100.00% 100.00%
LGD 99.87%: of ₦8,390,879.23 outstanding when loans reached 90 days past due, ₦10,956.69 came back
scenarios: base weight 60% PD x1.00, downside weight 40% PD x1.50
ECL BY STAGE
stage loans gross principal ECL coverage
1 527 ₦118,501,023.68 ₦1,774,050.47 1.50%
2 158 ₦9,849,068.46 ₦9,277,630.01 94.20%
3 220 ₦7,558,402.35 ₦7,548,576.55 99.87%
total 905 ₦135,908,494.49 ₦18,600,257.03 13.69%
ECL BY PRODUCT AND STAGE
SAL s1: ₦0.00 s2: ₦2,405,598.83 s3: ₦4,137,672.08
BNPL s1: ₦0.00 s2: ₦379,156.95 s3: ₦1,345,379.80
PL s1: ₦1,270,157.36 s2: ₦1,197,498.44 s3: ₦1,492,270.87
SME s1: ₦503,893.11 s2: ₦5,295,375.79 s3: ₦573,253.80
SENSITIVITY (total ECL)
as reported (weighted) ₦18,600,257.03
base ₦18,048,951.80
downside ₦19,427,214.64
SME stage 1 PD at 2% ₦20,111,936.09 (+₦1,511,679.06)
WORKED LOAN L000007 (PL, stage 1, class 1:PL, 0 days past due)
exposure (outstanding principal) 3985702 kobo = ₦39,857.02
base: PD 30801 ppm x 100% = 30801 ppm, weight 60%
downside: PD 30801 ppm x 150% = 46201 ppm, weight 40%
weighted PD = 36961 ppm; LGD = 9987 bp
ECL = 3985702 x 36961 x 9987 / 10^10, half up = 147124 kobo = ₦1,471.24Coverage climbs from 1.50% in stage 1 through 94.20% in stage 2 to 99.87% in stage 3, which is check 5. Stage 3 is below 100% only because of the LGD, 99.87%. The stage 1 PD for SAL is 20.36%, but no salary advance is left in stage 1 at the month-end, so it provides nothing. Redo the worked loan: 3,985,702 × 36,961 × 9,987 ÷ 10^10 = 147,124.02, which rounds to 147,124 kobo. The weighted allowance sits ₦0.55m above the base scenario and ₦0.83m below the downside one, and it rises by ₦1.51m if SME carries a 2% PD instead of the floor.
5. Reconcile the allowance. mv.py prints the movement from 31 August to 30 September, the PDs at both dates, and the charge.
cat > mv.py <<'EOF'
"""Reconcile the loss allowance from 31 August to 30 September, to the kobo."""
from review import *
A, B = d("2026-08-31"), d("2026-09-30")
data = load()
R = build(data, A, B)
mv, F = R["mv"], R["flows"]
print(f"LOSS ALLOWANCE MOVEMENT {A} to {B}")
print(f" {'opening allowance':<34}{naira(mv['opening']):>20}")
for k, v in mv["lines"].items():
print(f" {k:<34}{naira(v):>20}")
print(f" {'closing allowance':<34}{naira(mv['closing']):>20}")
print(f" lines add up to the closing allowance exactly: {mv['opening'] + sum(mv['lines'].values()) == mv['closing']}")
print("\n of which transfers, by stage (ECL change from the new stage, old parameters):")
for k, v in sorted(mv["transfers"].items()):
print(f" stage {k:<6}{naira(v):>18}")
print("\n PD by class (before weighting) and the LGD at the two dates:")
for c in sorted(R["p1"]["pd"]):
a0, a1 = R["p0"]["pd"][c], R["p1"]["pd"][c]
obs = lambda v: "fallback" if v.get("note") == "fallback" else f"{v['n']} obs"
print(f" {c:<10}{a0['ppm'] / 10000:>8.2f}% ({obs(a0)}){a1['ppm'] / 10000:>10.2f}% ({obs(a1)})")
print(f" {'LGD':<10}{R['p0']['lgd_bp'] / 100:>8.2f}%{'':>9}{R['p1']['lgd_bp'] / 100:>10.2f}%")
print(f" coverage (allowance / gross principal): {100 * mv['opening'] / gross(R['s0']):.2f}% at 31 August, {100 * mv['closing'] / gross(R['s1']):.2f}% at 30 September")
print("\n PD and LGD update, by the class the loan ended in:")
upd = collections.Counter()
for lid, r0 in R["s0"].items():
r1 = R["s1"].get(lid)
if r0["state"] == "open" and r1 and r1["state"] != "closed":
wo = r1["state"] == "written_off"
c1 = "3" if wo else r1["cls"]
upd[c1] += (r1["ecl_pre"] if wo else r1["ecl"]) - ecl(r1["out"], c1, R["p0"])
for c, v in sorted(upd.items()):
print(f" {c:<10}{naira(v):>18}")
used = -mv["lines"]["written off"]
charge = mv["closing"] - mv["opening"] + used
print("\nCHARGE TO PROFIT AND LOSS")
print(f" closing - opening + allowance used on write-offs = {naira(charge)}")
print(f" the movement lines other than 'written off' sum to {naira(sum(v for k, v in mv['lines'].items() if k != 'written off'))}")
print(f" gross written off {naira(F['written_off'])}, allowance used {naira(used)}, so {naira(F['written_off'] - used)} was not provided for")
print(f" total impairment expense for the month: {naira(charge + F['written_off'] - used)}")
by0, by1 = R["stages0"], R["stages"]
print("\nCLOSING ALLOWANCE BY STAGE")
for k in "123":
print(f" stage {k}: opening {naira(by0[k][2]):>18} closing {naira(by1[k][2]):>18}")
EOF
python3 mv.pyLOSS ALLOWANCE MOVEMENT 2026-08-31 to 2026-09-30
opening allowance ₦19,811,176.58
repaid in full -₦714,666.78
balance change (repayments) -₦1,640,252.28
transfers ₦2,721,584.76
PD and LGD update -₦1,111,676.96
new loans ₦0.00
written off -₦465,908.29
closing allowance ₦18,600,257.03
lines add up to the closing allowance exactly: True
of which transfers, by stage (ECL change from the new stage, old parameters):
stage 1->2 ₦3,055,913.40
stage 2->1 -₦355,908.24
stage 2->3 ₦21,579.60
PD by class (before weighting) and the LGD at the two dates:
1:BNPL 7.10% (352 obs) 8.87% (699 obs)
1:PL 4.62% (238 obs) 3.08% (487 obs)
1:SAL 20.29% (685 obs) 20.36% (1292 obs)
1:SME 0.50% (221 obs) 0.50% (469 obs)
2dpd 98.91% (183 obs) 98.60% (356 obs)
2trigger 98.91% (fallback) 60.00% (10 obs)
3 100.00% (0 obs) 100.00% (0 obs)
LGD 99.78% 99.87%
coverage (allowance / gross principal): 9.54% at 31 August, 13.69% at 30 September
PD and LGD update, by the class the loan ended in:
1:PL -₦634,031.23
1:SME ₦454.19
2dpd -₦7,872.07
2trigger -₦477,450.33
3 ₦7,222.48
CHARGE TO PROFIT AND LOSS
closing - opening + allowance used on write-offs = -₦745,011.26
the movement lines other than 'written off' sum to -₦745,011.26
gross written off ₦466,514.76, allowance used ₦465,908.29, so ₦606.47 was not provided for
total impairment expense for the month: -₦744,404.79
CLOSING ALLOWANCE BY STAGE
stage 1: opening ₦3,241,110.99 closing ₦1,774,050.47
stage 2: opening ₦11,853,366.70 closing ₦9,277,630.01
stage 3: opening ₦4,716,698.89 closing ₦7,548,576.55The lines add up to the closing allowance exactly. The allowance falls from ₦19,811,176.58 to ₦18,600,257.03 but coverage rises from 9.54% to 13.69%: this answers Gbolahan’s question. Transfers add ₦2.72m, mostly stage 1 to stage 2, while the balance change and the loans repaid in full take off ₦2.35m. The PD and LGD update of -₦1,111,676.96 is a model change and not a credit improvement: two classes explain nearly all of it. The PL stage 1 PD fell from 4.62% to 3.08%, and the trigger class moved from a fallback to the stage 2 PD (98.91%, used while fewer than 5 loans had been observed) to an observed 60.00% on 10 loans. The month’s impairment expense is negative, a release of ₦744,404.79, because the book shrank.
6. Post it in a ledger copy. ledger.py writes ledger.sqlite in this folder (not the lab’s data) and checks it against the pack.
cat > ledger.py <<'EOF'
"""Post the month into a ledger copy and check it agrees with the pack. SQLite, integer kobo."""
import os, sqlite3
from review import *
A, B = d("2026-08-31"), d("2026-09-30")
data = load()
R = build(data, A, B)
s0, s1, mv, F = R["s0"], R["s1"], R["mv"], R["flows"]
if os.path.exists("ledger.sqlite"):
os.remove("ledger.sqlite")
db = sqlite3.connect("ledger.sqlite")
db.execute("CREATE TABLE journal (id INTEGER PRIMARY KEY, day TEXT, account TEXT, debit INTEGER NOT NULL, credit INTEGER NOT NULL, memo TEXT)")
n = 0
def post(day, memo, *lines):
"""lines are (account, debit, credit); a journal must balance."""
global n
assert sum(x[1] for x in lines) == sum(x[2] for x in lines), memo
n += 1
for acct, dr, cr in lines:
if dr or cr:
db.execute("INSERT INTO journal (day, account, debit, credit, memo) VALUES (?,?,?,?,?)", (str(day), acct, dr, cr, f"{n}: {memo}"))
g0 = gross(s0)
post(A, "opening balances", ("loans_receivable", g0, 0), ("loss_allowance", 0, mv["opening"]), ("opening_equity", 0, g0 - mv["opening"]))
if F["disbursed"]:
post(B, "disbursements", ("loans_receivable", F["disbursed"], 0), ("cash", 0, F["disbursed"]))
post(B, "principal repaid", ("cash", F["repaid"], 0), ("loans_receivable", 0, F["repaid"]))
if F["recovered"]:
post(B, "recoveries on written-off loans", ("cash", F["recovered"], 0), ("impairment_expense", 0, F["recovered"]))
used = -mv["lines"]["written off"]
charge = mv["closing"] - mv["opening"] + used
post(B, "ECL charge for the month (negative = release)",
("impairment_expense", max(charge, 0), max(-charge, 0)), ("loss_allowance", max(-charge, 0), max(charge, 0)))
post(B, "write-offs", ("loss_allowance", used, 0), ("impairment_expense", F["written_off"] - used, 0), ("loans_receivable", 0, F["written_off"]))
db.commit()
bal = dict(db.execute("SELECT account, SUM(debit) - SUM(credit) FROM journal GROUP BY account"))
print(f"{'account':<22}{'debit - credit':>20}")
for a, v in sorted(bal.items()):
print(f"{a:<22}{naira(v):>20}")
print(f"{'trial balance sums to':<22}{naira(sum(bal.values())):>20}")
checks = [
("loans_receivable = gross principal in the pack", bal["loans_receivable"] == gross(s1)),
("loss_allowance (credit) = closing ECL in the pack", -bal["loss_allowance"] == mv["closing"]),
("expense = ECL charge + the part of write-offs not provided for", bal["impairment_expense"] == charge + F["written_off"] - used),
("every journal balances", db.execute("SELECT SUM(debit) - SUM(credit) FROM journal").fetchone()[0] == 0),
]
for text, ok in checks:
print(("PASS " if ok else "FAIL ") + text)
EOF
python3 ledger.pyaccount debit - credit
cash ₦71,264,819.51
impairment_expense -₦744,404.79
loans_receivable ₦135,908,494.49
loss_allowance -₦18,600,257.03
opening_equity -₦187,828,652.18
trial balance sums to ₦0.00
PASS loans_receivable = gross principal in the pack
PASS loss_allowance (credit) = closing ECL in the pack
PASS expense = ECL charge + the part of write-offs not provided for
PASS every journal balancesThe trial balance sums to zero, the receivable equals gross principal, and the allowance equals the closing ECL. Expense is negative because the allowance was released, which is the same fact as the movement table. The ₦606.47 of the write-offs that was not provided for is the LGD showing through.
7. Run the acceptance checks. accept.py runs checks 1 to 11. The last two poison the data: every payment dated after the as-of date is removed and every instalment is shown as paid in full the next day. A figure that uses only what was known on its date does not move.
cat > accept.py <<'EOF'
"""Acceptance checks for the September 2026 pack. Every line must print PASS."""
import collections, datetime as dt, json, subprocess, sys
from review import *
A, B = d("2026-08-31"), d("2026-09-30")
results = []
def check(text, ok, figure=""):
results.append(ok)
print(("PASS " if ok else "FAIL ") + text + (f" [{figure}]" if figure else ""))
data = load()
R = build(data, A, B)
s1, M, mv, F = R["s1"], R["metrics"], R["mv"], R["flows"]
# 1. the snapshot code reproduces the loans table at the cut-off
r = subprocess.run([sys.executable, "snapcheck.py"], capture_output=True, text=True).stdout.splitlines()[0]
check("snapshot at the cut-off matches loans.csv for every loan", "0 differ" in r, r.split(": ")[1])
# 2. gross principal and allowance reconcile for September, to the kobo
g0 = gross(R["s0"])
check("gross principal: opening + disbursed - repaid - written off = closing", g0 + F["disbursed"] - F["repaid"] - F["written_off"] == M["gross"], naira(M["gross"]))
check("allowance: opening + movement lines = closing", mv["ties"], naira(mv["closing"]))
# 3. the same two identities hold in every month, including months with new lending
bad = []
disb_months = 0
for i in range(len(MONTH_ENDS) - 1):
a, b = d(MONTH_ENDS[i]), d(MONTH_ENDS[i + 1])
Q = build(data, a, b)
f, g = Q["flows"], gross(Q["s0"])
disb_months += f["disbursed_n"] > 0
if g + f["disbursed"] - f["repaid"] - f["written_off"] != Q["metrics"]["gross"] or not Q["mv"]["ties"]:
bad.append(MONTH_ENDS[i + 1])
check("both identities hold for every month-end pair, January to September", not bad, f"{len(MONTH_ENDS) - 1} months, {disb_months} with new lending, failures {bad or 'none'}")
# 4. staging and coverage make sense
st = R["stages"]
cov = {k: st[k][2] / st[k][1] for k in "123"}
check("coverage rises with the stage", cov["1"] < cov["2"] < cov["3"], " < ".join(f"{100 * cov[k]:.2f}%" for k in "123"))
check("stage 3 loans are exactly the 90+ days past due loans (NPL ratio)", st["3"][1] == M["par90"], f"{st['3'][0]} loans, {M['par90_pct']}%")
check("no loan carries more ECL than its balance", all(x["ecl"] <= x["out"] for x in s1.values()))
check("stage totals add to the pack totals", sum(st[k][1] for k in st) == M["gross"] and sum(st[k][2] for k in st) == mv["closing"])
# 5. the ledger copy agrees
out = subprocess.run([sys.executable, "ledger.py"], capture_output=True, text=True).stdout
check("ledger copy: trial balance zero, receivable and allowance agree with the pack", out.count("PASS") == 4 and "FAIL" not in out)
# 6. no hindsight. Poison everything after a date: real payments are removed and every instalment is
# "paid in full" the next day. A figure dated D that moves when the poison changes used the future.
def poison(data, day):
reps = collections.defaultdict(list)
for lid, rows in data["reps"].items():
reps[lid] = [x for x in rows if x[0] <= day]
for lid, rows in data["sched"].items():
for n, due, tot in rows:
reps[lid].append((day + dt.timedelta(days=1), n, tot, tot, 0, 0))
return dict(data, reps=reps)
def figures(snap, p):
return (gross(snap), sum(x["ecl"] for x in snap.values()), json.dumps(p, sort_keys=True))
for label, day in (("opening", A), ("closing", B)):
clean = figures(*measure(data, day))
dirty = figures(*measure(poison(data, day), day))
check(f"{label} figures (gross, ECL, every PD and the LGD) ignore anything dated after {day}", clean == dirty,
f"{naira(clean[0])}, ECL {naira(clean[1])}")
print()
print("ACCEPTED" if all(results) else "NOT ACCEPTED", f"({sum(results)} of {len(results)} checks)")
print(f"figures: gross {naira(M['gross'])}, {M['loans']} loans; PAR30 {M['par30_pct']}%; NPL {M['par90_pct']}%; "
f"ECL {naira(mv['closing'])} ({100 * mv['closing'] / M['gross']:.2f}% of gross); opening ECL {naira(mv['opening'])}")
EOF
python3 accept.pyPASS snapshot at the cut-off matches loans.csv for every loan [3645 loans rebuilt, 0 differ from loans.csv (days past due, balance, status)]
PASS gross principal: opening + disbursed - repaid - written off = closing [₦135,908,494.49]
PASS allowance: opening + movement lines = closing [₦18,600,257.03]
PASS both identities hold for every month-end pair, January to September [8 months, 5 with new lending, failures none]
PASS coverage rises with the stage [1.50% < 94.20% < 99.87%]
PASS stage 3 loans are exactly the 90+ days past due loans (NPL ratio) [220 loans, 5.56%]
PASS no loan carries more ECL than its balance
PASS stage totals add to the pack totals
PASS ledger copy: trial balance zero, receivable and allowance agree with the pack
PASS opening figures (gross, ECL, every PD and the LGD) ignore anything dated after 2026-08-31 [₦207,639,828.76, ECL ₦19,811,176.58]
PASS closing figures (gross, ECL, every PD and the LGD) ignore anything dated after 2026-09-30 [₦135,908,494.49, ECL ₦18,600,257.03]
ACCEPTED (11 of 11 checks)
figures: gross ₦135,908,494.49, 905 loans; PAR30 11.52%; NPL 5.56%; ECL ₦18,600,257.03 (13.69% of gross); opening ECL ₦19,811,176.58All eleven pass. Check 4 ran the same code on eight month-end pairs, five of them with new lending, so the reconciliation does not depend on September being a run-off month.
8. Write the commentary, and check it. Save the reference commentary, which you should rewrite in your own words, and check_commentary.py, which looks up every figure in the pack.
cat > commentary.md <<'EOF'
# Owoleaf lending: month-end review, September 2026
**Book.** Lending has been in run-off since the last disbursement in June, and nothing was disbursed in September. Gross principal fell from ₦207.6m to ₦135.9m: ₦71.3m was repaid and 15 loans (₦0.47m) were written off. 905 loans are open.
**Credit quality.** PAR30 rose from 6.74% to 11.52% and the NPL ratio from 2.28% to 5.56%. Two things drive this. The 90+ balance grew from ₦4.73m to ₦7.56m, and the denominator shrank by about a third because good loans repaid. Ratios rise in a run-off even when no new loan goes bad, so read them with the roll rates: 42.8% of the loans 31 to 89 days past due on 31 August were 90+ at month-end, and 74.2% of current loans stayed current.
**Provision.** The allowance fell from ₦19.81m to ₦18.60m, but coverage rose from 9.54% to 13.69%. Transfers added ₦2.72m (stage 1 to stage 2 ₦3.06m), repayments took off ₦1.64m, loans repaid in full ₦0.71m, and write-offs used ₦0.47m. The PD and LGD update of -₦1.11m is a model change and not an improvement in credit: the cross-default trigger moved from the stage 2 fallback PD of 98.91% to an observed 60.00% on 10 loans, and the stage 1 PD for PL fell from 4.62% to 3.08%.
**Judgement.** SME is 66.4% of gross principal and its stage 1 PD sits at the 0.5% floor, resting on one bad loan in 469 observations. At 2% the allowance would be ₦20.11m, ₦1.51m higher. The downside scenario alone gives ₦19.43m.
**Watch next month.** The 142 loans 31 to 89 days past due (₦8.09m), the trigger PD as more observations arrive, and the SME PD.
EOF
cat > check_commentary.py <<'EOF'
"""Every figure in commentary.md must appear in the pack. Numbers with a naira sign, a percent sign, a decimal point,
a comma or three or more digits are checked; small whole numbers (days, counts below 100) are not."""
import re, subprocess, sys
pack = "".join(subprocess.run([sys.executable, s], capture_output=True, text=True).stdout for s in ("pack.py", "provision.py", "mv.py"))
num = r"\d[\d,]*(?:\.\d+)?"
allowed = set()
for tok in re.findall(num, pack):
t = tok.replace(",", "").rstrip(".")
allowed.add(t)
v = float(t)
allowed.update({f"{v / 1e6:.1f}", f"{v / 1e6:.2f}", f"{v:.0f}", f"{v:.1f}"}) # 135908494.49 -> 135.9, 135.91; 74.2 -> 74
allowed.update({f"{v / 1e8:.1f}", f"{v / 1e8:.2f}"}) # kobo to millions of naira
text = open(sys.argv[1] if len(sys.argv) > 1 else "commentary.md").read()
bad = []
for m in re.finditer(r"[₦-]?\s?(" + num + r")(m|%)?", text):
tok, unit = m.group(1), m.group(2)
plain = tok.replace(",", "")
if not (unit or "." in tok or "," in tok or len(plain) >= 3):
continue
if plain in ("2026", "2025"):
continue
if plain not in allowed:
bad.append(m.group(0).strip())
print(f"checked {len(re.findall(num, text))} numbers in {sys.argv[1] if len(sys.argv) > 1 else "commentary.md"}; not found in the pack: {bad or 'none'}")
sys.exit(1 if bad else 0)
EOF
python3 check_commentary.py
sed 's/₦18.60m/₦17.90m/; s/13.69%/13.9%/' commentary.md > bad.md
python3 check_commentary.py bad.mdchecked 52 numbers in commentary.md; not found in the pack: none
checked 52 numbers in bad.md; not found in the pack: ['₦17.90m', '13.9%']Every figure in the commentary is in the pack. The second run has two figures changed by hand and the checker names both. It cannot tell you whether a sentence is true: it only catches figures that are not in the pack. The sentence about the PD update being a model change is the author’s judgement and is Gbolahan’s to challenge.
Let the pack peek at the future, and watch every reconciliation pass. In lib.py, params estimates PDs from the month-ends up to the as-of date. Change that one line so it uses every month-end, which is what an analyst does by accident when the loop runs over the whole list. Run the checks, then restore the file.
sed -i.bak 's/ ends = months_before(asof)/ ends = MONTH_ENDS/' lib.py
python3 accept.py | tail -7
mv lib.py.bak lib.pyThe output ends:
PASS stage totals add to the pack totals
PASS ledger copy: trial balance zero, receivable and allowance agree with the pack
FAIL opening figures (gross, ECL, every PD and the LGD) ignore anything dated after 2026-08-31 [₦207,639,828.76, ECL ₦18,281,014.94]
PASS closing figures (gross, ECL, every PD and the LGD) ignore anything dated after 2026-09-30 [₦135,908,494.49, ECL ₦18,600,257.03]
NOT ACCEPTED (10 of 11 checks)
figures: gross ₦135,908,494.49, 905 loans; PAR30 11.52%; NPL 5.56%; ECL ₦18,600,257.03 (13.69% of gross); opening ECL ₦18,281,014.94The identities all pass, and the closing figures are unchanged because 30 September is the last month-end. Only the opening allowance moves, from ₦19,811,176.58 to ₦18,281,014.94, because the 31 August PDs now use September’s outcomes, and only check 10 notices. The mistake lowers the opening provision, so the month’s movement would look different from what it was. A reconciliation proves the arithmetic. Only a test that changes the future and watches the past proves the figures are honest. Then say which of the eleven checks would have caught a PD fitted on the full year when the pack is dated June.
Template
# Credit committee minutes: <company>, <month> review, <date>
Minuted by <committee secretary>. Signed by <chair>.
Decision asked of the chair: <what the chair is asked to sign>.
## 1. Attendance
Present (by role): <role>, <role>, ... Apologies: <role>. Quorum met: <yes or no, and why>.
## 2. Presented
- Pack: <title, as-at date, who presented>
- Headline figures: <figure, with its source line in the pack>
- Reconciliation: <opening + movement = closing, and whether it ties to the kobo>
## 3. Decisions
| # | Decision | Reason | Figure relied on | Decided by |
## 4. Dissent
<who, what they held, what would settle it, and whether the chair accepted it>
## 5. Actions
| # | Action | Owner | Due | Done when |
## 6. Not decided
<items discussed and deferred, with the date they return>
## 7. How this could be wrong
<one way, and what would show it>
## 8. Sign-off
Out of scope: <what these minutes do not cover>.
Minuted <name, date>. Approved <name, date>. WORKED EXAMPLE
At Owoleaf the committee secretary minutes the meeting and the chair, the head of credit risk, signs them. These are the minutes of the September close review, held on Tuesday 6 October 2026, from the lab’s figures.
Attendance. Head of credit risk (chair), financial controller for lending (Feranmi), portfolio risk analyst (Gbolahan), head of collections, head of lending products, committee secretary. Apologies: head of internal audit. Quorum met, on the committee’s own rule (assumed here): the chair and two members were present.
Presented. Feranmi presented the pack for the month ended 30 September 2026. Gross principal fell from ₦207.6m to ₦135.9m, with nothing disbursed. PAR30 rose from 6.74% to 11.52%. The allowance fell from ₦19,811,176.58 to ₦18,600,257.03, and coverage rose from 9.54% to 13.69%. The lines add up to the closing allowance exactly.
Decisions.
- Accept the allowance of ₦18,600,257.03. Reason: it ties to the kobo and all eleven acceptance checks passed.
- Keep the SME stage 1 PD at the 0.5% floor for September. Reason: the book offers no other estimate, and the effect is disclosed.
Dissent. Gbolahan held that the floor rests on one bad loan in 469 observations and that 2% is safer, which would give ₦20,111,936.09 (+₦1,511,679.06). The chair noted it. Revisit when a second SME month-end gives more observations.
Actions.
| # | Action | Owner | Due |
|---|---|---|---|
| 1 | Write a one-page note on the SME PD and its sensitivity | Gbolahan | Tue 13 October |
| 2 | Add the 31 August poison test to the monthly run | Feranmi | Fri 16 October |
Could be wrong. The PDs come from five starting months. A second month of SME defaults would show it.
Not decided. Whether to change the SME PD; it returns at the November meeting with the note.
Sign-off. The chair is asked to sign these minutes, which confirms that the allowance of ₦18,600,257.03 stands as reported. Interest receivable is out of scope.
Now you
You are the committee secretary at Owoleaf, and your chair signs what you write. Write the minutes and action log for the committee that met on Tuesday 8 September 2026 to review the August close, one month before the meeting above. Use the lab’s step 3 and step 5 output for 31 August: gross principal ₦207,639,828.76, PAR30 6.74%, allowance ₦19,811,176.58, coverage 9.54%, and the PD table. The room agreed to accept the pack, asked collections to look at the 236 loans 31 to 89 days past due, and noted that the cross-default trigger still used a fallback PD. The risk analyst thought that fallback too high. Use only what the committee could have known on 8 September. You choose the reasons, owners and dates. The chair reads the minutes to decide whether the August allowance stands as reported.
Self-check
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.