SENIORCHAPTER 19

Provisioning under IFRS 9

A provision is a loss booked before it happens. Three stages decide how much to book, and one choice, when a loan counts as significantly worse, moves the total more than most models do

75 MINLENDING AND CREDITUPDATED 2026-11-14
PREDICT

Two personal loans have the same terms: ₦18,153.48 of principal outstanding and two instalments left. One is current. The other missed its instalment 20 days ago. The lab computes a base-scenario expected credit loss for each. How many times larger is the late loan's?

IFRS 9 is the international accounting standard for financial instruments. Its impairment rules say how a lender measures the loss it expects on a loan and books it before the loss happens. The older approach waited for evidence of a loss. IFRS 9 asks for an expected credit loss (ECL): the probability-weighted, discounted shortfall in cash flows, estimated from reasonable and supportable information that includes forward-looking information. This chapter teaches how the staging works, computes it on the loan book, and posts it. Expected loss is its own chapter in this module, so the probability of default, loss given default and exposure at default (PD, LGD and EAD, defined in the economics of a loan) are computed here in compact form from the book, and that chapter derives them in full. Both chapters use the same LGD rule: principal recovered after default as a share of the principal owed at default.

The bank in the opening is fictional and has no book to quote, so the lab uses Owoleaf’s loan book on data1/ as a stand-in. Every price, cut-off and scenario in it is illustrative.

An allowance is a balance, and a charge is a movement

A provision has two faces. On the balance sheet sits a loss allowance: a negative asset, deducted from the loans. The loans’ gross carrying amount (here, the principal still owed) less the allowance is the net amount the lender reports. In the income statement sits the impairment charge: the change in the allowance over the period. If the allowance rises by ₦1,000,000, the lender books ₦1,000,000 of expense.

Those two facts explain what goes wrong first. A team that treats the provision as an expense each month double-counts, because the allowance already holds last month’s loss. A team that treats a write-off as a new expense counts the loss twice, because a write-off removes the loan and uses up the allowance already built against it. The ledger in step 8 posts the allowance as a balance and the charge as its movement.

Three stages

IFRS 9 sorts each loan into one of three stages and sets the measure by the stage.

Stage Test Loss allowance Interest income on
1 Credit risk has not increased significantly since the loan was first recognised 12-month ECL Gross carrying amount
2 Credit risk has increased significantly since then, but the loan is not impaired Lifetime ECL Gross carrying amount
3 The loan is credit-impaired: in default Lifetime ECL Amortised cost, which is the gross amount less the allowance

IFRS 9 recognises 12-month ECL when credit risk has not increased significantly since initial recognition and lifetime ECL when it has. Commentary and IFRS Foundation staff papers describe a rebuttable presumption that credit risk has increased significantly once contractual payments are more than 30 days past due, a floor on caution and not a ceiling: more forward-looking information, where available without undue cost or effort, must be used. The same sources describe a rebuttable presumption that default is no later than 90 days past due, and interest in stage 3 calculated on the net amount (the gross carrying amount less the allowance, paragraph 5.4.1(b)). The search did not return the standard’s own text, so the wording and paragraph numbers should be checked in the standardas of 2026-11.

Lifetime means the expected credit loss from default events over the whole remaining life of the loan. 12-month means only the defaults that can happen in the next 12 months. The jump from the second to the first is the so-called cliff: a loan moves to stage 2 and its allowance can multiply, on the day it moves. The size of the jump depends on how long the loan has left. For a loan with under 12 months left there is no jump from the horizon at all, a point the lab makes concrete in step 6.

Significant increase in credit risk

Significant increase in credit risk (SICR) is the test that moves a loan from stage 1 to stage 2. The standard asks a lender to compare the risk of default over the loan’s remaining life now with the risk it estimated at origination. It does not say how much is “significant”. Lenders use three kinds of evidence.

A backstop. The 30-day presumption above is a backstop. A loan more than 30 days past due is in stage 2 unless you can rebut it. The backstop is the latest point and it is a floor on how cautious you must be. A lender with earlier evidence must act on that evidence.

A relative test on probability of default. Compare the loan’s lifetime PD now with its PD at origination, and move it when the ratio passes a limit (two or three times are common choices, and each is a policy decision a committee signs). The lab does this. At origination, a six-instalment personal loan has a lifetime PD of 8.8% (1 minus 0.9847 to the sixth power, from a hazard of 1.53% per instalment). After a missed instalment, the lab’s own roll rates put it near 44%. That is five times, so the loan is stage 2 at 20 days past due.

Qualitative evidence. A restructuring (the chapter on restructuring and forbearance, later in this module, covers the accounting), a watch-list entry, news that a borrower’s employer has stopped paying salaries, or a fall in a bureau score. The lab’s book has none of these at the cut-off for the loans that are still open, so the lab does not use them. A real lender writes each indicator down in its policy, with its source.

The choice matters because of the numbers on the other side. Step 3 shows that the backstop alone puts 18 of the 504 open loans that are not in default in stage 2. Adding the relative test puts 40 there, and step 6 shows the difference between the two is ₦1,420,610.40 of provision.

Default is a definition

Stage 3 needs a definition of default, and the standard asks you to use the one you already use in credit-risk management. It then adds a rebuttable presumption that default is no later than 90 days past due. That matches the definition of bad in credit scoring, and the lab uses it. A credit-impaired loan is one with evidence that an event has hurt its expected cash flows: default is the clearest.

Aligning the definitions matters more than it sounds. A bank whose scorecards say bad is 90 days, whose collections hand over at 60 and whose accounts use 180 for stage 3 has three PDs that cannot be compared. Model and provision should use one definition, and a policy should say when it is allowed to differ.

From a loan to a number: the formula

A loan’s expected credit loss is the sum, over every future instalment, of five factors:

ECL = sum over instalments t of:
      (chance the loan is still performing before t)
    x (chance instalment t is missed, given it was performing)     marginal PD
    x (the share of the exposure not recovered)                    LGD
    x (what is owed when it is missed)                             EAD
    x (a discount factor back to the reporting date)

Take the first of the two loans in the Predict question, L000037. It has two instalments to come, 5 and 6. The inputs come from step 2: the instalment hazard (the chance an instalment is still unpaid 90 days after it falls due) for personal loans is 14 missed of 918 at risk, 1.53%; LGD is 99.55%; and the loan’s effective interest rate (EIR, the discount rate at which its payments are worth what the borrower was paid out, from interest, APR, fees and amortisation) is 77.2% a year. Instalment 5 is due 15 days after the cut-off. The default date for an instalment is its due date plus 90 days, so the discount runs 105 days: 1.772^(−105/365) = 0.8483.

instalment 5:  1.5251% x ₦18,153.48 x 99.55% x 0.8483 = ₦233.79
instalment 6:  1.5018% x  ₦9,276.47 x 99.55% x 0.8094 = ₦112.24
ECL                                                     ₦346.03

Check the first line: 0.0152505 × 18,153.48 = 276.85; × 0.9955 = 275.60; × 0.8483 = 233.79. The marginal PD of instalment 6 is lower than 1.5251% because the loan must survive instalment 5: 0.984749 × 0.015251 = 1.5018%. The exposure for instalment 6 is ₦9,276.47, the principal that falls due in it, because instalment 5 will have been paid if the loan is performing.

Now the late loan. It is stage 2, so the lab first asks whether it rolls to default at once, using the roll rate for its bucket (8 to 30 days past due: 57 of 132, 43.18%). If it rolls, the loss is on all ₦18,153.48 and the default date is 90 days after the missed instalment, 70 days from the cut-off. If it does not, the loan faces the instalment hazard on what is still to come. The lab’s ladder for L000082 shows 43.1818% × ₦18,153.48 × 99.55% × 0.8961 = ₦6,992.85, and ₦68.41 for the one instalment left. The 20 days of lateness multiply the provision by 20.

The ECL is an estimate, and the estimate is not smooth. Two loans a few days apart in lateness can sit a stage apart, and the stage sets the multiplier. This is why the staging rule gets so much attention.

What the stage 3 line shows

Stage 3 is the simplest case. The loan has defaulted, so the probability is 1, and the loss is LGD times the principal outstanding. In this book, LGD is close to 1. The lab measures the principal paid after each defaulted loan reached 90 days past due: nothing on salary advances, BNPL and SME loans, and ₦10,956.69 of principal against ₦2,411,684.64 of exposure on personal loans. The generator’s borrowers who stop paying do not pay again, and its agency placements recover almost nothing (stated in the lab README), so a stage 3 allowance here is 99.96% of the balance. Interest recovered after default is not counted, because the exposure is principal only. A lender with real recoveries would estimate LGD from a recovery curve and discount the recoveries. Expected loss does that work.

The 58 written-off loans (₦2,945,038.89 of principal that the book still records) are not in the stage 3 line. The book follows the convention of the ledger project: a written-off loan has left receivables and its loss is booked. In a real ledger the allowance would have been built while the loan was in stage 3 and used up at write-off. The movement of an allowance from month to month is the subject of the project at the end of this module.

Forward-looking: scenarios and weights

IFRS 9 asks for an unbiased, probability-weighted amount, estimated with forward-looking information. A lender cannot take the past default rate and stop. It builds two or more macroeconomic scenarios, estimates the ECL under each, and weights the results by the probability it gives each scenario. The lab uses two, labelled illustrative: a base scenario with the hazards as observed, and a downturn in which every hazard and roll rate doubles (capped at 1), weighted 70% and 30%.

Three things go wrong with scenarios, and each shows in the lab.

First, a link between the economy and default has to be estimated, usually by regressing default rates on macro variables such as inflation, exchange rates or unemployment over several years. The lab has ten months of data and one economy, so it cannot, and the multiplier of 2 is an assumption. A lender that has no history of its own says so and uses a stated external view.

Second, the weighted figure is not the figure for the average scenario, because loss is not linear in the inputs. Step 5 shows it: the downturn adds 96% to stage 1 (₦1,509,055.12 to ₦2,962,777.43), 22% to stage 2 and nothing to stage 3, where loss is already certain. A scenario multiplier bites where the book is still healthy, and the same doubling lifts a stage 1 balance far more than a stage 3 one.

Third, the weights are a judgement that moves the profit. Step 6 prints the range: ₦18,013,763.30 at 100% base, ₦18,842,468.38 at 70/30 and ₦20,776,113.59 at 100% downturn. A management that is under pressure to show a profit has a way to move that number, so the weights and the multipliers need an owner other than the person whose results they change, a written basis and a record of each change. A manual adjustment on top of the model, a management overlay, is allowed when the model is known to miss something. It has the same need for evidence.

Discounting, and why the horizon matters little here

Expected loss is discounted from the date of the loss back to the reporting date at the loan’s EIR. That sounds like a refinement and it is not small for a high-rate lender: the lab’s personal loans have an EIR above 70% a year, and with no discounting the total is ₦860,825.57 higher (step 6).

Look at the horizon. Stage 1 counts defaults in the 12 months after the cut-off. In the lab’s book, every loan has under 12 months to run, and the furthest default date of any stage 1 or 2 loan is 328 days away (the last instalment’s due date plus 90 days). So a stage 1 loan measured over its whole life gets exactly the same ECL, and the cliff is absent. That is a fact about short loans, not a flaw in the model. Staging still matters, because stage 2 changes the PD from about 1.5% an instalment to 43%, but the horizon does nothing. Step 7 builds a hypothetical product with 24 or 36 instalments and shows the cliff reappear: lifetime ECL 1.45 times the 12-month figure for 24 instalments and 1.75 times for 36.

CBN prudential rules and IFRS 9

A lender regulated by the Central Bank of Nigeria (CBN) may have to report under IFRS and also meet the CBN’s prudential rules, which set their own provisioning table by days overdue. The two give different numbers and the rules say what to do with the difference. What each says depends on the kind of institution, so check which guideline applies to you.

For banks, search results describing the CBN’s circular of 18 October 2018 on the transitional treatment of IFRS 9 report that Section 12.4 of the Prudential Guidelines requires a non-distributable regulatory risk reserve: where prudential provisions exceed IFRS provisions, the difference is transferred to that reserve, and the circular sets a four-year transition for the effect of adopting IFRS 9 in January 2018. The circular itself was not read: this rests on search summariesas of 2026-11.

For microfinance banks the guidance is separate.

The CBN’s Prudential Guidelines for Microfinance Banks (August 2019) exist at this address and, per search extracts, contain a loan-classification and provisioning section. The search did not show the classification bands or percentages, and third-party commentary describes an August 2019 exposure draft, so it is not clear whether this file is the final text. The 20%, 50% and 100% bands used in step 9 are the chapter’s illustrative assumptions, not confirmed rules, and bands differ by institution type, so do not carry them acrossas of 2026-11.

A regulation tracker’s summary of a CBN letter dated 8 October 2021 says other financial institutions, microfinance banks among them, must prepare annual financial statements under IFRS from the 2021 financial year, and a separate CBN guidance note on IFRS 9 for these institutions is dated March 2019 (sources give 5 and 25 March). Neither document was read: this rests on the tracker’s summariesas of 2026-11.

Treat all three paragraphs as leads to the documents, not as the documents. The comparison that matters is mechanical, and step 9 computes it with illustrative bands, not confirmed rules. In the lab’s book, the prudential table gives ₦5,815,973.66 and IFRS 9 gives ₦18,842,468.38, because the generator’s defaulters never repay. The table does not see the 493 loans under 61 days overdue at all, and those carry ₦5,877,032.31 of IFRS 9 provision. The direction here would be no transfer to a reserve. In a book with real recoveries the two can be the other way, and the reserve exists for that case.

Posting the provision

A provision is booked with one rule from the project ledger: every entry balances. At the cut-off, debit impairment expense and credit one loss allowance account per stage. The loans receivable account does not change, because the allowance sits beside it. When the scenario weights move from 70/30 to 50/50, the bank does not post the whole provision again. It posts the movement: ₦552,470.00 debit to impairment expense, credit to the stage 1 and stage 2 allowances. Step 8 builds the ledger and proves four things: every journal balances, each stage’s allowance equals the sum of its loans’ ECL, net loans equal gross less allowance, and the expense equals the allowance.

The proof does not show the ECL is right. It shows the books agree with the model. Whether the model is right is a model risk question: someone other than its builder checks the inputs, back-tests the PD against what happened, and reviews the staging.

Where it goes wrong

  • Staging by days past due alone. The backstop is a floor. A book can look healthy on that rule while its early arrears are already losing.
  • Inputs from immature loans. A hazard measured on loans too young to have failed understates the PD. The lab counts only instalments whose 90th day has passed by the cut-off.
  • Small samples. The 1 to 7 day roll rate rests on 106 loan-snapshots. Quote the count with the rate.
  • Rounding. The lab rounds each loan’s ECL to a whole kobo before adding, so the weighted column differs by a few kobo from weighting the totals. A ledger needs one rule for this and a record of it.
  • Counting a regulator’s table as ECL. A table by days overdue is a floor for capital and a different measurement.
  • Weights chosen to hit a profit. See the section above: the fix is governance, not arithmetic.
  • Double counting at write-off. Use the allowance first, and book only the excess.

Back at the bank

Agbani and Ajoke agree on how to present the year-end. The method: stage every open loan, with the staging rules written down and their thresholds signed. The inputs: hazards, roll rates and recoveries computed from the bank’s own history with the counts shown. The scenarios: two, with stated weights and an owner outside finance. The reconciliation: the model’s allowance against the ledger, and the IFRS figure against the CBN table, with the difference explained. They rerun the lab’s steps on the bank’s own data. The lab’s figures are not the bank’s, and they quote none of them to the auditors.

LAB Stage the book, compute ECL under two scenarios and post the provision on data1 ~60 MIN
YOU NEEDPython 3.9 or later (standard library only)labs/finance with the scale 1 book built into data1 (step 0)about 720 MB of disk for data1 and about 40 seconds to build itabout 5 minutes of reading per step

You build one library file, ifrs.py, a step at a time, then a small ledger, post.py. Work in labs/finance. The scripts open the book read-only. Do not open data1/answers/loans_truth.csv: a lender has no such file. Money is integer kobo throughout; probabilities are floats, and every loan’s loss is rounded to a whole kobo before anything is added. Every input is illustrative.

0. Build the scale 1 book once. If data1/finance.sqlite is missing, build it (about 40 seconds, about 720 MB) and check it.

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
loan book: 3645 loans, 9,771,721,819 kobo of principal outstanding; checks 7-11 run
...
OK: all invariants hold

The first and last lines of check.py’s output; it takes about 30 seconds. The cut-off is 2026-10-28, and 3,645 loans is the scale 1 count.

1. Load the book and rebuild days past due. Save this as ifrs.py. The constants at the top are the chapter’s choices and are all illustrative. The file rebuilds each loan’s days past due from schedule and repayments and checks it against loans.days_past_due.

"""ifrs.py: stage the loan book at the cut-off and compute expected credit losses (data1, scale 1).

Standard library only. Money is integer kobo; probabilities are floats, and every loan's
loss is rounded to a whole kobo before anything is added. Every input is ILLUSTRATIVE.
"""
import collections
import datetime as dt
import functools
import sqlite3

DB = "data1/finance.sqlite"
CUT_OFF = dt.date(2026, 10, 28)           # the loan book is observed to here
DAY90 = dt.timedelta(days=90)             # 90 days past due: the default definition
HORIZON = CUT_OFF + dt.timedelta(days=365)  # a 12-month ECL counts defaults that happen by here
SICR_MULTIPLE = 2.0                       # stage 2 when lifetime PD now is 2x the PD at origination (ILLUSTRATIVE)
BACKSTOP_DPD = 30                         # IFRS 9 presumes a significant increase beyond 30 days past due
WEIGHTS = {"base": 0.70, "downturn": 0.30}      # scenario weights (ILLUSTRATIVE)
PD_MULTIPLIER = {"base": 1.0, "downturn": 2.0}  # scenario effect on hazards (ILLUSTRATIVE)


def day(text):
    return dt.date.fromisoformat(text[:10])


@functools.lru_cache(maxsize=1)
def book(db_path=DB):
    """loans {id: dict}, instalments {id: [(n, due, principal, total)]}, cleared {(id, n): date or None}."""
    db = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
    loans = {r[0]: dict(id=r[0], product=r[1], principal=r[2], fee=r[3], disbursed=day(r[4]), n=r[5],
                        status=r[6], dpd=r[7], outstanding=r[8])
             for r in db.execute("""SELECT id, product, principal_kobo, fee_kobo, disbursed_at, instalments, status,
                                           days_past_due, outstanding_principal_kobo FROM loans ORDER BY id""")}
    sched = collections.defaultdict(list)
    for loan_id, n, due, p, t in db.execute(
            "SELECT loan_id, instalment, due_date, principal_kobo, total_kobo FROM schedule ORDER BY loan_id, instalment"):
        sched[loan_id].append((n, day(due), p, t))
    paid = collections.defaultdict(int)
    cleared = {}
    totals = {(l, n): t for l, rows in sched.items() for n, _, _, t in rows}
    for loan_id, n, when, amount, late_fee in db.execute(
            "SELECT loan_id, instalment, paid_at, amount_kobo, late_fee_kobo FROM repayments ORDER BY paid_at, id"):
        paid[(loan_id, n)] += amount - late_fee               # a late fee is not part of the instalment
        if (loan_id, n) not in cleared and paid[(loan_id, n)] >= totals[(loan_id, n)]:
            cleared[(loan_id, n)] = day(when)
    return loans, sched, cleared


def oldest_unpaid(loan_id, on):
    """(instalment, due date) of the oldest instalment due before `on` and not cleared by `on`, or None."""
    _, sched, cleared = book()
    for n, due, _, _ in sched[loan_id]:
        if due >= on:
            return None
        c = cleared.get((loan_id, n))
        if c is None or c > on:
            return n, due
    return None


def dpd_on(loan_id, on):
    o = oldest_unpaid(loan_id, on)
    return (on - o[1]).days if o else 0


def missed(loan_id, n, due):
    """Was instalment n still unpaid 90 days after its due date? (Call only when due + 90 <= the cut-off.)"""
    c = book()[2].get((loan_id, n))
    return c is None or c > due + DAY90


def show_rebuild():
    loans, _, _ = book()
    wrong = [l for l in loans if dpd_on(l, CUT_OFF) != loans[l]["dpd"]]
    print(f"{len(loans)} loans; days past due rebuilt from schedule and repayments differs from loans.days_past_due on {len(wrong)}")
    by = collections.defaultdict(lambda: [0, 0])
    for l in loans.values():
        by[l["status"]][0] += 1
        by[l["status"]][1] += l["outstanding"]
    print(f"{'status':<12}{'loans':>6}{'principal outstanding':>24}")
    for s in ("closed", "current", "arrears", "default", "written_off"):
        print(f"{s:<12}{by[s][0]:>6}{naira(by[s][1]):>24}")


def naira(kobo):
    return f"₦{kobo // 100:,}.{kobo % 100:02d}" if kobo >= 0 else "-" + naira(-kobo)
python3 -c "import ifrs; ifrs.show_rebuild()"
3645 loans; days past due rebuilt from schedule and repayments differs from loans.days_past_due on 0
status       loans   principal outstanding
closed        2773                   ₦0.00
current        462          ₦75,217,147.92
arrears         42           ₦8,900,715.56
default        310          ₦10,654,315.82
written_off     58           ₦2,945,038.89

The rebuild agrees with the book on all 3,645 loans, so the later steps can ask what a loan’s days past due were on any date, not only at the cut-off. The open book is 462 current loans, 42 in arrears and 310 in default, with ₦94,772,179.30 of principal outstanding after the 58 written-off loans (₦2,945,038.89) are set aside.

2. Compute the inputs. Add this to the end of ifrs.py. It is a compact version of what chapter expected loss derives in full: an instalment hazard by product, a roll rate by days-past-due bucket from month-end snapshots, and a loss given default from the principal paid after 90 days.

# ---- the inputs: hazard, roll rate, loss given default -------------------------------------------
# The expected-loss chapter derives PD, LGD and EAD in full. These are compact versions so this chapter stands alone.
SNAPSHOTS = [dt.date(2026, m, 1) - dt.timedelta(days=1) for m in range(2, 10)]   # month-ends, Jan to Aug


def bucket(dpd):
    return "1-7" if dpd <= 7 else "8-30" if dpd <= 30 else "31-89"


def hazards():
    """{product: (instalments at risk, instalments missed, hazard)}. An instalment is 'missed' when it is still
    unpaid 90 days after its due date; the loan then leaves the risk set. Only instalments whose 90th day has
    passed by the cut-off count, so nothing is guessed."""
    loans, sched, _ = book()
    risk, miss = collections.Counter(), collections.Counter()
    for l, row in loans.items():
        for n, due, _, _ in sched[l]:
            if due + DAY90 > CUT_OFF:
                break
            risk[row["product"]] += 1
            if missed(l, n, due):
                miss[row["product"]] += 1
                break
    return {p: (risk[p], miss[p], miss[p] / risk[p]) for p in risk}


def roll_rates(products=("PL", "SME", "BNPL")):
    """{bucket: (loan-snapshots, rolled, rate)}: of the loans past due in a bucket on a month-end, the share
    whose oldest unpaid instalment was still unpaid 90 days after it fell due."""
    loans, _, _ = book()
    seen, rolled = collections.Counter(), collections.Counter()
    for s in SNAPSHOTS:
        for l, row in loans.items():
            if row["product"] not in products or row["disbursed"] >= s:
                continue
            o = oldest_unpaid(l, s)
            if not o or o[1] + DAY90 > CUT_OFF:
                continue
            b = bucket((s - o[1]).days)
            seen[b] += 1
            rolled[b] += missed(l, o[0], o[1])
    return {b: (seen[b], rolled[b], rolled[b] / seen[b]) for b in ("1-7", "8-30", "31-89")}


def lgds():
    """{product: (defaulted loans, exposure at default, recovered after, LGD)}. Exposure is the principal
    outstanding on the day the loan reached 90 days past due; recovered is the principal paid after that day.
    Interest and fees recovered are left out, because the exposure is principal only (the expected-loss chapter's rule)."""
    loans, sched, _ = book()
    db = sqlite3.connect(f"file:{DB}?mode=ro", uri=True)
    n_, ead, rec = collections.Counter(), collections.Counter(), collections.Counter()
    for l, row in loans.items():
        for n, due, _, _ in sched[l]:
            if due + DAY90 > CUT_OFF:
                break
            if missed(l, n, due):
                when = (due + DAY90).isoformat()
                principal_paid, after = db.execute(
                    """SELECT COALESCE(SUM(CASE WHEN paid_at <= ? THEN principal_kobo END), 0),
                              COALESCE(SUM(CASE WHEN paid_at > ? THEN principal_kobo END), 0)
                       FROM repayments WHERE loan_id = ?""", (when, when, l)).fetchone()
                n_[row["product"]] += 1
                ead[row["product"]] += row["principal"] - principal_paid
                rec[row["product"]] += after
                break
    return {p: (n_[p], ead[p], rec[p], 1 - rec[p] / ead[p]) for p in n_}


def show_inputs():
    print("1. hazard: instalments missed (unpaid 90 days after due) per instalment at risk")
    print(f"   {'product':<8}{'at risk':>9}{'missed':>8}{'hazard':>9}")
    for p, (r, m, h) in sorted(hazards().items()):
        print(f"   {p:<8}{r:>9}{m:>8}{h:>9.2%}")
    print("\n2. roll rate: share of past-due loan-snapshots (PL, SME, BNPL, month-ends Jan to Aug) that reached 90 days")
    print(f"   {'days past due':<14}{'snapshots':>10}{'rolled':>8}{'rate':>8}")
    for b, (s, r, rate) in roll_rates().items():
        print(f"   {b:<14}{s:>10}{r:>8}{rate:>8.1%}")
    print("\n3. loss given default: principal paid after the loan reached 90 days past due")
    print(f"   {'product':<8}{'loans':>6}{'exposure':>18}{'recovered':>14}{'LGD':>8}")
    for p, (n, e, r, lgd) in sorted(lgds().items()):
        print(f"   {p:<8}{n:>6}{naira(e):>18}{naira(r):>14}{lgd:>8.2%}")
python3 -c "import ifrs; ifrs.show_inputs()"
1. hazard: instalments missed (unpaid 90 days after due) per instalment at risk
   product   at risk  missed   hazard
   BNPL         2614      66    2.52%
   PL            918      14    1.53%
   SAL          1959     281   14.34%
   SME           916       7    0.76%

2. roll rate: share of past-due loan-snapshots (PL, SME, BNPL, month-ends Jan to Aug) that reached 90 days
   days past due  snapshots  rolled    rate
   1-7                  106      27   25.5%
   8-30                 132      57   43.2%
   31-89                201     193   96.0%

3. loss given default: principal paid after the loan reached 90 days past due
   product  loans          exposure     recovered     LGD
   BNPL        66     ₦1,775,883.00         ₦0.00 100.00%
   PL          14     ₦2,411,684.64    ₦10,956.69  99.55%
   SAL        281     ₦6,848,659.00         ₦0.00 100.00%
   SME          7     ₦2,574,084.76         ₦0.00 100.00%

Check the personal-loan hazard by hand: 14 ÷ 918 = 1.53%. The salary advance’s 14.34% is why stage 1 and 2 hold none of it: every salary advance in the book is closed or in default by the cut-off. Roll rates climb with lateness: 25.5% at 1 to 7 days, 43.2% at 8 to 30, 96.0% beyond 30. LGD is 100% on three products because nothing was paid after default, and 99.55% on personal loans: 1 − 10,956.69 ÷ 2,411,684.64 = 0.9955. Only principal counts as recovered, as in expected loss: two personal loans paid ₦37,364.00 in cash after default, and ₦26,407.31 of it was interest, which is not in the exposure.

3. Stage the book. Add the discount rate and the staging rule.

# ---- discounting: the effective interest rate ------------------------------------------------------
def eir(loan_id):
    """Annual effective interest rate: the rate at which the instalments, on their due dates, are worth
    exactly what the borrower was paid out (principal less the fee). Found by bisection."""
    loans, sched, _ = book()
    row = loans[loan_id]
    net = row["principal"] - row["fee"]
    flows = [((due - row["disbursed"]).days / 365, t) for _, due, _, t in sched[loan_id]]
    lo, hi = 0.0, 200.0
    for _ in range(200):
        mid = (lo + hi) / 2
        if sum(t / (1 + mid) ** y for y, t in flows) > net:
            lo = mid
        else:
            hi = mid
    return (lo + hi) / 2


# ---- staging ---------------------------------------------------------------------------------------
def survive(h, k):
    return (1 - h) ** k


def stage_of(loan_id, haz, roll, backstop_only=False):
    """(stage, reason). Stage 3: 90+ days past due. Stage 2: more than 30 days past due (the IFRS 9 backstop),
    or lifetime PD now at least SICR_MULTIPLE times the PD at origination. Stage 1: the rest."""
    loans, sched, _ = book()
    row = loans[loan_id]
    if row["status"] in ("closed", "written_off"):
        return None, row["status"]
    if row["dpd"] >= 90:
        return 3, "90+ days past due"
    if row["dpd"] > BACKSTOP_DPD:
        return 2, "backstop: more than 30 days past due"
    if backstop_only or row["dpd"] == 0:
        return 1, "performing"
    h = haz[row["product"]][2]
    ahead = sum(1 for n, due, _, _ in sched[loan_id] if due > CUT_OFF)
    pd_now = roll[bucket(row["dpd"])][2] + (1 - roll[bucket(row["dpd"])][2]) * (1 - survive(h, ahead))
    pd_then = 1 - survive(h, row["n"])
    if pd_now >= SICR_MULTIPLE * pd_then:
        return 2, f"PD now {pd_now:.1%} is {pd_now / pd_then:.1f}x PD at origination {pd_then:.1%}"
    return 1, f"PD now {pd_now:.1%} is {pd_now / pd_then:.1f}x PD at origination {pd_then:.1%}"


def stage_book(backstop_only=False):
    haz, roll = hazards(), roll_rates()
    return {l: stage_of(l, haz, roll, backstop_only) for l in book()[0]}


def show_staging():
    loans, _, _ = book()
    print(f"{'rule':<26}{'stage':>6}{'loans':>7}{'gross carrying amount':>24}")
    for label, flag in (("backstop only", True), ("backstop + relative test", False)):
        st = stage_book(flag)
        for s in (1, 2, 3):
            ids = [l for l, (stage, _) in st.items() if stage == s]
            print(f"{label:<26}{s:>6}{len(ids):>7}{naira(sum(loans[l]['outstanding'] for l in ids)):>24}")
    st = stage_book(False)
    early = [(l, why) for l, (stage, why) in sorted(st.items()) if stage == 2 and loans[l]["dpd"] <= 30]
    print(f"\nstage 2 only because of the relative test (30 days past due or less): {len(early)} loans, the first five:")
    for l, why in early[:5]:
        print(f"  {l} {loans[l]['product']:<5}{loans[l]['dpd']:>3} days  {why}")
python3 -c "import ifrs; ifrs.show_staging()"
rule                       stage  loans   gross carrying amount
backstop only                  1    486          ₦78,988,039.95
backstop only                  2     18           ₦5,129,823.53
backstop only                  3    310          ₦10,654,315.82
backstop + relative test       1    464          ₦75,370,828.17
backstop + relative test       2     40           ₦8,747,035.31
backstop + relative test       3    310          ₦10,654,315.82

stage 2 only because of the relative test (30 days past due or less): 22 loans, the first five:
  L000007 PL    28 days  PD now 49.8% is 3.0x PD at origination 16.8%
  L000082 PL    20 days  PD now 44.0% is 5.0x PD at origination 8.8%
  L000313 SME    2 days  PD now 26.0% is 5.8x PD at origination 4.5%
  L000323 SME    8 days  PD now 44.0% is 9.8x PD at origination 4.5%
  L000368 SME    4 days  PD now 26.0% is 5.8x PD at origination 4.5%

The backstop alone puts 18 loans in stage 2. The relative test adds 22, all 30 days past due or less. Two loans, L000662 and L001027 (twelve-instalment personal loans, 3 and 1 days late), stay in stage 1: their PD now is 1.8 times the PD at origination, under the multiple of 2. In the printed list, L000082 is a six-instalment personal loan with a PD at origination of 8.8% (1 − 0.9847^6) and a PD now of 44.0%, 5.0 times.

4. Compute one loan’s ECL. Add the ECL ladder. ecl_terms returns each term of the formula, so you can check the arithmetic.

# ---- expected credit loss ---------------------------------------------------------------------------
def ecl_terms(loan_id, stage, haz, roll, lgd, mult=1.0, lifetime=False, rate=None):
    """The rows behind one loan's ECL, as (label, probability, exposure kobo, LGD, discount factor, loss kobo float).
    Stage 3: the loan has defaulted, so probability 1. Stage 1 counts only defaults that happen within 12 months
    of the cut-off; stage 2 (and lifetime=True) counts every default over the life of the loan. In stage 2 the
    loan first rolls to default with the observed roll rate; if it does not, it faces the hazard on each
    instalment still to fall due."""
    loans, sched, _ = book()
    row = loans[loan_id]
    g = rate if rate is not None else eir(loan_id)
    df = lambda when: (1 + g) ** (-max(0, (when - CUT_OFF).days) / 365)
    p = row["product"]
    rows = []
    if stage == 3:
        return [("in default", 1.0, row["outstanding"], lgd[p], 1.0, row["outstanding"] * lgd[p])]
    h = min(1.0, mult * haz[p][2])
    alive = 1.0
    if stage == 2:
        o = oldest_unpaid(loan_id, CUT_OFF)
        q = min(1.0, mult * roll[bucket(row["dpd"])][2])
        when = o[1] + DAY90
        rows.append((f"rolls from {row['dpd']} days", q, row["outstanding"], lgd[p], df(when),
                     q * row["outstanding"] * lgd[p] * df(when)))
        alive = 1 - q
    future = [(n, due, pr) for n, due, pr, _ in sched[loan_id] if due > CUT_OFF]
    left = sum(pr for _, _, pr in future)
    for n, due, pr in future:
        when = due + DAY90
        if lifetime or stage == 2 or when <= HORIZON:
            marginal = alive * h
            rows.append((f"instalment {n} missed", marginal, left, lgd[p], df(when), marginal * left * lgd[p] * df(when)))
        alive *= 1 - h
        left -= pr
    return rows


def show_one(loan_id):
    haz, roll = hazards(), roll_rates()
    lgd = {p: v[3] for p, v in lgds().items()}
    st = stage_book()
    stage = st[loan_id][0]
    row = book()[0][loan_id]
    print(f"{loan_id} {row['product']} stage {stage}, {row['dpd']} days past due, outstanding {naira(row['outstanding'])}, "
          f"EIR {eir(loan_id):.1%} a year, hazard {haz[row['product']][2]:.2%}, LGD {lgd[row['product']]:.2%}")
    print(f"   {'event':<26}{'probability':>12}{'exposure':>16}{'discount':>10}{'loss':>14}")
    total = 0
    for label, pr, ead, _, d, loss in ecl_terms(loan_id, stage, haz, roll, lgd):
        print(f"   {label:<26}{pr:>12.4%}{naira(ead):>16}{d:>10.4f}{naira(round(loss)):>14}")
        total += loss
    print(f"   {'ECL (base scenario)':<26}{'':>12}{'':>16}{'':>10}{naira(round(total)):>14}")
python3 -c "
import ifrs
for l in ('L000037', 'L000082', 'L000011'):
    ifrs.show_one(l)
    print()"
L000037 PL stage 1, 0 days past due, outstanding ₦18,153.48, EIR 77.2% a year, hazard 1.53%, LGD 99.55%
   event                      probability        exposure  discount          loss
   instalment 5 missed            1.5251%      ₦18,153.48    0.8483       ₦233.79
   instalment 6 missed            1.5018%       ₦9,276.47    0.8094       ₦112.24
   ECL (base scenario)                                                    ₦346.03

L000082 PL stage 2, 20 days past due, outstanding ₦18,153.48, EIR 77.2% a year, hazard 1.53%, LGD 99.55%
   event                      probability        exposure  discount          loss
   rolls from 20 days            43.1818%      ₦18,153.48    0.8961     ₦6,992.85
   instalment 6 missed            0.8665%       ₦9,276.47    0.8550        ₦68.41
   ECL (base scenario)                                                  ₦7,061.26

L000011 PL stage 1, 0 days past due, outstanding ₦162,752.79, EIR 74.4% a year, hazard 1.53%, LGD 99.55%
   event                      probability        exposure  discount          loss
   instalment 5 missed            1.5251%     ₦162,752.79    0.8483     ₦2,095.97
   instalment 6 missed            1.5018%     ₦145,401.78    0.8104     ₦1,761.59
   instalment 7 missed            1.4789%     ₦127,269.97    0.7742     ₦1,450.57
   instalment 8 missed            1.4563%     ₦108,322.23    0.7396     ₦1,161.47
   instalment 9 missed            1.4341%      ₦88,521.84    0.7066       ₦892.93
   instalment 10 missed           1.4123%      ₦67,830.43    0.6750       ₦643.68
   instalment 11 missed           1.3907%      ₦46,207.91    0.6449       ₦412.52
   instalment 12 missed           1.3695%      ₦23,612.38    0.6160       ₦198.31
   ECL (base scenario)                                                  ₦8,617.03

L000037 and L000082 have the same terms. One is current (₦346.03) and one is 20 days late (₦7,061.26). Redo the first ladder row by hand: 0.0152505 × 18,153.48 × 0.9955 × 0.8483 = 233.79. L000011 is a twelve-instalment loan with eight to go: its exposure falls with each instalment and its discount factor with each month.

5. The whole book under two scenarios. Add the provision for every loan and the stage table.

def provision(weights=None, backstop_only=False, lifetime=False, rate=None):
    """One row per loan that is not closed or written off: stage, gross carrying amount, and the ECL in whole
    kobo for each scenario and probability-weighted."""
    weights = weights or WEIGHTS
    haz, roll = hazards(), roll_rates()
    lgd = {p: v[3] for p, v in lgds().items()}
    loans, _, _ = book()
    rows = []
    for l, (stage, why) in stage_book(backstop_only).items():
        if stage is None:
            continue
        per = {s: sum(r[-1] for r in ecl_terms(l, stage, haz, roll, lgd, PD_MULTIPLIER[s], lifetime, rate))
               for s in PD_MULTIPLIER}
        weighted = sum(weights[s] * per[s] for s in per)
        rows.append(dict(loan_id=l, product=loans[l]["product"], stage=stage, gross=loans[l]["outstanding"],
                         **{s: round(v) for s, v in per.items()}, ecl=round(weighted)))
    return rows


def show_ecl(weights=None):
    rows = provision(weights)
    w = weights or WEIGHTS
    print("scenario weights: " + ", ".join(f"{s} {v:.0%} (hazards x{PD_MULTIPLIER[s]:g})" for s, v in w.items()))
    print(f"{'stage':<7}{'loans':>6}{'gross':>20}{'base':>18}{'downturn':>18}{'weighted ECL':>18}{'cover':>8}")
    tot = collections.Counter()
    for s in (1, 2, 3):
        sel = [r for r in rows if r["stage"] == s]
        vals = dict(n=len(sel), gross=sum(r["gross"] for r in sel), base=sum(r["base"] for r in sel),
                    downturn=sum(r["downturn"] for r in sel), ecl=sum(r["ecl"] for r in sel))
        tot.update(vals)
        print(f"{s:<7}{vals['n']:>6}{naira(vals['gross']):>20}{naira(vals['base']):>18}{naira(vals['downturn']):>18}"
              f"{naira(vals['ecl']):>18}{vals['ecl'] / vals['gross']:>8.2%}")
    print(f"{'all':<7}{tot['n']:>6}{naira(tot['gross']):>20}{naira(tot['base']):>18}{naira(tot['downturn']):>18}"
          f"{naira(tot['ecl']):>18}{tot['ecl'] / tot['gross']:>8.2%}")
    print("\nstage 1 and 2 by product:")
    for p in ("PL", "SME", "BNPL"):
        for s in (1, 2):
            sel = [r for r in rows if r["stage"] == s and r["product"] == p]
            if sel:
                g, e = sum(r["gross"] for r in sel), sum(r["ecl"] for r in sel)
                print(f"   {p:<5}stage {s}{len(sel):>5} loans {naira(g):>18}  ECL {naira(e):>16}  cover {e / g:.2%}")
python3 -c "import ifrs; ifrs.show_ecl()"
scenario weights: base 70% (hazards x1), downturn 30% (hazards x2)
stage   loans               gross              base          downturn      weighted ECL   cover
1         464      ₦75,370,828.17     ₦1,509,055.12     ₦2,962,777.43     ₦1,945,171.83   2.58%
2          40       ₦8,747,035.31     ₦5,854,596.52     ₦7,163,224.50     ₦6,247,184.89  71.42%
3         310      ₦10,654,315.82    ₦10,650,111.66    ₦10,650,111.66    ₦10,650,111.66  99.96%
all       814      ₦94,772,179.30    ₦18,013,763.30    ₦20,776,113.59    ₦18,842,468.38  19.88%

stage 1 and 2 by product:
   PL   stage 1  306 loans     ₦27,809,412.89  ECL    ₦1,394,429.31  cover 5.01%
   PL   stage 2   20 loans      ₦1,506,375.28  ECL      ₦821,199.28  cover 54.51%
   SME  stage 1  158 loans     ₦47,561,415.28  ECL      ₦550,742.52  cover 1.16%
   SME  stage 2   14 loans      ₦7,165,910.03  ECL    ₦5,353,318.19  cover 74.71%
   BNPL stage 2    6 loans         ₦74,750.00  ECL       ₦72,667.42  cover 97.21%

Stage 3 covers 99.96% of its balance in both scenarios. Stage 1 nearly doubles under the downturn (1.96 times) and stage 2 rises by 22%, because 43% doubled is 86% and 96% is capped at 100%. The weighted column is each loan’s 70/30 figure rounded to the kobo, so it differs by a few kobo from weighting the column totals: 0.7 × ₦1,509,055.12 + 0.3 × ₦2,962,777.43 = ₦1,945,171.81, against ₦1,945,171.83 here.

6. Change one choice at a time. Add the sensitivity table.

def show_sensitivity():
    """Total weighted ECL when one choice changes. The first line is the chapter's own answer."""
    def total(**kw):
        rows = provision(**kw)
        return sum(r["ecl"] for r in rows), [sum(r["ecl"] for r in rows if r["stage"] == k) for k in (1, 2, 3)]
    base, _ = total()
    print(f"{'choice':<52}{'total ECL':>18}{'change':>14}")
    for label, kw in (
            ("the chapter's answer", {}),
            ("backstop only (no relative test)", dict(backstop_only=True)),
            ("stage 1 measured over the whole life", dict(lifetime=True)),
            ("no discounting (rate 0)", dict(rate=0.0)),
            ("weights base 100%, downturn 0%", dict(weights={"base": 1.0, "downturn": 0.0})),
            ("weights base 50%, downturn 50%", dict(weights={"base": 0.5, "downturn": 0.5})),
            ("weights base 0%, downturn 100%", dict(weights={"base": 0.0, "downturn": 1.0}))):
        t, _ = total(**kw)
        print(f"{label:<52}{naira(t):>18}{naira(t - base):>16}")
    _, sched, _ = book()
    st = stage_book()
    furthest = max((due + DAY90 - CUT_OFF).days for l, (s, _) in st.items() if s in (1, 2)
                   for _, due, _, _ in sched[l] if due > CUT_OFF)
    print(f"\nthe furthest default date any stage 1 or 2 loan can have is {furthest} days after the cut-off; "
          f"the 12-month horizon is {(HORIZON - CUT_OFF).days}")
python3 -c "import ifrs; ifrs.show_sensitivity()"
choice                                                       total ECL        change
the chapter's answer                                    ₦18,842,468.38           ₦0.00
backstop only (no relative test)                        ₦17,421,857.98  -₦1,420,610.40
stage 1 measured over the whole life                    ₦18,842,468.38           ₦0.00
no discounting (rate 0)                                 ₦19,703,293.95     ₦860,825.57
weights base 100%, downturn 0%                          ₦18,013,763.30    -₦828,705.08
weights base 50%, downturn 50%                          ₦19,394,938.38     ₦552,470.00
weights base 0%, downturn 100%                          ₦20,776,113.59   ₦1,933,645.21

the furthest default date any stage 1 or 2 loan can have is 328 days after the cut-off; the 12-month horizon is 365

Stage 1 measured over the whole life gives the same total, because no stage 1 or 2 loan can default later than 328 days from the cut-off. Dropping the relative test saves ₦1,420,610.40. No discounting adds ₦860,825.57. The scenario weights span ₦2,762,350.29 from end to end. The largest choice is staging.

7. Build the cliff. Add a hypothetical longer loan. The book has none, so the function builds each loan’s schedule with the same rule as loans.py.

# ---- the cliff: where 12-month and lifetime ECL part ----------------------------------------------
def annuity(principal, rate, n):
    """Equal instalments on a reducing balance, as (instalment, principal part), in kobo (loans.py's rule)."""
    payment = round(principal * rate / (1 - (1 + rate) ** -n))
    rows, balance = [], principal
    for i in range(1, n + 1):
        interest = round(balance * rate)
        part = payment - interest if i < n else balance
        rows.append((payment if i < n else part + interest, part))
        balance -= part
    return rows


def show_cliff(principal=100_000_000, rate=0.045, fee_bps=100, product="PL"):
    """A new loan of the personal-loan type at origination, with n instalments: ECL over 12 months and over the life.
    Same hazard, LGD and 30-day months as the book; a hypothetical product, because the lab's loans end within 12 months."""
    h = hazards()[product][2]
    lgd = lgds()[product][3]
    print(f"₦{principal // 100:,} at {rate:.1%} a month, fee {fee_bps / 100:.0f}%, hazard {h:.2%} per instalment, LGD {lgd:.2%}")
    print(f"{'instalments':>12}{'EIR a year':>12}{'12-month ECL':>16}{'lifetime ECL':>16}{'ratio':>7}")
    for n in (6, 12, 24, 36):
        rows = annuity(principal, rate, n)
        net = principal - principal * fee_bps // 10_000
        lo, hi = 0.0, 200.0
        for _ in range(200):
            mid = (lo + hi) / 2
            if sum(t / (1 + mid) ** (30 * (i + 1) / 365) for i, (t, _) in enumerate(rows)) > net:
                lo = mid
            else:
                hi = mid
        g = (lo + hi) / 2
        left, alive, e12, life = principal, 1.0, 0.0, 0.0
        for i, (t, part) in enumerate(rows):
            default_day = 30 * (i + 1) + 90
            loss = alive * h * left * lgd * (1 + g) ** (-default_day / 365)
            life += loss
            if default_day <= 365:
                e12 += loss
            alive *= 1 - h
            left -= part
        print(f"{n:>12}{g:>12.1%}{naira(round(e12)):>16}{naira(round(life)):>16}{life / e12:>7.2f}")
python3 -c "import ifrs; ifrs.show_cliff()"
₦1,000,000 at 4.5% a month, fee 1%, hazard 1.53% per instalment, LGD 99.55%
 instalments  EIR a year    12-month ECL    lifetime ECL  ratio
           6       77.2%      ₦41,189.57      ₦41,189.57   1.00
          12       74.4%      ₦67,041.31      ₦71,329.40   1.06
          24       72.9%      ₦82,077.20     ₦118,651.77   1.45
          36       72.3%      ₦86,709.63     ₦152,087.30   1.75

A six-instalment loan has no cliff. A 12-instalment loan has a 6% one, because only the last instalments’ defaults fall after month 12. At 36 instalments the lifetime loss is 1.75 times the 12-month loss, and a loan moving from stage 1 to stage 2 would see its allowance rise by that factor before its PD changes at all.

8. Post it. Save this as post.py. It builds the ledger, posts the 70/30 provision, then re-weights to 50/50 and posts only the movement.

"""post.py: post the provision into a small double-entry ledger of its own and prove it.

Standard library only. Money is integer kobo. Run: python3 post.py
"""
import os
import sqlite3

import ifrs

LEDGER = "provision_ledger.sqlite"
ACCOUNTS = [(1100, "Loans receivable (gross)", "asset"), (1191, "Loss allowance, stage 1", "contra-asset"),
            (1192, "Loss allowance, stage 2", "contra-asset"), (1193, "Loss allowance, stage 3", "contra-asset"),
            (3000, "Opening balance equity", "equity"), (6100, "Impairment expense", "expense")]
ALLOWANCE = {1: 1191, 2: 1192, 3: 1193}


def open_ledger():
    if os.path.exists(LEDGER):
        os.remove(LEDGER)
    db = sqlite3.connect(LEDGER)
    db.executescript("""
        CREATE TABLE accounts (id INTEGER PRIMARY KEY, name TEXT, kind TEXT);
        CREATE TABLE journal (id INTEGER PRIMARY KEY, memo TEXT);
        CREATE TABLE lines (journal_id INTEGER, account_id INTEGER, debit_kobo INTEGER NOT NULL DEFAULT 0,
                            credit_kobo INTEGER NOT NULL DEFAULT 0);
        CREATE TABLE ecl_by_loan (version INTEGER, loan_id TEXT, product TEXT, stage INTEGER, gross_kobo INTEGER,
                                  ecl_kobo INTEGER);""")
    db.executemany("INSERT INTO accounts VALUES (?, ?, ?)", ACCOUNTS)
    return db


def post(db, memo, lines):
    """lines: [(account, debit, credit)]. Refuses an entry whose debits and credits differ."""
    lines = [l for l in lines if l[1] or l[2]]
    if sum(l[1] for l in lines) != sum(l[2] for l in lines):
        raise ValueError(f"{memo}: debits {sum(l[1] for l in lines)} != credits {sum(l[2] for l in lines)}")
    cur = db.execute("INSERT INTO journal (memo) VALUES (?)", (memo,))
    db.executemany("INSERT INTO lines VALUES (?, ?, ?, ?)", [(cur.lastrowid, *l) for l in lines])


def balance(db, account):
    return db.execute("SELECT COALESCE(SUM(debit_kobo - credit_kobo), 0) FROM lines WHERE account_id = ?",
                      (account,)).fetchone()[0]


def by_stage(rows):
    return {s: sum(r["ecl"] for r in rows if r["stage"] == s) for s in (1, 2, 3)}


def store(db, version, rows):
    db.executemany("INSERT INTO ecl_by_loan VALUES (?, ?, ?, ?, ?, ?)",
                   [(version, r["loan_id"], r["product"], r["stage"], r["gross"], r["ecl"]) for r in rows])


def main():
    db = open_ledger()
    v1 = ifrs.provision()
    gross = sum(r["gross"] for r in v1)
    post(db, "opening: loans receivable, written-off loans already removed", [(1100, gross, 0), (3000, 0, gross)])
    s1 = by_stage(v1)
    store(db, 1, v1)
    post(db, "provision at the cut-off, weights 70/30",
         [(6100, sum(s1.values()), 0)] + [(ALLOWANCE[s], 0, s1[s]) for s in (1, 2, 3)])
    # the weights change: post only the movement
    v2 = ifrs.provision({"base": 0.5, "downturn": 0.5})
    s2 = by_stage(v2)
    store(db, 2, v2)
    move = {s: s2[s] - s1[s] for s in (1, 2, 3)}
    post(db, "reweight scenarios to 50/50: movement only",
         [(6100, max(0, sum(move.values())), max(0, -sum(move.values())))] +
         [(ALLOWANCE[s], max(0, -move[s]), max(0, move[s])) for s in (1, 2, 3)])
    db.commit()

    print(f"{'account':<30}{'balance (Dr +, Cr -)':>24}")
    for a, name, _ in ACCOUNTS:
        print(f"{a} {name:<25}{ifrs.naira(balance(db, a)):>24}")
    print("\nproofs")
    d, c = db.execute("SELECT SUM(debit_kobo), SUM(credit_kobo) FROM lines").fetchone()
    print(f"  every journal balances; all debits {ifrs.naira(d)} = all credits {ifrs.naira(c)}: {d == c}")
    for s in (1, 2, 3):
        tbl = db.execute("SELECT SUM(ecl_kobo) FROM ecl_by_loan WHERE version = 2 AND stage = ?", (s,)).fetchone()[0]
        print(f"  stage {s}: allowance {ifrs.naira(-balance(db, ALLOWANCE[s]))} = sum of loan ECL {ifrs.naira(tbl)}: "
              f"{-balance(db, ALLOWANCE[s]) == tbl}")
    allowance = -sum(balance(db, a) for a in ALLOWANCE.values())
    print(f"  net loans = {ifrs.naira(balance(db, 1100))} - {ifrs.naira(allowance)} = "
          f"{ifrs.naira(balance(db, 1100) - allowance)}")
    print(f"  impairment expense {ifrs.naira(balance(db, 6100))} = allowance {ifrs.naira(allowance)}: "
          f"{balance(db, 6100) == allowance}")
    for jid, memo in db.execute("SELECT id, memo FROM journal"):
        print(f"\njournal {jid}: {memo}")
        for a, dr, cr in db.execute("SELECT account_id, debit_kobo, credit_kobo FROM lines WHERE journal_id = ?", (jid,)):
            print(f"   {'Dr' if dr else 'Cr'} {a}  {ifrs.naira(dr or cr):>18}")


if __name__ == "__main__":
    main()
python3 post.py
account                           balance (Dr +, Cr -)
1100 Loans receivable (gross)           ₦94,772,179.30
1191 Loss allowance, stage 1            -₦2,235,916.22
1192 Loss allowance, stage 2            -₦6,508,910.50
1193 Loss allowance, stage 3           -₦10,650,111.66
3000 Opening balance equity            -₦94,772,179.30
6100 Impairment expense                 ₦19,394,938.38

proofs
  every journal balances; all debits ₦114,167,117.68 = all credits ₦114,167,117.68: True
  stage 1: allowance ₦2,235,916.22 = sum of loan ECL ₦2,235,916.22: True
  stage 2: allowance ₦6,508,910.50 = sum of loan ECL ₦6,508,910.50: True
  stage 3: allowance ₦10,650,111.66 = sum of loan ECL ₦10,650,111.66: True
  net loans = ₦94,772,179.30 - ₦19,394,938.38 = ₦75,377,240.92
  impairment expense ₦19,394,938.38 = allowance ₦19,394,938.38: True

journal 1: opening: loans receivable, written-off loans already removed
   Dr 1100      ₦94,772,179.30
   Cr 3000      ₦94,772,179.30

journal 2: provision at the cut-off, weights 70/30
   Dr 6100      ₦18,842,468.38
   Cr 1191       ₦1,945,171.83
   Cr 1192       ₦6,247,184.89
   Cr 1193      ₦10,650,111.66

journal 3: reweight scenarios to 50/50: movement only
   Dr 6100         ₦552,470.00
   Cr 1191         ₦290,744.39
   Cr 1192         ₦261,725.61

The stage 1 allowance of ₦2,235,916.22 is the sum of 464 loans’ ECL under 50/50 weights, and journal 3 is the difference from the 70/30 figure: ₦290,744.39 for stage 1 and ₦261,725.61 for stage 2, ₦552,470.00 in all. Stage 3 did not move, so it has no line.

9. Compare with a prudential table. Add this, with illustrative bands (20%, 50% and 100%) as inputs. They are not confirmed from the regulator’s text.

# ---- a prudential comparison (ILLUSTRATIVE bands, not confirmed: read the regulator's text before relying on them) ------
PRUDENTIAL = [(181, 1.00, "lost"), (91, 0.50, "doubtful"), (61, 0.20, "substandard"), (0, 0.0, "performing")]


def show_prudential():
    loans, _, _ = book()
    rows = provision()
    print(f"{'band by days past due':<24}{'loans':>6}{'gross':>18}{'prudential':>16}{'IFRS 9 ECL':>16}")
    tot_p = tot_e = 0
    for floor, pct, name in PRUDENTIAL[::-1]:
        top = next((f for f, _, _ in PRUDENTIAL[::-1] if f > floor), None)
        sel = [r for r in rows if floor <= loans[r["loan_id"]]["dpd"] and (top is None or loans[r["loan_id"]]["dpd"] < top)]
        g, e = sum(r["gross"] for r in sel), sum(r["ecl"] for r in sel)
        p = g * round(pct * 100) // 100
        tot_p += p
        tot_e += e
        label = f"{floor}+ {name}" if top is None else f"{floor}-{top - 1} {name}"
        print(f"{label:<24}{len(sel):>6}{naira(g):>18}{naira(p):>16}{naira(e):>16}")
    print(f"{'all':<24}{'':>6}{'':>18}{naira(tot_p):>16}{naira(tot_e):>16}")
    print(f"prudential minus IFRS 9: {naira(tot_p - tot_e)}"
          + ("  (prudential is higher: the difference would go to a non-distributable reserve)" if tot_p > tot_e
             else "  (IFRS 9 is higher: nothing to transfer)"))
python3 -c "import ifrs; ifrs.show_prudential()"
band by days past due    loans             gross      prudential      IFRS 9 ECL
0-60 performing            493    ₦81,673,784.70           ₦0.00   ₦5,877,032.31
61-90 substandard           11     ₦2,444,078.78     ₦488,815.75   ₦2,315,324.41
91-180 doubtful            310    ₦10,654,315.82   ₦5,327,157.91  ₦10,650,111.66
181+ lost                    0             ₦0.00           ₦0.00           ₦0.00
all                                                ₦5,815,973.66  ₦18,842,468.38
prudential minus IFRS 9: -₦13,026,494.72  (IFRS 9 is higher: nothing to transfer)

The table gives nothing for the 493 loans under 61 days overdue and the 181+ line is empty because the written-off loans have left the book. IFRS 9 is ₦13,026,494.72 higher, so in this book there is nothing to transfer to a reserve. Read the guideline’s own text before using any band.

Tighten the staging test. In ifrs.py set SICR_MULTIPLE = 5.0 and run steps 3 and 5 again.

python3 -c "import ifrs; ifrs.show_staging()" | sed -n 5,7p
python3 -c "import ifrs; ifrs.show_ecl()" | sed -n 3,6p
backstop + relative test       1    475          ₦76,390,917.43
backstop + relative test       2     29           ₦7,726,946.05
backstop + relative test       3    310          ₦10,654,315.82
1         475      ₦76,390,917.43     ₦1,547,412.69     ₦3,037,438.25     ₦1,994,420.41   2.61%
2          29       ₦7,726,946.05     ₦5,490,208.77     ₦6,463,112.27     ₦5,782,079.81  74.83%
3         310      ₦10,654,315.82    ₦10,650,111.66    ₦10,650,111.66    ₦10,650,111.66  99.96%
all       814      ₦94,772,179.30    ₦17,687,733.12    ₦20,150,662.18    ₦18,426,611.88  19.44%

Stage 2 falls from 40 loans to 29 and the total ECL from ₦18,842,468.38 to ₦18,426,611.88, a fall of ₦415,856.50, for a change in one constant that no data told you to make. Then try SICR_MULTIPLE = 10.0: stage 2 falls to 18 loans, the ones the backstop holds, and stays there however high you set the multiple. Set the constant back to 2.0 before you go on.

ARTEFACT Write the month's provisions note ~50 MIN
YOU PRODUCEA monthly IFRS 9 provisions note

Template

# Provisions note: <institution>, <month>
Prepared by <credit-risk analyst>. Signed by <finance controller>.

## 1. Staging at <cut-off date>
Rule: backstop at <days> past due; relative test at <multiple> times the PD at origination. Signed <name, date>.
| Stage | Loans | Gross carrying amount | In since last month | Out since last month |
Stage 2 only because of the relative test: <loans>.

## 2. ECL by stage
| Stage | Gross | Base ECL | Downturn ECL | Weighted ECL | Cover |
Scenario weights: <base %> / <downturn %>. Owner of the weights (outside finance): <name>.

## 3. Movement from last month
| Line | Stage 1 | Stage 2 | Stage 3 | Total |
Opening allowance; change from staging; change from inputs or weights; overlay; closing allowance.
Impairment charge for the month: <amount>, equal to the change in the allowance.

## 4. Overlays
<amount, what the model misses, evidence, owner, review date>, or "none".

## 5. Do the books agree?
<journals balance; allowance by stage equals the sum of loan ECL; net loans = gross less allowance>.

## 6. How this could be wrong
<one way, and what would show it>

## 7. Decision and sign-off
Decision needed: <what, from whom, by when>. Out of scope: <what this note does not cover>.
Prepared <name, date>. Approved <name, date>.
WORKED EXAMPLE

At the Ibadan microfinance bank, Ajoke, the credit-risk analyst, writes this note each month and Agbani, the finance controller, signs it. The lab has one book and one cut-off, 2026-10-28, so there is no real last month. As a device, the example takes the 70/30 run as last month’s closing allowance and the 50/50 run as this month’s, on the same loans. Only the weights differ. In a real month loans would also change stage, new loans would arrive and the inputs would be re-estimated, and the movement table would show those causes too.

Staging. Backstop at 30 days, relative test at 2.0 times, both illustrative and assumed signed by the risk committee. Loss given default is 99.55% on personal loans and 100% on the other products. Stage 1: 464 loans, ₦75,370,828.17. Stage 2: 40 loans, ₦8,747,035.31, of which 22 are there only because of the relative test. Stage 3: 310 loans, ₦10,654,315.82.

ECL at 70/30. Stage 1 ₦1,945,171.83 (cover 2.58%), stage 2 ₦6,247,184.89 (71.42%), stage 3 ₦10,650,111.66 (99.96%): ₦18,842,468.38 in all.

Movement. Opening ₦18,842,468.38. Reweighting to 50/50 adds ₦290,744.39 to stage 1 and ₦261,725.61 to stage 2, ₦552,470.00 in all. Closing ₦19,394,938.38 (stage 1 ₦2,235,916.22, stage 2 ₦6,508,910.50, stage 3 ₦10,650,111.66). The charge is ₦552,470.00. By construction, none of it comes from staging or inputs.

Overlay. None.

Books. All journals balance; each stage’s allowance equals its loans’ ECL; net loans are ₦94,772,179.30 less ₦19,394,938.38, which is ₦75,377,240.92. This shows the books agree with the model, not that the model is right.

Wrong if. The roll rates rest on 106 loan-snapshots at 1 to 7 days and 132 at 8 to 30. A back-test showing fewer loans reaching 90 days would show stage 2 is overstated.

Decision. Agbani is asked to approve the 50/50 weights, which cost ₦552,470.00, once their owner outside finance has supplied the basis. Out of scope: the prudential table.

Now you

You are the credit-risk analyst at an unnamed microfinance lender of about 90 people in Abeokuta. Treat the lab’s 70/30 run with SICR_MULTIPLE = 2.0 as last month’s close (a device: the lab has one book, so last month and this month hold the same loans). This month its risk committee raises the multiple to 5.0, and you rerun steps 3 and 5 as the lab’s break does, which prints the new staging and ECL by stage. The committee also asks for a management overlay of ₦500,000 for a traders’ strike that the model cannot see; treat that as a stated assumption, and say which stage allowance it sits in and why.

Write the note. It must reconcile opening to closing by stage, show the overlay separately from the model, and say what the change of constant, which no data told anyone to make, did to the book. The finance director will sign it, and the board’s audit committee will read it to decide whether to accept the new multiple.

Self-check

DECIDE

Agbani's auditors accept either a backstop-only staging rule or a relative test on PD, if it is documented. In the lab's book the backstop puts 18 loans in stage 2 and the relative test 40, and the provision differs by ₦1,420,610.40 (₦17,421,857.98 against ₦18,842,468.38). The roll rates behind the relative test rest on 106 loan-snapshots at 1 to 7 days and 132 at 8 to 30. Ajoke must recommend a rule.

READING
  1. DOC
    IFRS 9 Financial Instruments (IFRS Foundation, 2021 edition, HTML) IFRS Foundation

    The standard's own page, with the full text. Read Section 5.5 on impairment and the application guidance B5.5.1 to B5.5.55 on significant increase in credit risk and on measuring ECL; skip the hedge accounting sections.

  2. DOC
    Post-implementation Review of IFRS 9: Impairment (project page) IASB, 2023

    The standard-setter's own review of how the impairment model has worked, with its 2023 request for information and the feedback on it. Read what it asks about significant increase in credit risk and forward-looking information; skip the disclosure questions.

  3. DOC
    Significant increases in credit risk, ITG staff paper IFRS Transition Resource Group for Impairment of Financial Instruments, 2015

    A staff paper written for the group that took questions from preparers. Read it for how practitioners were told to apply the SICR test before they had data.

  4. DOC
    CBN Guidance Note to Banks and Discount Houses on the Implementation of IFRS 9 in Nigeria Central Bank of Nigeria, 2016

    The regulator's expectations for banks. Read it for what the regulator expects of banks; this chapter has not read it in full, and it is the banks' note, so check which guidance applies to your kind of institution.

  5. DOC
    CBN IFRS guidance note for other financial institutions Central Bank of Nigeria, 2019

    The note for microfinance banks and other non-bank institutions. Read what it expects of an IFRS 9 implementation project and its timetable; this chapter has not read it in full.

  6. DOC
    CBN Prudential Guidelines for Microfinance Banks Central Bank of Nigeria, 2019

    The regulator's guideline for microfinance banks. Check whether this is the final text, then read its loan-classification and provisioning section; do not rely on the illustrative bands in this chapter.

  7. DOC
    CBN circular on the transitional arrangement for the treatment of IFRS 9 Central Bank of Nigeria, 2018

    The circular on the regulatory risk reserve and the transition for banks. Read how the reserve is calculated; it concerns banks and not the other institutions.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Restructuring and forbearance →