STAFFCHAPTER 33

Writing a credit policy that a regulator, a funder and a board can read

A credit policy is a list of statements a stranger can test against your loans. Copy your decision engine's rules into one and the test finds the words the engine and the page mean differently

60 MINLENDING AND CREDITUPDATED 2026-11-14
PREDICT

Ladun copies the engine's rules into a policy. She defines monthly inflow as the money funded into the wallet in the 90 days before the application, the only figure a funder can verify from the application date. She then tests the 3,645 loans Owoleaf approved. Roughly how many break the policy?

A credit policy is the document that says how a lender decides to lend: to whom, how much, on what terms, who may break its rules, and how the lender knows when the book has drifted from them. Module 2 taught the decisions in the policy one at a time: scores and cut-offs, limits and prices. This chapter puts them on a page that other people read.

The lab runs on Owoleaf’s loan book at scale 1 (data1/). The company in the prose is Owoleaf at 60 people, preparing for a funder that this chapter does not name. Nothing here is legal advice, and nothing says what to borrow or from whom.

Who reads it, and what each reader tests

One document has several readers, and each asks a different question of it.

Reader The question What they check
Board What risk are we taking, and who may take more? Appetite, limits, the exception rule, the triggers
Funder Will the loans I fund look like the policy says? They sample loans and re-perform the decision from the policy’s words
Regulator Does a written, approved process exist, and is it followed? That the policy is approved, current and consistent with the records
Credit team and engineers What do I build and what may I approve? Each rule as a condition on named fields, with an order
Auditors Can I trace a decision to a clause? The evidence for each clause, and for each exception

Two of those readers are the reason the document exists at all. The Basel Committee’s Principles for the Management of Credit Risk, first issued in 2000, were republished in a revised version dated 30 April 2025, which law-firm commentary in search results describes as limited, targeted technical amendmentsas of 2026-11. The search results did not return the revised principles’ wording, so read the provisions on the board and on credit policy before you quote them. It is a document for bank supervisors and not Nigerian law.

For Nigerian lenders under the Central Bank of Nigeria (CBN), search results quote two CBN prudential guideline documents dated August 2019. The version for finance companies, which the search results describe as an exposure draft issued for comments, is quoted as saying that a finance company shall put in place a comprehensive credit policy duly approved by its board of directorsas of 2026-11. The version for microfinance banks, also an August 2019 exposure draft, is quoted as saying that a microfinance bank shall have a comprehensive credit policy duly approved by its boardas of 2026-11. The search results did not show whether final versions were issued or what they say, so treat the wording as unconfirmed and check the CBN’s current text. Which licence Owoleaf’s lending needs is a question for the licences and structures chapter later in this module. This chapter does not say. It also found nothing on whether the Federal Competition and Consumer Protection Commission (FCCPC) approval process asks for a credit policy. The consumer protection chapter reads what is known about that process. A funder’s demand needs no regulator behind it: it is a condition of the money.

What a policy contains

A policy is short. Owoleaf’s, in the lab, is about 570 words. It answers nine questions, in this order, because each section’s rules assume the one before.

Section Question Where Owoleaf’s answer comes from
1. Purpose and appetite What are we for, and what will we not do? The board. Appetite is a choice, and it comes before any data
2. Products What do we offer, on what terms? The loan_products table and loans.py
3. Eligibility and credit criteria Who qualifies, in what order is it checked? The decline rules in loans.py (the loan lifecycle chapter lists them)
4. Limits How much? The inflow cap in loans.py, and the limits from module 2
5. Terms What does the customer owe, and when? Rate, fee and late-fee rules, the interest and APR chapter
6. Arrears and recovery When is a loan in default and who acts? The 90 and 180 days past due lines in loans.py
7. Approvals and exceptions Who may go outside the rules? The head of credit and the board
8. Monitoring What tells us the book has drifted? Triggers on portfolio metrics
9. Review Who owns it, and when does it change? Version, owner, review date

Section 7 is the one that is missing from most first drafts. Without it a policy has no way to say that a loan outside the rules was a decision. Every loan outside them is then a breach, whatever the reason.

Sections 3 and 4 carry the weight. A criterion is an ordered list. The loan lifecycle chapter showed why the order matters: the decline reason on a row is the first rule the application failed, so half the lab’s declines are amount_below_product_minimum, the last rule on the list, and read wrongly they say the risk rules are too tight. The policy states the order, and says that the reason recorded is the first failure.

Write it from what the engine does

Ladun does not invent anything. She reads loans.py, whose rules are the lender’s actual rules, and writes down what each does:

  1. A bureau score below the product’s cut-off declines (580 for SAL, 620 for PL, 560 for BNPL, 600 for SME). SAL is the salary advance, PL the personal loan, BNPL buy now pay later and SME working capital for merchants.
  2. More than 6 bureau enquiries in 90 days declines.
  3. Two or more delinquencies in 12 months decline.
  4. Monthly wallet inflow below ₦5,000 declines, except for BNPL.
  5. The amount is capped at a multiple of monthly inflow, and a thin file (a customer the bureau has no history for) at ₦50,000. A capped amount below the product’s minimum declines.

Each of these is a statement about data. That is the test of a clause. A good one has five parts: an identifier, a condition on fields the lender holds, a scope (every loan, or one product), the date its facts are taken from, and the table that holds the evidence. “Principal is at most one times the monthly inflow, for a salary advance” has the first three. It has no date and no evidence yet. Those two gaps are where the lab’s findings come from.

The word that means two things

Rule 5 uses “monthly inflow”. The engine computes it as the wallet’s total inflows, from sign-up to the end of the data, divided by the months from sign-up to the cut-off date of 28 October 2026. That sum contains money that arrived after the customer applied. A lender cannot know it at the application date, and a funder who re-performs the decision from a snapshot on that date cannot reproduce it.

Ladun cannot put that definition in a policy that a stranger must test. She writes the one Module 2’s limits section used: the money funded into the wallet by bank transfer or card in the 90 days before the application date, divided by the months of history, at least 30 days and at most 90. Nothing after the application date counts. That one definition changes every figure in the rest of this chapter.

This is the general trap. Words in a policy that name a quantity (income, balance, arrears, exposure, a month) need a definition with a window, a source and an as-of date. A policy is a list of conditions on quantities, and a quantity nobody has defined is a condition nobody can test.

A clause is a test

The policy and the tests come from the same file, so they cannot drift apart. In the lab the policy is data (rules.py), a script renders it as a document, and another tests the book against it. When a number changes, it changes in one place.

A test returns one of three results.

Result Meaning
PASS The data shows every loan in scope keeps the clause
EXCEPTION One or more loans break it, and the test lists them
GAP The book cannot show either, because the evidence table does not exist

The consumer protection chapter used the same three words for rules, with FAIL where this chapter says EXCEPTION. Here the unit is a loan, not a rule, and a loan is an exception to a clause.

Two details of testing. First, test each clause on its own and not in the engine’s order. The engine stops at the first failure, so a loan that fails two rules shows one. A funder wants to know which clauses a loan breaks, all of them. Second, test each clause on what was known at the application date, and say where a test reads later facts. The lab’s late-fee clause (T3) and the arrears clause (A1) read what happened after disbursement, because they are about conduct and status, not about the decision.

What the test finds

The lab’s policy has fourteen clauses that a loan can break. Twelve pass for every loan, among them the product terms, the late fee and the status ladder. Two have exceptions: the cap on amount (L2) and the income rule (I1). Four more clauses have no evidence in the book at all.

Run on data1, 460 of 3,645 approved loans (12.6%) break L2, and 119 of those also break I1. They hold ₦49,113,000 of the ₦611,757,000 lent, and ₦19,399,000 of that sits above the cap. The cause is the definition. The engine divides by the months from sign-up to the cut-off and the policy by at most 90 days, so the two sums are furthest apart for a new wallet. The count falls as wallets age: 28.2% of loans to wallets under 30 days old are exceptions, 5.2% from 30 to 89 days and 2.3% from 90 days. By month, exceptions fall from 65.7% of January’s loans to 5.0% of June’s, as the lab’s wallets age.

The same definition changes the decisions the other way. The policy would approve 1,152 applications that Owoleaf declined. A policy is not a stricter copy of the engine. It is a different rule, and aligning them is a decision, not a fix. Three choices follow, and each costs something:

  1. Change the engine to the policy’s definition. Every future decision can be re-performed. Volume changes, so the funder’s forecast does too.
  2. Change the policy to the engine’s definition. Zero exceptions. A funder cannot check the clause, and the lender has taken a figure it cannot see at the time of decision into its own rules. The lab’s break step shows how clean this looks.
  3. Keep both for a stated period. The policy carries the 90-day definition. The 460 loans are disclosed as exceptions of one known cause, with a dated engine change.

The exceptions did not behave much worse than the other loans. Among salary advances 15.8% of exceptions were 90 or more days past due, against 14.1% of conforming loans, and among BNPL loans 11.3% against 8.2%. These are counts of tens of loans, and PL and SME loans are still running, so the table proves nothing. It shows only that the exceptions are not obviously the cause of the book’s losses. A funder cares most about the next thing.

The register that does not exist

The policy says a loan outside sections 3 and 4 needs a written exception: a reason, a named approver and a date. The book has no table for that. Every one of the 460 is therefore an exception with no recorded approval. The test writes exceptions_data1.csv with empty approver and reason_recorded columns, and those columns stay empty until a person fills them with something that is true. Back-filling them to make the rate look better is falsifying a record. The honest report has three numbers: how many loans are outside the policy, how many have a recorded approval, and the cause of the rest.

Module 3’s model risk chapter met the same thing as an override log. A lender that lets staff or a system go outside its rules needs a register of who and why, or the policy cannot tell an exception from an error. Delegated authority, which sets how large an exception each person may approve, is the subject of the credit risk governance chapter later in this module. Here the policy only states that approval is a named role.

The book has no other records the policy asks for either. It holds no consent for each bureau check, no copy of the offer the customer accepted and no sign that a person can review a decline. Those clauses are GAPs, and each is a build. The credit data chapter explains why consent is the first.

A clause you have not built

A policy that holds only what is true today does not guide anyone. A policy that states what the lender wants without saying what is in force misleads. The way out is a status on each clause: in force from a date, or proposed with a target date. Test in-force clauses against loans after their date and call breaches exceptions. Test proposed clauses as a what-if, and call the result an impact.

The lab tests two proposed clauses.

P1, identity. The name from the identity check must match the applicant. The engine does not check this today. Of the 3,645 loans, 158 had a mismatch and 61 of them were 90 or more days past due (38.6%), against 8.8% of the rest. The lending fraud chapter weighs what such a rule costs honest customers whose names are spelt in more than one way, so a clause on identity needs a route to a person.

P2, affordability limit. The limits from the decisions chapter: a share of monthly inflow by points band, divided by the monthly burden per naira lent. Applied to the book, 1,266 of 1,959 salary advances (64.6%) and 236 of 766 BNPL loans (30.8%) sit above it. Those loans went bad more often, 16.2% against 11.0% for salary advances and 10.6% against 7.7% for BNPL. Adopting P2 as an in-force clause would make most of the salary-advance book an exception on day one. As a proposal it tells Ladun the price of the clause: a cut in volume the funder’s forecast has to carry.

Triggers: the part that watches

A monitoring section names a measure, a ceiling, an owner and an action. The ceilings below are illustrative and Ladun fixes them before she tests the book, the same discipline as a cut-off: choose first, test after, or the test confirms whatever you saw.

Trigger Measure Ceiling
M1 90 or more days past due, by product and disbursement month 10%
M2 One employer’s share of open salary-advance principal 5%
M3 Loans approved outside the policy, as a share of the month’s approvals 2%

The book breaches all three. Seven of the nine salary-advance and BNPL product-months that have 30 loans or more are over 10%. EMP07 holds 7.6% of open salary-advance principal on 27 June 2026, the day exposure peaks, which is the figure the employer lending chapter found. Every month’s exception rate is above 2%.

A book that breaches every trigger on the first day does not show that the triggers are wrong. It says the lender is outside its own appetite, and that the board must see it before the funder does. Check the economics too. The salary advance breaks even at a bad rate of about 1.6% at its price in the decisions chapter’s illustrative costs, so a 10% ceiling already accepts a loss. A ceiling should be derived from the price and costs of the product, as the decisions chapter derives the break-even bad rate for the salary advance. PL and SME loans are left out of M1 because they are still running, so their 90-day rates are unfinished.

A trigger without an action is decoration. Each needs a line: who is told, within what time, and what stops (new lending to one employer, a product paused, a cut-off raised).

Keeping it true

Three habits keep a policy from becoming a document nobody opens.

  • One source. The policy is data, the document is rendered from it and the tests read it. A change is a change to the data, with a version, a date and an approver.
  • A re-run on every change. Rerun the replay: does the policy still reproduce the engine’s decisions, on the definitions it states? The lab’s first result, 8,386 of 8,386, is the check to repeat after every engine release.
  • A review date and an owner. The head of credit owns it and the board approves it. A trigger firing is a reason to review, not only the calendar.

Where it goes wrong

  • Writing the policy to describe the engine. It then passes every test and says nothing a stranger can check. Test the words, not only the numbers.
  • Undefined quantities. Income, balance and arrears with no window or as-of date.
  • Back-filling approvals. An exception register filled in after the fact is a false record.
  • Aspirational clauses stated as in force. Mark proposals as proposals.
  • Ceilings chosen after the data. They confirm what you already saw.
  • Counting exceptions once. Report clauses broken, loans affected and the principal involved, and say which you mean.
  • A pass read as a clearance. Twelve of fourteen clauses pass here, and none shows the customer was told the price.
LAB Write Owoleaf's credit policy as data, render it and test the book on data1 ~60 MIN
YOU NEEDPython 3.9 or later (standard library only)labs/finance with the scale 1 book, collections and signals built into data1About 720 MB of disk for data1 and about 40 seconds to build it if you have notNo Docker, no packages, no mock services

You work in labs/finance. Every script reads data1/finance.sqlite read-only and writes into a new policy/ folder. Money is integer kobo. Every cut-off, ceiling and fee is the lab’s illustrative value, copied from loans.py and the decisions chapter, or written for this chapter and labelled so.

1. Check the book. If data1/ does not exist, build it with the README’s command (about 40 seconds), then add the signals and employers table. Then check the tables this chapter reads.

cd labs/finance
python3 generate.py --scale 1 --out data1 && python3 loans.py --out data1 \
  && python3 cards.py --out data1 && python3 collect.py --out data1 \
  && python3 book3.py --out data1
mkdir -p policy
python3 - <<'PY'
import sqlite3
db = sqlite3.connect("file:data1/finance.sqlite?mode=ro", uri=True)
for t in ("applications", "loans", "applicant_signals", "loan_employers"):
    print(db.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0], t)
PY
8386 applications
3645 loans
8386 applicant_signals
1959 loan_employers

Those four counts are the ones the earlier modules quote. If loan_employers is missing, run python3 book3.py --out data1.

2. Write the policy as data. Save this as policy/rules.py. It holds every figure in the policy, the one function that applies it (decide), and the one definition of monthly inflow the policy uses (monthly_policy) beside the engine’s (monthly_engine).

"""Owoleaf's credit policy as data, and the one function that applies it.

Everything here is ILLUSTRATIVE: the numbers come from the lab's own rules (loans.py and
the decisions chapter), not from the CBN, the FCCPC or any funder. Money is integer kobo.
"""
import datetime as dt
import sqlite3

NAIRA = 100
VERSION = "0.1 draft"

# Products: the terms the policy says Owoleaf offers (copied from loans.py and checked against
# the loan_products table in testbook.py).
PRODUCTS = {
    #        borrower      min        max        tenors       rate_bps fee_bps late_fee   cut-off  inflow cap (num, den) x instalments
    "SAL":  dict(kind="individual", lo=10_000,  hi=150_000,   tenors=[1],            rate=500, fee=100, late=500,   cutoff=580, cap=(1, 1, False)),
    "PL":   dict(kind="individual", lo=50_000,  hi=1_000_000, tenors=[3, 6, 9, 12],  rate=450, fee=100, late=1_000, cutoff=620, cap=(2, 3, True)),
    "BNPL": dict(kind="individual", lo=20_000,  hi=300_000,   tenors=[4],            rate=0,   fee=0,   late=500,   cutoff=560, cap=(1, 1, False)),
    "SME":  dict(kind="merchant",   lo=200_000, hi=5_000_000, tenors=[3, 6],         rate=350, fee=150, late=2_000, cutoff=600, cap=(2, 3, True)),
}
MAX_ENQUIRIES_90D = 6            # more than this declines
MAX_DELINQUENT_12M = 1           # two or more declines
MIN_MONTHLY_INFLOW = 5_000 * NAIRA   # not required for BNPL
THIN_FILE_MAX = 50_000 * NAIRA
MIN_WALLET_AGE_DAYS = 7
DEFAULT_DPD, WRITE_OFF_DPD = 90, 180
LATE_FEE_AFTER_DAYS = 3
ROUND_LIMITS_TO = 100_000        # amounts are rounded down to a whole N1,000

CUT_OFF = dt.date(2026, 10, 28)


def monthly_inflow(inflow_kobo, days):
    """Integer kobo a month: inflows divided by the months of history, 30 to 90 days."""
    return inflow_kobo * 30 // days


def cap_kobo(code, instalments, monthly):
    """The most the policy lends: a multiple of monthly inflow, rounded down to a whole N1,000.
    SAL and BNPL: 1 x monthly inflow. PL and SME: 2/3 of a month of inflow per instalment."""
    num, den, per_instalment = PRODUCTS[code]["cap"]
    n = instalments if per_instalment else 1
    return monthly * num * n // den // ROUND_LIMITS_TO * ROUND_LIMITS_TO


def decide(code, instalments, requested, hit, score, delinquent, enquiries, monthly):
    """The policy's decision rules, in order. Returns (decision, reason, amount in kobo)."""
    p = PRODUCTS[code]
    if hit and score < p["cutoff"]:
        return "declined", "score_below_cutoff", 0
    if enquiries > MAX_ENQUIRIES_90D:
        return "declined", "too_many_recent_enquiries", 0
    if hit and delinquent > MAX_DELINQUENT_12M:
        return "declined", "recent_delinquency", 0
    if code != "BNPL" and monthly < MIN_MONTHLY_INFLOW:
        return "declined", "insufficient_income_evidence", 0
    cap = cap_kobo(code, instalments, monthly)
    if not hit:
        cap = min(cap, THIN_FILE_MAX)
    amount = max(0, min(requested, cap))
    if amount < p["lo"] * NAIRA:
        return "declined", "amount_below_product_minimum", 0
    return "approved", None, amount


def naira(kobo):
    return f"₦{kobo // 100:,}.{abs(kobo) % 100:02d}" if kobo >= 0 else "-" + naira(-kobo)


def connect(folder):
    return sqlite3.connect(f"file:{folder}/finance.sqlite?mode=ro", uri=True)


APPS = """
SELECT a.id, a.customer_id, a.product, a.instalments, a.requested_kobo, a.decision, a.decline_reason,
       a.approved_kobo, a.applied_at, b.hit, COALESCE(b.score, 0), b.delinquent_12m, b.enquiries_90d,
       c.kind, c.kyc_tier, substr(c.signup_at, 1, 10),
       (SELECT COALESCE(SUM(t.amount_kobo), 0) FROM transactions t
         WHERE t.customer_id = a.customer_id AND t.status = 'succeeded'
           AND t.kind IN ('funding_transfer', 'funding_card')) AS inflow_all,
       (SELECT COALESCE(SUM(t.amount_kobo), 0) FROM transactions t
         WHERE t.customer_id = a.customer_id AND t.status = 'succeeded'
           AND t.kind IN ('funding_transfer', 'funding_card')
           AND t.created_at >= date(a.applied_at, '-90 days') AND t.created_at < a.applied_at) AS inflow_90d
FROM applications a
JOIN bureau_reports b ON b.id = a.bureau_report_id
JOIN customers c ON c.id = a.customer_id
ORDER BY a.id
"""
COLS = ("id customer product instalments requested decision reason approved applied hit score delinquent "
        "enquiries kind tier signup inflow_all inflow_90d").split()


def applications(db):
    """Every application with what the policy needs, as dicts, with both inflow definitions applied."""
    out = []
    for row in db.execute(APPS):
        a = dict(zip(COLS, row))
        applied = dt.date.fromisoformat(a["applied"])
        signup = dt.date.fromisoformat(a["signup"])
        a["age_days"] = (applied - signup).days
        # The engine's definition (loans.py): all inflows ever, over the months from sign-up to the cut-off.
        # It uses money that arrives after the application date.
        a["monthly_engine"] = (a["inflow_all"] if (CUT_OFF - signup).days < 30
                               else monthly_inflow(a["inflow_all"], (CUT_OFF - signup).days))
        # The policy's definition: the 90 days before the application, over 30 to 90 days of history.
        a["monthly_policy"] = monthly_inflow(a["inflow_90d"], max(30, min(90, a["age_days"])))
        out.append(a)
    return out

Nothing runs yet. Read decide: it is the five rules of loans.py in order, written with integers. Read applications: it computes both definitions of inflow for every application.

3. Render the document. Save this as policy/render.py. It writes policy/CREDIT_POLICY.md from rules.py.

"""Write the policy document from rules.py, so the document and the tests share one source."""
from rules import *

L = [f"# Owoleaf credit policy, version {VERSION}", "",
     "Status: DRAFT for the head of credit. Every figure is ILLUSTRATIVE (the lab's own rules).", "",
     "## 1. Purpose and appetite",
     "Owoleaf lends only to its own wallet customers: individuals (SAL, PL, BNPL) and merchants (SME).",
     "It does not lend to a customer with no wallet history, and it does not lend more than a customer's wallet inflows support.", "",
     "## 2. Products", "",
     "| Product | Borrower | Amount | Instalments | Rate per period | Fee | Late fee | Bureau cut-off |", "|---|---|---|---|---|---|---|---|"]
for code, p in PRODUCTS.items():
    L.append(f"| {code} | {p['kind']} | ₦{p['lo']:,} to ₦{p['hi']:,} | {', '.join(map(str, p['tenors']))} | {p['rate'] / 100:.2f}% | "
             f"{p['fee'] / 100:.2f}% | ₦{p['late']:,} | {p['cutoff']} |")
L += ["", "## 3. Eligibility and credit criteria",
      "Rules apply in this order and the first failure is the decline reason.",
      f"- E1. The wallet is at least {MIN_WALLET_AGE_DAYS} days old on the application date.",
      "- E2. Individuals borrow SAL, PL and BNPL; merchants borrow SME.",
      "- E3. A tier 1 customer is not offered a personal loan (PL).",
      "- C1. A bureau score below the product's cut-off declines (when the bureau holds a file).",
      f"- C2. More than {MAX_ENQUIRIES_90D} bureau enquiries in 90 days declines.",
      f"- C3. More than {MAX_DELINQUENT_12M} delinquency in 12 months declines (when the bureau holds a file).",
      f"- I1. Monthly wallet inflow below {naira(MIN_MONTHLY_INFLOW)} declines (not BNPL).",
      "- Monthly wallet inflow means: money funded into the wallet by bank transfer or card in the 90 days before the application date,",
      "  divided by the months of history (at least 30 days, at most 90). Nothing after the application date counts.", "",
      "## 4. Limits",
      "- L1. The amount is within the product's minimum and maximum.",
      "- L2. The amount is at most 1 x monthly inflow (SAL, BNPL) or 2/3 of a month of inflow per instalment (PL, SME), rounded down to a whole ₦1,000.",
      f"- L3. A thin file (no bureau history) borrows at most {naira(THIN_FILE_MAX)}.",
      "- If the limit is below the product's minimum, the application is declined.", "",
      "## 5. Terms",
      "- T1. The number of instalments is one the product offers.",
      "- T2. The rate and fee are the product's. The fee is taken from the principal at disbursement.",
      f"- T3. A late fee is charged once on an instalment paid in full more than {LATE_FEE_AFTER_DAYS} days late. A part payment carries none.", "",
      "## 6. Arrears and recovery",
      f"- A1. A loan is in default from {DEFAULT_DPD} days past due and written off from {WRITE_OFF_DPD}.", "",
      "## 7. Approvals and exceptions",
      "- X1. A decision inside sections 3 and 4 is automatic.",
      "- X2. A loan outside them needs a written exception: reason, named approver, date. The register is reported monthly.", "",
      "## 8. Monitoring (triggers go to the head of credit)",
      "- M1. 90+ days past due above 10% for a product and disbursement month.",
      "- M2. One employer above 5% of open salary-advance principal.",
      "- M3. Exceptions above 2% of loans approved in a month.", "",
      "## 9. Review", f"Version {VERSION}. Reviewed every 12 months and when a trigger fires. Owner: head of credit."]
open("policy/CREDIT_POLICY.md", "w").write("\n".join(L) + "\n")
print(f"wrote policy/CREDIT_POLICY.md: {len(L)} lines, {sum(len(x.split()) for x in L)} words")
print("\n".join(L[:16]))
python3 policy/render.py
wrote policy/CREDIT_POLICY.md: 54 lines, 568 words
# Owoleaf credit policy, version 0.1 draft

Status: DRAFT for the head of credit. Every figure is ILLUSTRATIVE (the lab's own rules).

## 1. Purpose and appetite
Owoleaf lends only to its own wallet customers: individuals (SAL, PL, BNPL) and merchants (SME).
It does not lend to a customer with no wallet history, and it does not lend more than a customer's wallet inflows support.

## 2. Products

| Product | Borrower | Amount | Instalments | Rate per period | Fee | Late fee | Bureau cut-off |
|---|---|---|---|---|---|---|---|
| SAL | individual | ₦10,000 to ₦150,000 | 1 | 5.00% | 1.00% | ₦500 | 580 |
| PL | individual | ₦50,000 to ₦1,000,000 | 3, 6, 9, 12 | 4.50% | 1.00% | ₦1,000 | 620 |
| BNPL | individual | ₦20,000 to ₦300,000 | 4 | 0.00% | 0.00% | ₦500 | 560 |
| SME | merchant | ₦200,000 to ₦5,000,000 | 3, 6 | 3.50% | 1.50% | ₦2,000 | 600 |

The file has nine sections and about 570 words. Open policy/CREDIT_POLICY.md and read it as Nkiruka would: pick any clause and ask where its evidence lives.

4. Does the policy reproduce the engine? Save this as policy/replay.py. Part A runs the policy on every application with the engine’s inflow. Part B runs it with the policy’s own.

"""Does the policy reproduce the decisions Owoleaf made? Run with a folder name: data or data1."""
import collections
import sys
from rules import applications, connect, decide

folder = sys.argv[1] if len(sys.argv) > 1 else "data1"
apps = applications(connect(folder))
print(f"{len(apps)} applications in {folder}\n")


def policy_says(a, key):
    return decide(a["product"], a["instalments"], a["requested"], a["hit"], a["score"],
                  a["delinquent"], a["enquiries"], a[key])


# A. The policy with the engine's inflow figure. A withdrawal was an approval the customer did not take up.
same = 0
for a in apps:
    d, reason, amount = policy_says(a, "monthly_engine")
    if a["decision"] == "withdrawn":
        same += d == "approved"
    elif a["decision"] == "approved":
        same += d == "approved" and amount == a["approved"]
    else:
        same += d == "declined" and reason == a["reason"]
print("A. policy with the engine's inflow (all inflows, to the cut-off)")
print(f"   {same} of {len(apps)} decisions reproduced exactly (decision, reason and amount)\n")

# B. The policy with its own inflow: the 90 days before the application.
print("B. policy with its own inflow (the 90 days before the application)")
seen = collections.Counter()
for a in apps:
    d, reason, amount = policy_says(a, "monthly_policy")
    if a["decision"] == "approved":
        if d == "declined":
            seen["Owoleaf approved; the policy declines: " + reason] += 1
        elif amount < a["approved"]:
            seen["Owoleaf approved; the policy allows less (over its limit)"] += 1
        else:
            seen["Owoleaf approved; the policy allows it"] += 1
    elif a["decision"] == "declined":
        seen["Owoleaf declined; the policy would approve" if d == "approved" else "Owoleaf declined; the policy declines too"] += 1
for k in sorted(seen):
    print(f"   {seen[k]:>5}  {k}")
python3 policy/replay.py data1
8386 applications in data1

A. policy with the engine's inflow (all inflows, to the cut-off)
   8386 of 8386 decisions reproduced exactly (decision, reason and amount)

B. policy with its own inflow (the 90 days before the application)
    3185  Owoleaf approved; the policy allows it
     203  Owoleaf approved; the policy allows less (over its limit)
     138  Owoleaf approved; the policy declines: amount_below_product_minimum
     119  Owoleaf approved; the policy declines: insufficient_income_evidence
    3369  Owoleaf declined; the policy declines too
    1152  Owoleaf declined; the policy would approve

Part A is the weakest possible test, and it passes: all 8,386 decisions, reasons and amounts. The policy copies the engine. Part B changes one definition. Of the 3,645 approvals, 3,185 are allowed, 203 are over the limit, 138 fall below the product minimum once the cap is recomputed and 119 fail the income rule: 460 in all. The policy would also approve 1,152 applications that Owoleaf declined. The two sums disagree in both directions.

5. Test every loan against every clause. Save this as policy/testbook.py. It tests each clause on its own, so a loan that breaks two shows both. It writes the exceptions list and prints the clauses that have no evidence.

"""Test every approved loan against every clause of the policy. Run: python3 policy/testbook.py data1"""
import collections
import csv
import datetime as dt
import sys
from rules import (PRODUCTS, MAX_ENQUIRIES_90D, MAX_DELINQUENT_12M, MIN_MONTHLY_INFLOW, THIN_FILE_MAX,
                   MIN_WALLET_AGE_DAYS, DEFAULT_DPD, WRITE_OFF_DPD, LATE_FEE_AFTER_DAYS, NAIRA,
                   applications, cap_kobo, connect, naira)

folder = sys.argv[1] if len(sys.argv) > 1 else "data1"
db = connect(folder)
apps = {a["id"]: a for a in applications(db)}

loans = db.execute("""SELECT id, application_id, product, principal_kobo, fee_kobo, rate_bps_per_period, instalments,
                      status, days_past_due, outstanding_principal_kobo FROM loans ORDER BY id""").fetchall()

# Each test returns True when the loan keeps the clause. Tests read only what was known at the application,
# except T3 and A1, which read the loan's history.
tests = {}


def clause(cid, area, text):
    def wrap(fn):
        tests[cid] = (area, text, fn)
        return fn
    return wrap


@clause("E1", "Eligibility", f"Wallet at least {MIN_WALLET_AGE_DAYS} days old at application")
def _(l, a): return a["age_days"] >= MIN_WALLET_AGE_DAYS
@clause("E2", "Eligibility", "Individuals borrow SAL, PL and BNPL; merchants borrow SME")
def _(l, a): return a["kind"] == PRODUCTS[l["product"]]["kind"]
@clause("E3", "Eligibility", "A KYC tier 1 customer is not lent a personal loan")
def _(l, a): return not (l["product"] == "PL" and a["tier"] == 1)
@clause("C1", "Credit", "Bureau score at or above the product's cut-off (when the bureau has a file)")
def _(l, a): return (not a["hit"]) or a["score"] >= PRODUCTS[l["product"]]["cutoff"]
@clause("C2", "Credit", f"No more than {MAX_ENQUIRIES_90D} bureau enquiries in 90 days")
def _(l, a): return a["enquiries"] <= MAX_ENQUIRIES_90D
@clause("C3", "Credit", f"No more than {MAX_DELINQUENT_12M} delinquency in 12 months (when the bureau has a file)")
def _(l, a): return (not a["hit"]) or a["delinquent"] <= MAX_DELINQUENT_12M
@clause("I1", "Income", f"Monthly wallet inflow of at least {naira(MIN_MONTHLY_INFLOW)}, 90 days before applying (not BNPL)")
def _(l, a): return l["product"] == "BNPL" or a["monthly_policy"] >= MIN_MONTHLY_INFLOW
@clause("L1", "Limits", "Principal within the product's minimum and maximum")
def _(l, a):
    p = PRODUCTS[l["product"]]
    return p["lo"] * NAIRA <= l["principal_kobo"] <= p["hi"] * NAIRA
@clause("L2", "Limits", "Principal within the inflow cap (1 x monthly inflow, or 2/3 per instalment for PL and SME)")
def _(l, a): return l["principal_kobo"] <= cap_kobo(l["product"], l["instalments"], a["monthly_policy"])
@clause("L3", "Limits", f"A thin file borrows no more than {naira(THIN_FILE_MAX)}")
def _(l, a): return a["hit"] or l["principal_kobo"] <= THIN_FILE_MAX
@clause("T1", "Terms", "Number of instalments is one the product offers")
def _(l, a): return l["instalments"] in PRODUCTS[l["product"]]["tenors"]
@clause("T2", "Terms", "Rate and fee are the product's, and the fee is taken from the principal")
def _(l, a):
    p = PRODUCTS[l["product"]]
    return l["rate_bps_per_period"] == p["rate"] and l["fee_kobo"] == l["principal_kobo"] * p["fee"] // 10_000
@clause("A1", "Arrears", f"Status follows days past due: default from {DEFAULT_DPD}, written off from {WRITE_OFF_DPD}")
def _(l, a):
    dpd, status = l["days_past_due"], l["status"]
    if l["outstanding_principal_kobo"] == 0:
        return status == "closed"
    want = "written_off" if dpd >= WRITE_OFF_DPD else "default" if dpd >= DEFAULT_DPD else "arrears" if dpd > 0 else "current"
    return status == want

# T3 is tested on repayments, not on loans: a full payment more than 3 days late carries the product's late fee, once.
late_rows = db.execute("""SELECT r.loan_id, l.product, r.amount_kobo, s.total_kobo, r.late_fee_kobo,
                                 julianday(r.paid_at) - julianday(s.due_date)
                          FROM repayments r JOIN schedule s ON s.loan_id = r.loan_id AND s.instalment = r.instalment
                          JOIN loans l ON l.id = r.loan_id""").fetchall()
t3_bad = set()
t3_rows = 0
for loan_id, product, paid, due, fee, days in late_rows:
    full = paid >= due
    if not full:
        continue                                       # a part payment carries no late fee
    t3_rows += 1
    want = PRODUCTS[product]["late"] * NAIRA if days > LATE_FEE_AFTER_DAYS else 0
    if fee != want:
        t3_bad.add(loan_id)
tests["T3"] = ("Terms", f"A full payment more than {LATE_FEE_AFTER_DAYS} days late carries the product's late fee, and no other does", None)

failed = collections.defaultdict(set)
for row in loans:
    l = dict(zip(("id", "application_id", "product", "principal_kobo", "fee_kobo", "rate_bps_per_period",
                  "instalments", "status", "days_past_due", "outstanding_principal_kobo"), row))
    a = apps[l["application_id"]]
    for cid, (area, text, fn) in tests.items():
        if fn and not fn(l, a):
            failed[cid].add(l["id"])
failed["T3"] = t3_bad

print(f"{len(loans)} approved loans in {folder}; {t3_rows} full payments tested for T3\n")
print(f"{'clause':<7}{'area':<13}{'fail':>6}  {'result':<9} text")
for cid in ("E1 E2 E3 C1 C2 C3 I1 L1 L2 L3 T1 T2 T3 A1".split()):
    area, text, _ = tests[cid]
    n = len(failed[cid])
    print(f"{cid:<7}{area:<13}{n:>6}  {'PASS' if n == 0 else 'EXCEPTION':<9} {text}")

every = set().union(*failed.values())
print(f"\nloans with at least one exception: {len(every)} of {len(loans)} ({len(every) / len(loans):.1%})")
by_loan = collections.defaultdict(list)
for cid, ids in failed.items():
    for i in ids:
        by_loan[i].append(cid)
print("clause sets:", dict(sorted(collections.Counter(",".join(sorted(v)) for v in by_loan.values()).items())))

prod = {r[0]: r for r in loans}
count, total, kobo = collections.Counter(), collections.Counter(), collections.Counter()
for r in loans:
    total[r[2]] += 1
for i in every:
    count[prod[i][2]] += 1
    kobo[prod[i][2]] += prod[i][3]
print("\nexceptions by product")
for code in PRODUCTS:
    print(f"   {code:<5}{count[code]:>5} of {total[code]:>5} loans  {count[code] / total[code]:>6.1%}   principal {naira(kobo[code])}")

over = sum(prod[i][3] - cap_kobo(prod[i][2], prod[i][6], apps[prod[i][1]]["monthly_policy"]) for i in every)
print(f"   all  {naira(sum(prod[i][3] for i in every))} of {naira(sum(r[3] for r in loans))} lent; "
      f"{naira(over)} of it above the cap")

print("\nexceptions by the wallet's age at application")
bands = [("under 30 days", 0, 30), ("30 to 89 days", 30, 90), ("90 days or more", 90, 10_000)]
for label, lo, hi in bands:
    n = [r[0] for r in loans if lo <= apps[r[1]]["age_days"] < hi]
    e = [i for i in n if i in every]
    print(f"   {label:<16}{len(e):>5} of {len(n):>5} loans  {len(e) / len(n):>6.1%}")

print("\nhow the exceptions behaved (default or written off at the cut-off)")
print(f"   {'':<5}{'exception loans':>17}{'bad':>6}{'bad rate':>10}   {'conforming loans':>17}{'bad':>6}{'bad rate':>10}")
for code in PRODUCTS:
    ex = [r for r in loans if r[2] == code and r[0] in every]
    ok = [r for r in loans if r[2] == code and r[0] not in every]
    bad = lambda rs: sum(r[7] in ("default", "written_off") for r in rs)
    print(f"   {code:<5}{len(ex):>17}{bad(ex):>6}{bad(ex) / max(1, len(ex)):>10.1%}   {len(ok):>17}{bad(ok):>6}{bad(ok) / max(1, len(ok)):>10.1%}")

with open(f"policy/exceptions_{folder}.csv", "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["loan_id", "product", "principal_kobo", "clauses", "approver", "reason_recorded"])
    for i in sorted(every):
        w.writerow([i, prod[i][2], prod[i][3], " ".join(sorted(by_loan[i])), "", ""])
print(f"\nwrote policy/exceptions_{folder}.csv: {len(every)} rows, approver and reason_recorded empty")

# Clauses the book cannot test: the evidence would live in a table that does not exist.
print("\nclauses with no evidence in the book (GAP)")
have = {r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type = 'table'")}
for cid, table, text in (("X2", "exception_register", "a written exception: reason, named approver, date"),
                         ("G1", "consents", "consent recorded before each bureau check"),
                         ("G2", "offers", "the offer, with its APR, shown before the customer accepts"),
                         ("G3", "decision_reviews", "a person can review a decline")):
    print(f"   {cid}  needs table {table:<19} {'present' if table in have else 'ABSENT':<8} {text}")
python3 policy/testbook.py data1
head -4 policy/exceptions_data1.csv
3645 approved loans in data1; 8369 full payments tested for T3

clause area           fail  result    text
E1     Eligibility       0  PASS      Wallet at least 7 days old at application
E2     Eligibility       0  PASS      Individuals borrow SAL, PL and BNPL; merchants borrow SME
E3     Eligibility       0  PASS      A KYC tier 1 customer is not lent a personal loan
C1     Credit            0  PASS      Bureau score at or above the product's cut-off (when the bureau has a file)
C2     Credit            0  PASS      No more than 6 bureau enquiries in 90 days
C3     Credit            0  PASS      No more than 1 delinquency in 12 months (when the bureau has a file)
I1     Income          119  EXCEPTION Monthly wallet inflow of at least ₦5,000.00, 90 days before applying (not BNPL)
L1     Limits            0  PASS      Principal within the product's minimum and maximum
L2     Limits          460  EXCEPTION Principal within the inflow cap (1 x monthly inflow, or 2/3 per instalment for PL and SME)
L3     Limits            0  PASS      A thin file borrows no more than ₦50,000.00
T1     Terms             0  PASS      Number of instalments is one the product offers
T2     Terms             0  PASS      Rate and fee are the product's, and the fee is taken from the principal
T3     Terms             0  PASS      A full payment more than 3 days late carries the product's late fee, and no other does
A1     Arrears           0  PASS      Status follows days past due: default from 90, written off from 180

loans with at least one exception: 460 of 3645 (12.6%)
clause sets: {'I1,L2': 119, 'L2': 341}

exceptions by product
   SAL    272 of  1959 loans   13.9%   principal ₦6,384,000.00
   PL      55 of   451 loans   12.2%   principal ₦11,044,000.00
   BNPL   106 of   766 loans   13.8%   principal ₦4,104,000.00
   SME     27 of   469 loans    5.8%   principal ₦27,581,000.00
   all  ₦49,113,000.00 of ₦611,757,000.00 lent; ₦19,399,000.00 of it above the cap

exceptions by the wallet's age at application
   under 30 days     352 of  1249 loans   28.2%
   30 to 89 days      94 of  1796 loans    5.2%
   90 days or more    14 of   600 loans    2.3%

how the exceptions behaved (default or written off at the cut-off)
          exception loans   bad  bad rate    conforming loans   bad  bad rate
   SAL                272    43     15.8%                1687   238     14.1%
   PL                  55     3      5.5%                 396    11      2.8%
   BNPL               106    12     11.3%                 660    54      8.2%
   SME                 27     1      3.7%                 442     6      1.4%

wrote policy/exceptions_data1.csv: 460 rows, approver and reason_recorded empty

clauses with no evidence in the book (GAP)
   X2  needs table exception_register  ABSENT   a written exception: reason, named approver, date
   G1  needs table consents            ABSENT   consent recorded before each bureau check
   G2  needs table offers              ABSENT   the offer, with its APR, shown before the customer accepts
   G3  needs table decision_reviews    ABSENT   a person can review a decline

The CSV starts:

loan_id,product,principal_kobo,clauses,approver,reason_recorded
L000003,PL,12600000,L2,,
L000020,SAL,2000000,L2,,
L000021,SAL,1000000,I1 L2,,

Fourteen clauses are tested. Twelve pass (E1 to E3, C1 to C3, L1, L3, T1 to T3 and A1) and two have exceptions (I1 and L2). 341 loans break L2 alone and 119 break I1 and L2. The approver column is empty for every loan, because the book holds no register. Do not fill it in. The four GAP lines are clauses the book cannot test.

6. Run the triggers. Save this as policy/monitor.py. It reads the exceptions file from step 5.

"""Check the policy's monitoring triggers on the book. Run: python3 policy/monitor.py data1
Needs policy/exceptions_<folder>.csv from testbook.py."""
import collections
import csv
import datetime as dt
import sys
from rules import connect, naira

folder = sys.argv[1] if len(sys.argv) > 1 else "data1"
db = connect(folder)

# ILLUSTRATIVE ceilings, written into the policy before the book was tested.
MAX_BAD_RATE = 0.10            # M1: loans of one product and disbursement month that are 90+ days past due at the cut-off
MAX_EMPLOYER_SHARE = 0.05      # M2: one employer's share of open salary-advance principal on a stated day
MAX_EXCEPTION_RATE = 0.02      # M3: loans approved outside the policy, as a share of loans approved in the month
EXPOSURE_DAY = "2026-06-27"

loans = db.execute("""SELECT id, product, substr(disbursed_at, 1, 7), status, principal_kobo, disbursed_at, maturity_date
                      FROM loans""").fetchall()

MIN_CELL = 30                  # a product-month with fewer loans is too small to read
print(f"M1. 90+ days past due, by product and disbursement month (ceiling {MAX_BAD_RATE:.0%}, cells under {MIN_CELL} loans blank); breaches marked *")
cells = collections.defaultdict(lambda: [0, 0])
for _, product, month, status, *_ in loans:
    cells[(product, month)][0] += 1
    cells[(product, month)][1] += status in ("default", "written_off")
months = sorted({m for _, m in cells if m <= "2026-06"})
print(f"   {'':<6}" + "".join(f"{m[5:]:>10}" for m in months))
breaches = 0
read = 0
for product in ("SAL", "BNPL"):      # PL and SME loans are still running: their 90+ rates are unfinished
    line = f"   {product:<6}"
    for m in months:
        n, bad = cells.get((product, m), (0, 0))
        if n < MIN_CELL:
            line += f"{'':>10}"
            continue
        read += 1
        breaches += bad / n > MAX_BAD_RATE
        line += f"{bad / n:>9.1%}{'*' if bad / n > MAX_BAD_RATE else ' '}"
    print(line)
print(f"   {breaches} of {read} product-months read breach the ceiling")

print(f"\nM2. one employer's share of open salary-advance principal on {EXPOSURE_DAY} (ceiling {MAX_EMPLOYER_SHARE:.0%})")
rows = db.execute("""SELECT e.employer_id, SUM(l.principal_kobo) FROM loans l JOIN loan_employers e ON e.loan_id = l.id
                     WHERE l.disbursed_at <= ? AND l.maturity_date > ? GROUP BY 1 ORDER BY 2 DESC""",
                  (EXPOSURE_DAY, EXPOSURE_DAY)).fetchall()
total = sum(k for _, k in rows)
print(f"   open principal {naira(total)} across {len(rows)} employers")
for emp, k in rows[:4]:
    print(f"   {emp}  {naira(k):>16}  {k / total:>6.1%}{'  *' if k / total > MAX_EMPLOYER_SHARE else ''}")

print(f"\nM3. loans approved outside the policy, by disbursement month (ceiling {MAX_EXCEPTION_RATE:.0%})")
ex = {r["loan_id"] for r in csv.DictReader(open(f"policy/exceptions_{folder}.csv"))}
per = collections.defaultdict(lambda: [0, 0])
for lid, _, month, *_ in loans:
    per[month][0] += 1
    per[month][1] += lid in ex
for m in sorted(per):
    n, e = per[m]
    print(f"   {m}  {n:>5} loans  {e:>4} exceptions  {e / n:>6.1%}{'  *' if e / n > MAX_EXCEPTION_RATE else ''}")
python3 policy/monitor.py data1
M1. 90+ days past due, by product and disbursement month (ceiling 10%, cells under 30 loans blank); breaches marked *
                 01        02        03        04        05        06
   SAL                 12.3%*    16.8%*    16.1%*    13.4%*    14.2%*
   BNPL                          11.1%*     9.0%     11.0%*     6.3% 
   7 of 9 product-months read breach the ceiling

M2. one employer's share of open salary-advance principal on 2026-06-27 (ceiling 5%)
   open principal ₦21,567,000.00 across 40 employers
   EMP07     ₦1,647,000.00    7.6%  *
   EMP24       ₦788,000.00    3.7%
   EMP32       ₦721,000.00    3.3%
   EMP33       ₦719,000.00    3.3%

M3. loans approved outside the policy, by disbursement month (ceiling 2%)
   2026-01     35 loans    23 exceptions   65.7%  *
   2026-02    138 loans    49 exceptions   35.5%  *
   2026-03    365 loans    85 exceptions   23.3%  *
   2026-04    628 loans   111 exceptions   17.7%  *
   2026-05   1008 loans   119 exceptions   11.8%  *
   2026-06   1471 loans    73 exceptions    5.0%  *

Seven of the nine readable product-months for SAL and BNPL breach the 10% ceiling. EMP07’s 7.6% matches the employer lending chapter (₦1,647,000 of ₦21,567,000). All six months breach the 2% exception ceiling, with the share falling from 65.7% in January to 5.0% in June as wallets age.

7. Test the proposed clauses as a what-if. Save this as policy/whatif.py.

"""What would two proposed clauses do to the book? Run: python3 policy/whatif.py data1
Neither clause is in force: they are tested as a what-if, and nothing here counts as an exception."""
import sys
from rules import applications, connect, naira

folder = sys.argv[1] if len(sys.argv) > 1 else "data1"
db = connect(folder)
apps = {a["id"]: a for a in applications(db)}
signals = dict(db.execute("SELECT application_id, name_match FROM applicant_signals"))
loans = db.execute("SELECT id, application_id, product, principal_kobo, status FROM loans ORDER BY id").fetchall()
bad = lambda s: s in ("default", "written_off")

# P1. The identity check's name must match (the lending-fraud chapter's signal).
mismatch = [l for l in loans if signals[l[1]] == 0]
print("P1. identity name check must match")
print(f"   {len(mismatch)} of {len(loans)} loans had a mismatch; {sum(bad(l[4]) for l in mismatch)} went bad "
      f"({sum(bad(l[4]) for l in mismatch) / len(mismatch):.1%}), against "
      f"{sum(bad(l[4]) for l in loans if signals[l[1]] != 0) / (len(loans) - len(mismatch)):.1%} of the rest")

# P2. Affordability limit from the decisions chapter: a share of monthly inflow, by points band.
# Bands by points: A 100 or more (40%), B 80-90 (35%), C 60-70 (30%), D under 60 (25%).
BURDEN = {"SAL": (21, 20), "BNPL": (30, 56)}           # naira due a month per naira lent, as a fraction: 1.05 and 30/14/4


def points(a):
    p = (60 if a["score"] >= 740 else 40 if a["score"] >= 680 else 20 if a["score"] >= 620 else 0) if a["hit"] else 20
    p += 20 if a["delinquent"] == 0 else 0
    p += 20 if a["enquiries"] <= 2 else 10 if a["enquiries"] <= 4 else 0
    p += 20 if a["history_years"] >= 5 else 10 if a["history_years"] >= 2 else 0
    return p


years = dict(db.execute("SELECT a.id, b.history_years FROM applications a JOIN bureau_reports b ON b.id = a.bureau_report_id"))
pct_of = lambda p: 40 if p >= 100 else 35 if p >= 80 else 30 if p >= 60 else 25     # band A to D, in per cent
print("\nP2. affordability limit (share of monthly inflow by points band), salary advances and BNPL")
print(f"   {'':<6}{'loans':>6}{'over limit':>11}{'share':>8}{'bad over':>10}{'bad within':>12}   {'principal over the limit':>26}")
for code in ("SAL", "BNPL"):
    over, within, excess = [], [], 0
    for l in loans:
        if l[2] != code:
            continue
        a = dict(apps[l[1]], history_years=years[l[1]])
        pct = pct_of(points(a))
        num, den = BURDEN[code]
        limit = a["monthly_policy"] * pct * den // (100 * num) // 100_000 * 100_000
        (over if l[3] > limit else within).append(l)
        excess += max(0, l[3] - limit)
    n = len(over) + len(within)
    rate = lambda rs: sum(bad(r[4]) for r in rs) / len(rs)
    print(f"   {code:<6}{n:>6}{len(over):>11}{len(over) / n:>8.1%}{rate(over):>10.1%}{rate(within):>12.1%}   {naira(excess):>26}")
python3 policy/whatif.py data1
P1. identity name check must match
   158 of 3645 loans had a mismatch; 61 went bad (38.6%), against 8.8% of the rest

P2. affordability limit (share of monthly inflow by points band), salary advances and BNPL
          loans over limit   share  bad over  bad within     principal over the limit
   SAL     1959       1266   64.6%     16.2%       11.0%               ₦15,254,000.00
   BNPL     766        236   30.8%     10.6%        7.7%                ₦4,174,000.00

The SAL and BNPL rows match the decisions chapter’s step 5: 1,266 and 236 loans over the limit, bad rates 16.2% and 11.0%, 10.6% and 7.7%. Neither clause is in force, so neither line is an exception: each is the price of adopting the clause.

8. Run it on the small book. The scripts take the folder as an argument.

python3 policy/testbook.py data | sed -n 19,20p
loans with at least one exception: 51 of 372 (13.7%)
clause sets: {'I1,L2': 16, 'L2': 35}

At scale 0.1 the rate is 13.7%, close to scale 1’s 12.6%, so the finding does not depend on the sample size. The 51 loans are few enough to read one by one.

Make the policy agree with the engine by changing the definition and nothing else. Copy the testbook with the engine’s inflow in place of the policy’s, run it, then run the real one again so exceptions_data1.csv is restored (the copy overwrites it with an empty list).

sed 's/monthly_policy/monthly_engine/g' policy/testbook.py > policy/tb_break.py
python3 policy/tb_break.py data1 | grep "at least one"
rm policy/tb_break.py
python3 policy/testbook.py data1 | grep "at least one"

Expected:

loans with at least one exception: 0 of 3645 (0.0%)
loans with at least one exception: 460 of 3645 (12.6%)

Zero exceptions is the clean result, and it means nothing a funder could use: the clause now reads money that the lender could not see when it decided. A passing test is only as good as the definitions it reads. Ask what else in the lab’s policy depends on a figure computed after the decision date, and which clause you would test next.

ARTEFACT Write a credit policy exception request ~40 MIN
YOU PRODUCEA credit policy exception request and exception log entry

Template

# Exception request <number>: <clause or trigger id> <short name>
Requested by <analyst>, credit. Approver <named role and person>, within <the delegated authority that covers it>.

## 1. The exception
- Clause or trigger: <id and wording from the policy>
- Scope: <loans, product, employer or customers it covers>, from <date> to <date>
- Size: <number of loans>, <kobo> of principal (₦<amount>), <kobo> above the limit

## 2. Rationale
Why going outside the clause is better than keeping it, and what the alternative costs.

## 3. Risk
The main way it could lose money or breach appetite, with one figure from the book.
What watches it: <trigger id, ceiling, owner>.

## 4. Decision and log entry
| Request | Clause | Scope | Approver | Decision | Date | Review date | Reason recorded |
Decision needed: <what, from whom, by when>. Out of scope: <what this does not cover>.
Already lent and unapproved: listed, left blank, not back-filled.

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

A credit analyst on Ladun’s team writes each exception request at Owoleaf, and Ladun, head of credit, signs it. Her limit is an assumption, because the policy only says approval is a named role. This is 21 November 2026, from the lab’s testbook.py and monitor.py figures. The start date, end date and review date are assumptions, to be set by the engine team.

Exception. Clause L2, the cap on amount. Scope: new loans the engine approves under its own definition of inflow, from today until the engine uses the policy’s 90-day definition, assumed 29 January 2027. Size today: 460 of 3,645 loans (12.6%) are outside L2 and 119 of them also break I1. They hold ₦49,113,000 of ₦611,757,000 lent, with ₦19,399,000 above the cap.

Rationale. Pausing lending until the release would stop revenue and strand customers. The cause is known: 28.2% of loans to wallets under 30 days old are exceptions, against 2.3% from 90 days.

Risk. Exceptions went bad slightly more often: 15.8% against 14.1% for salary advances, 11.3% against 8.2% for BNPL, on counts of tens of loans. M3’s ceiling is 2%; June read 73 of 1,471, or 5.0%.

Log entry. Request 1, clause L2, Ladun, review date 18 December 2026 (assumed). The 460 loans already lent have no approver in the book, because the X2 register is absent. They stay blank.

Could be wrong. Bad rates are early; PL and SME loans are still running. A June exception share above 5.0% in November’s disbursements would show it.

Decision. Ladun is asked to approve continued lending to the end date and to open the register. Back-approving the 460 is out of scope.

Now you

It is a month later and you are the credit analyst at Owoleaf, writing for Ladun. The sales lead asks to keep approving salary advances to EMP07’s staff while the employer limit is built. M2 reads ₦1,647,000 of ₦21,567,000 open principal on EMP07, 7.6% against a 5% ceiling, with EMP24 next at 3.7%. Assume that position is unchanged. Run monitor.py on data1 for the M2 table, and testbook.py for the GAP lines, which show the book has no exception register. M2 is a trigger and the policy has no employer-limit clause, so your request is to keep lending while the trigger is breached. Choose an end date and a review date, and say what authority Ladun needs for it, since the policy only says approval is a named role. Ladun reads your request to decide whether to allow lending above the ceiling, and until when.

Self-check

DECIDE

Nkiruka's re-performance found 460 loans above the policy's cap, with no approver on record. Ladun has a week before the funder's credit committee. The cause is two definitions of monthly inflow, and the engine change needs a release that cannot ship before the meeting. The policy in front of the funder is draft 0.1.

READING
  1. DOC
    Principles for the Management of Credit Risk (Basel Committee, revised 2025) Basel Committee on Banking Supervision, 2025

    The current Basel text on what a sound credit-granting process and a board-approved credit policy cover. Read the principles on the credit risk environment and credit-granting; skip the supervisory annexes. Check the wording before you quote it.

  2. DOC
    Principles for the Management of Credit Risk (Basel Committee, 2000 version) Basel Committee on Banking Supervision, 2000

    The original 2000 paper, marked superseded on the BIS page, still useful for the plain statement of why a bank needs written credit-granting criteria. Read it for the argument and use the 2025 text for the rule.

  3. DOC
    CBN prudential guidelines for finance companies (August 2019 exposure draft) Central Bank of Nigeria, 2019

    The CBN's document quoted in search results as requiring a board-approved credit policy for finance companies. Find the credit-policy provision. Search results describe this as an exposure draft, so check whether a final version was issued. Read: The provision on credit policy.

  4. DOC
    CBN prudential guidelines for microfinance banks (August 2019 exposure draft) Central Bank of Nigeria, 2019

    The microfinance bank counterpart. Read the credit policy provision and compare its wording with the finance company text; skip the capital-adequacy tables on a first read. Read: The provision on credit policy.

  5. DOC
    FCCPC: Digital, Electronic, Online or Non-Traditional Consumer Lending Regulations 2025

    The consumer-lending Regulations as the FCCPC hosts them. Read the registration and conduct sections for what a digital lender must show; this chapter did not find a credit-policy requirement in the search results, so check the text yourself.

  6. DOC
    FCCPC: DEON Consumer Lending Guidelines 2025

    The guidance that sits beside the Regulations. Read it for what a lender must disclose and how it must treat borrowers, which a credit policy has to be consistent with; skip the forms.

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: Funding a loan book: equity, debt, warehouse facilities, securitisation →