BEGINNERPROJECTCHAPTER 07

Project: an amortisation engine and a loan ledger

Write the engine that produces every instalment to the kobo, post the whole loan book into a double-entry ledger, and prove that the two agree with the servicing records

120 MINLENDING AND CREDITUPDATED 2026-11-14

This chapter is a project. You write two programs and run them against the whole loan book from the finance lab: 372 loans, 1,127 instalments and 891 repayments. The first is an amortisation engine, which turns a loan’s terms into a dated schedule of instalments. The second posts the book into a small double-entry ledger and proves the ledger agrees with the loan records. Everything is standard-library Python. The numbers in the lab are illustrative: they are Owoleaf’s fictional prices, not any real lender’s and not a rule of any regulator.

What you are building

The engine takes a principal, a rate per period, a number of instalments, a disbursement date and a period length. It returns a list of instalments, each with a due date, a principal part, an interest part and a total. The test is strict: for every loan in schedule.csv, the engine must produce the same rows, to the kobo. Any difference is a bug in your engine, because loans.py generated that file from the same contract terms.

The ledger takes three kinds of event from the loan tables (a disbursement, a repayment and a write-off) and records each as a journal entry: a set of lines, each debiting or crediting one account, where the debits equal the credits. Then you prove four things. Every entry balances. The loans-receivable account agrees with each loan’s outstanding principal. The income accounts agree with what the loan records say was earned. The cash account agrees with the money that went out and came in.

The ledger is separate from the wallet ledger in the lab’s entries table. This one belongs to the lending book alone and lives in its own SQLite file. Double-entry itself is taught in the Payments course, in double-entry bookkeeping for engineers and its project, a double-entry ledger for a wallet; here you only need the rule that every entry’s debits equal its credits.

Integers, basis points and exact fractions

Money is integer kobo: ₦310,000 is 31,000,000. A float cannot hold 0.1 exactly, and an instalment calculated in floats can land a kobo away from the true value on one loan and a kobo the other way on the next. Integers add and compare exactly, so a total that should match either does or does not.

Rates are basis points (bps): one hundredth of a percent. The personal loan’s 4.5% a month is 450 bps. The instalment formula needs a division and a power, so the engine does that arithmetic with Python’s Fraction, which keeps the exact ratio of two integers, and rounds once, to the kobo, at the end of each step. No float touches the money.

The reducing-balance instalment is the standard annuity formula, where P is the principal, r the rate per period as a fraction, and n the number of instalments:

instalment = P × r ÷ (1 − (1 + r)^−n)

Each period the interest is balance × r, the principal part is the instalment minus the interest, and the balance falls by the principal part. The last instalment’s principal part is whatever balance is left, so the principal repaid adds up to the loan exactly and the last total absorbs the rounding.

The fee is taken from the amount when the loan is paid out: principal × fee_bps ÷ 10,000, rounded down. For L000043 (₦310,000, fee 100 bps) that is ₦3,100.00, so the customer receives ₦306,900.00 and owes interest on ₦310,000.

Three ways to charge interest

The engine supports three methods, and the comparison shows why a customer must be told which one a lender uses.

  • Reducing balance charges the rate on what is still owed. As the customer repays principal, the interest falls.
  • Flat charges the rate on the original principal every period, however much has been repaid. The customer pays interest on money they have already returned.
  • Bullet charges interest each period on the full principal and returns the principal in the last instalment. A one-period bullet is the salary advance: one repayment, principal and interest together.

On the same ₦310,000 loan, 6 monthly periods at 450 bps, the lab prints:

Method First instalment Total interest
Reducing balance ₦60,102.30 ₦50,613.80
Flat ₦65,616.66 ₦83,700.00
Bullet ₦13,950.00 ₦83,700.00

The flat total is easy to redo by hand: 31,000,000 kobo × 4.5% × 6 = 8,370,000 kobo. The same quoted “4.5% a month” costs ₦83,700.00 under flat and ₦50,613.80 under reducing balance, a difference of ₦33,086.20 on one loan. Owoleaf’s book uses reducing balance for every loan, and that is the method the check in the lab tests. The other two are there so you can see what a changed word in a contract does to the schedule.

Rounding to the kobo is a rule

Interest on a balance is rarely a whole number of kobo. The engine must choose, and the choice is part of the schedule. Two rules are common. Round half up sends 636,934.5 to 636,935. Round half to even, also called banker’s rounding and what Python’s round does, sends 636,934.5 to 636,934, because 636,934 is even. The two differ only when the fraction is exactly one half, which is rare. The lab shows how rare: with half-even the engine matches all 372 schedules, and with half-up it matches 370.

The two loans that differ are L000020 and L000059. For L000020, instalment 8 has a balance of 14,154,100 kobo, and 14,154,100 × 450 ÷ 10,000 is exactly 636,934.5 kobo. One engine charges ₦6,369.34 of interest, the other ₦6,369.35, and the one-kobo difference flows into every later instalment’s principal until the last absorbs it. This is the afternoon Bola lost. The fix is not to pick the “right” rule in the abstract. The fix is to write the rule down, in code, as part of the product definition, and to test every schedule against it.

A ledger as the book’s proof

A loan has three moments that change the books.

Event Debit Credit
Disbursement Loans receivable: the principal Cash: the net paid out. Fee income: the fee
Repayment Cash: the amount received Loans receivable: the principal part. Interest income: the interest part. Late-fee income: the late fee
Write-off Loss on write-off: the outstanding principal Loans receivable: the outstanding principal

For L000043 the disbursement is a debit of ₦310,000.00 to loans receivable, a credit of ₦306,900.00 to cash and a credit of ₦3,100.00 to fee income. Debits ₦310,000.00 equal credits ₦306,900.00 + ₦3,100.00. Its first repayment, paid on the due date, is ₦60,102.30 in cash: ₦46,152.30 of principal and ₦13,950.00 of interest. After it, loans receivable for this loan is ₦310,000.00 − ₦46,152.30 = ₦263,847.70.

The posting function in the lab refuses an entry that does not balance. That is the guard you want: a posting bug fails on the day it is written, with the loan and the event named, instead of surfacing in a trial balance a month later.

Three simplifications are deliberate and you should know them. Interest income is recognised when it is paid (a cash basis), not as it accrues. The fee is recognised in full at disbursement. And a write-off is dated at the cut-off, 2026-10-28, instead of the day the loan crossed 180 days past due. Real books treat these differently, and module 3 returns to them in the chapters on expected loss and on provisioning under IFRS 9 (the international accounting standard that sets how a lender estimates and books expected credit losses). Nothing in this project depends on getting them wrong or right; the proofs only need every posting to be traceable to one row in the loan tables.

The write-off and the ₦8,502,584.79

The book’s outstanding_principal_kobo column sums to ₦8,502,584.79 across all 372 loans. The ledger’s loans receivable is ₦8,164,579.00. They do not match, and the gap is exact: ₦338,005.79, the outstanding principal of the two loans with status written_off. The book leaves a written-off loan’s principal in its outstanding column, as a record of what was lost. The ledger removes it from receivable and books it as a loss. So the correct proof is not “receivable equals the book” but “receivable plus the principal written off equals the book”, and per loan, “receivable equals outstanding principal, or zero for a written-off loan”. Both hold with a difference of zero. If you posted no write-offs, receivable would equal ₦8,502,584.79 exactly, and the ledger would overstate what Owoleaf can expect to collect by ₦338,005.79.

The cash account is negative, ₦−1,701,235.91, which looks wrong and is not. This ledger holds only the loan book. The money Owoleaf lent came from somewhere (equity, a bank, customers’ wallets), and that funding is not posted here. Cash is the net movement the book caused: ₦62,346,580.00 paid out to borrowers and ₦60,645,344.09 received back, a net of −₦1,701,235.91. Funding a loan book is the subject of module 4.

What the checks prove, and what they do not

The checks catch a missing posting, a doubled posting, a wrong split between principal and interest, and a schedule that drifts from its contract. They do not catch a loan that should never have been made, an interest rate that was wrong in the contract and the engine alike, or a customer who was charged a fee they were never told about. A ledger that balances is internally consistent. Whether it is right is a separate question, and it is answered by comparing it to something outside itself: the bank statement, the contract and the customer’s own record. The lab’s checks compare the ledger to the loan tables, which loans.py generated; in a real company those tables are the thing you would reconcile to, and a second source such as the partner bank’s statement is the thing you would reconcile with.

Lab

LAB Build the engine, match schedule.csv, post the book and prove it balances ~75 MIN
YOU NEEDPython 3.9 or later (standard library only)The finance lab data from labs/finance (step 1 makes it)About 100 MB of disk for the lab data

You work in labs/finance. You create four small files there: engine.py, verify.py, post.py and prove.py. The loan tables are generated at seed 42 and scale 0.1, so your numbers match the ones below. The files are new files in the lab folder; leave them where they are.

1. Check the loan book exists.

cd labs/finance
ls data/loans.csv data/schedule.csv data/repayments.csv 2>/dev/null || (python3 generate.py && python3 loans.py && python3 check.py)
python3 -c "
import csv
print(len(list(csv.DictReader(open('data/loans.csv')))), 'loans,', len(list(csv.DictReader(open('data/schedule.csv')))), 'instalments')"

If the data is already there, ls lists the three files. If not, the three generator commands run first (about 5 seconds, and check.py ends with OK: all invariants hold). Either way the last line is:

372 loans, 1127 instalments

2. Write the engine. Save this as engine.py.

cat > engine.py <<'EOF'
"""An amortisation engine. Money is integer kobo; rates are integer basis points (bps) per period."""
from fractions import Fraction
import datetime as dt


def to_kobo(x, mode="even"):
    """Round an exact Fraction of kobo to a whole kobo. 'even' sends .5 to the even neighbour
    (banker's rounding, what Python's round does); 'up' sends .5 up (what most people expect)."""
    if mode == "even":
        return round(x)
    return int((x + Fraction(1, 2)) // 1)


def fee(principal, fee_bps):
    """The fee taken from the amount at disbursement, rounded down to the kobo."""
    return principal * fee_bps // 10_000


def reducing(principal, bps, n, mode="even"):
    """Equal instalments on the reducing balance. Returns [(instalment, principal, interest)].
    The last instalment's principal is whatever is left, so principal adds up to the loan exactly."""
    rows, balance = [], principal
    if bps == 0:
        each = principal // n
        for i in range(1, n + 1):
            p = each if i < n else balance
            rows.append((i, p, 0))
            balance -= p
        return rows
    r = Fraction(bps, 10_000)
    payment = to_kobo(principal * r / (1 - (1 + r) ** -n), mode)
    for i in range(1, n + 1):
        interest = to_kobo(balance * r, mode)
        p = payment - interest if i < n else balance
        rows.append((i, p, interest))
        balance -= p
    return rows


def flat(principal, bps, n, mode="even"):
    """Flat interest: the rate is charged on the original principal for every period."""
    total_interest = to_kobo(principal * Fraction(bps, 10_000) * n, mode)
    rows, p_left, i_left = [], principal, total_interest
    for i in range(1, n + 1):
        p = principal // n if i < n else p_left
        it = total_interest // n if i < n else i_left
        rows.append((i, p, it))
        p_left -= p
        i_left -= it
    return rows


def bullet(principal, bps, n, mode="even"):
    """Interest on the full principal each period; the principal comes back in the last one."""
    it = to_kobo(principal * Fraction(bps, 10_000), mode)
    return [(i, principal if i == n else 0, it) for i in range(1, n + 1)]


METHODS = {"reducing": reducing, "flat": flat, "bullet": bullet}


def schedule(principal, bps, n, disbursed, period_days, method="reducing", mode="even"):
    """Dated instalments: [(instalment, due_date, principal, interest, total)]."""
    start = dt.date.fromisoformat(disbursed)
    out = []
    for i, p, it in METHODS[method](principal, bps, n, mode):
        due = start + dt.timedelta(days=period_days * i)
        out.append((i, due.isoformat(), p, it, p + it))
    return out
EOF

The engine has three interest methods, one fee function and one schedule function that adds due dates. Money is integer kobo, rates are integer basis points, and to_kobo is the only place a fraction becomes a whole number.

3. Recompute L000043. The loan is ₦310,000 for 6 months at 450 bps, paid out on 2026-06-20.

python3 - <<'EOF'
from engine import schedule, fee
rows = schedule(31_000_000, 450, 6, "2026-06-20", 30)
for i, due, p, it, total in rows:
    print(i, due, f"{p:>10,} {it:>10,} {total:>10,}")
print("fee", f"{fee(31_000_000, 100):,}", "paid out", f"{31_000_000 - fee(31_000_000, 100):,}")
EOF
grep -E "^L000043," data/schedule.csv

Six instalments of 6,010,230 kobo each (₦60,102.30), with interest falling and principal rising, and the fee of 310,000 kobo (₦3,100.00):

1 2026-07-20  4,615,230  1,395,000  6,010,230
2 2026-08-19  4,822,915  1,187,315  6,010,230
3 2026-09-18  5,039,947    970,283  6,010,230
4 2026-10-18  5,266,744    743,486  6,010,230
5 2026-11-17  5,503,748    506,482  6,010,230
6 2026-12-17  5,751,416    258,814  6,010,230
fee 310,000 paid out 30,690,000
L000043,1,2026-07-20,4615230,1395000,6010230
L000043,2,2026-08-19,4822915,1187315,6010230
L000043,3,2026-09-18,5039947,970283,6010230
L000043,4,2026-10-18,5266744,743486,6010230
L000043,5,2026-11-17,5503748,506482,6010230
L000043,6,2026-12-17,5751416,258814,6010230

Redo instalment 1 by hand: 31,000,000 × 0.045 = 1,395,000 interest, and 6,010,230 − 1,395,000 = 4,615,230 principal. The engine and schedule.csv agree on every number.

4. Compare the three methods.

python3 - <<'EOF'
from engine import METHODS
for name, build in METHODS.items():
    rows = build(31_000_000, 450, 6)
    first = rows[0][1] + rows[0][2]
    print(f"{name:<9} first instalment {first:>10,}  total interest {sum(r[2] for r in rows):>10,}")
EOF
reducing  first instalment  6,010,230  total interest  5,061,380
flat      first instalment  6,561,666  total interest  8,370,000
bullet    first instalment  1,395,000  total interest  8,370,000

The same 4.5% a month costs ₦83,700.00 flat and ₦50,613.80 on the reducing balance. Flat and bullet cost the same in total and differ in when the customer pays. The flat first instalment ends in 66 kobo because the last instalment absorbs the remainder of 31,000,000 ÷ 6.

5. Reproduce the whole book. Save this as verify.py.

cat > verify.py <<'EOF'
import csv
from engine import schedule

loans = list(csv.DictReader(open("data/loans.csv")))
book = {}
for r in csv.DictReader(open("data/schedule.csv")):
    book.setdefault(r["loan_id"], []).append(
        (int(r["instalment"]), r["due_date"], int(r["principal_kobo"]),
         int(r["interest_kobo"]), int(r["total_kobo"])))

for mode in ("even", "up"):
    bad = []
    for l in loans:
        mine = schedule(int(l["principal_kobo"]), int(l["rate_bps_per_period"]), int(l["instalments"]),
                        l["disbursed_at"], int(l["period_days"]), "reducing", mode)
        if mine != book[l["id"]]:
            bad.append(l["id"])
    print(f"rounding {mode!r}: {len(loans) - len(bad)} of {len(loans)} schedules match; differ: {bad}")
EOF
python3 verify.py

The engine with half-even rounding reproduces every schedule. The same engine with half-up rounding misses two:

rounding 'even': 372 of 372 schedules match; differ: []
rounding 'up': 370 of 372 schedules match; differ: ['L000020', 'L000059']

If your even line shows fewer than 372, compare the first differing row of the first loan listed with its row in schedule.csv. The usual causes are a float creeping into the maths, rounding the payment up where the engine rounds to even, and a last instalment that does not take the remaining balance.

6. Find the half kobo. This is the interest on L000020’s instalment 8 (balance 14,154,100 kobo at 450 bps).

python3 - <<'EOF'
from fractions import Fraction
from engine import to_kobo
exact = 14_154_100 * Fraction(450, 10_000)
print(exact, float(exact), "even:", to_kobo(exact, "even"), "up:", to_kobo(exact, "up"))
EOF
1273869/2 636934.5 even: 636934 up: 636935

The exact interest is 1,273,869 over 2 kobo: a half. The two rules split here, and only here, for a one-kobo difference that carries through the rest of the loan. L000059 has the same tie at instalment 9.

7. Post the book. Save this as post.py. It writes data/loan_ledger.sqlite, which is git-ignored with the rest of data/, and recreates it on every run.

cat > post.py <<'EOF'
"""Post Owoleaf's loan book into a small double-entry ledger. Money is integer kobo."""
import csv
import os
import sqlite3
from engine import fee

DATA = "data"
CUT_OFF = "2026-10-28"      # loan_book_meta.cut_off
ACCOUNTS = [
    (1100, "Cash", "asset"),
    (1200, "Loans receivable", "asset"),
    (4100, "Interest income", "income"),
    (4200, "Fee income", "income"),
    (4300, "Late-fee income", "income"),
    (5100, "Loss on write-off", "expense"),
]


def rows(name):
    with open(os.path.join(DATA, name + ".csv")) as f:
        return list(csv.DictReader(f))


db_path = os.path.join(DATA, "loan_ledger.sqlite")
if os.path.exists(db_path):
    os.remove(db_path)
db = sqlite3.connect(db_path)
db.executescript("""
CREATE TABLE accounts (code INTEGER PRIMARY KEY, name TEXT, kind TEXT);
CREATE TABLE journal  (id INTEGER PRIMARY KEY, posted_on TEXT, loan_id TEXT, memo TEXT);
CREATE TABLE lines    (journal_id INTEGER REFERENCES journal(id), account INTEGER REFERENCES accounts(code),
                       debit_kobo INTEGER NOT NULL DEFAULT 0, credit_kobo INTEGER NOT NULL DEFAULT 0,
                       CHECK (debit_kobo >= 0 AND credit_kobo >= 0 AND (debit_kobo = 0 OR credit_kobo = 0)));
""")
db.executemany("INSERT INTO accounts VALUES (?, ?, ?)", ACCOUNTS)


def post(posted_on, loan_id, memo, lines):
    """lines: [(account, debit, credit)]. Refuses an entry that does not balance."""
    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"{loan_id} {memo}: debits {sum(l[1] for l in lines)} "
                         f"!= credits {sum(l[2] for l in lines)}")
    cur = db.execute("INSERT INTO journal (posted_on, loan_id, memo) VALUES (?, ?, ?)",
                     (posted_on, loan_id, memo))
    db.executemany("INSERT INTO lines VALUES (?, ?, ?, ?)", [(cur.lastrowid, *l) for l in lines])


fee_bps = {p["code"]: int(p["fee_bps"]) for p in rows("loan_products")}
loans = rows("loans")
for l in loans:
    principal = int(l["principal_kobo"])
    f = fee(principal, fee_bps[l["product"]])
    assert f == int(l["fee_kobo"]), l["id"]                 # the engine's fee is the book's fee
    post(l["disbursed_at"], l["id"], "disbursement",
         [(1200, principal, 0), (1100, 0, principal - f), (4200, 0, f)])

for r in rows("repayments"):
    post(r["paid_at"], r["loan_id"], f"repayment {r['instalment']}",
         [(1100, int(r["amount_kobo"]), 0), (1200, 0, int(r["principal_kobo"])),
          (4100, 0, int(r["interest_kobo"])), (4300, 0, int(r["late_fee_kobo"]))])

for l in loans:
    if l["status"] == "written_off":
        post(CUT_OFF, l["id"], "write-off",
             [(5100, int(l["outstanding_principal_kobo"]), 0), (1200, 0, int(l["outstanding_principal_kobo"]))])
db.commit()

n_j, n_l = db.execute("SELECT (SELECT COUNT(*) FROM journal), (SELECT COUNT(*) FROM lines)").fetchone()
print(f"posted {n_j:,} journal entries and {n_l:,} lines to {db_path}")
EOF
python3 post.py

One entry for each of the 372 disbursements, one for each of the 891 repayments and one for each of the 2 write-offs: 372 + 891 + 2 = 1,265.

posted 1,265 journal entries and 3,455 lines to data/loan_ledger.sqlite

8. Prove it. Save this as prove.py.

cat > prove.py <<'EOF'
import csv
import sqlite3

db = sqlite3.connect("data/loan_ledger.sqlite")
q = lambda sql: db.execute(sql).fetchall()
naira = lambda k: f"₦{k / 100:,.2f}"

print("1. Entries that do not balance:",
      q("SELECT COUNT(*) FROM (SELECT journal_id FROM lines GROUP BY journal_id "
        "HAVING SUM(debit_kobo) <> SUM(credit_kobo))")[0][0])
d, c = q("SELECT SUM(debit_kobo), SUM(credit_kobo) FROM lines")[0]
print(f"2. Total debits {d:,} kobo, total credits {c:,} kobo, difference {d - c}")

print("3. Trial balance (debit minus credit, kobo):")
for code, name, bal in q("""SELECT a.code, a.name, COALESCE(SUM(l.debit_kobo - l.credit_kobo), 0)
                            FROM accounts a LEFT JOIN lines l ON l.account = a.code
                            GROUP BY a.code ORDER BY a.code"""):
    print(f"   {code} {name:<18}{bal:>16,}  {naira(bal):>16}")

with open("data/loans.csv") as f:
    loans = list(csv.DictReader(f))
book = sum(int(l["outstanding_principal_kobo"]) for l in loans)
written = sum(int(l["outstanding_principal_kobo"]) for l in loans if l["status"] == "written_off")
recv = q("SELECT SUM(debit_kobo - credit_kobo) FROM lines WHERE account = 1200")[0][0]
print(f"4. The book's outstanding principal      {book:>14,}  {naira(book)}")
print(f"   less principal written off            {written:>14,}  {naira(written)}")
print(f"   Loans receivable in the ledger        {recv:>14,}  {naira(recv)}")
print(f"   receivable + written off - book = {recv + written - book}")

per_loan = dict(q("""SELECT j.loan_id, SUM(l.debit_kobo - l.credit_kobo) FROM lines l
                     JOIN journal j ON j.id = l.journal_id WHERE l.account = 1200 GROUP BY j.loan_id"""))
off = [l for l in loans if per_loan.get(l["id"], 0) != (0 if l["status"] == "written_off" else int(l["outstanding_principal_kobo"]))]
print(f"5. Loans whose receivable differs from the book: {len(off)} of {len(loans)}")

bal = dict(q("SELECT account, SUM(credit_kobo - debit_kobo) FROM lines GROUP BY account"))
tot = lambda col: sum(int(l[col]) for l in loans)
checks = [
    ("interest income = paid_interest_kobo", bal[4100], tot("paid_interest_kobo")),
    ("fee income = fee_kobo", bal[4200], tot("fee_kobo")),
    ("late-fee income = paid_late_fees_kobo", bal[4300], tot("paid_late_fees_kobo")),
]
for name, got, want in checks:
    print(f"6. {name}: {got:,} vs {want:,} -> {'OK' if got == want else 'DIFFERENT'}")
paid_out = tot("disbursed_net_kobo")
with open("data/repayments.csv") as f:
    received = sum(int(r["amount_kobo"]) for r in csv.DictReader(f))
print(f"7. Cash: received {received:,} - paid out {paid_out:,} = {received - paid_out:,}; ledger says {-bal[1100]:,}")
EOF
python3 prove.py
1. Entries that do not balance: 0
2. Total debits 12,415,334,988 kobo, total credits 12,415,334,988 kobo, difference 0
3. Trial balance (debit minus credit, kobo):
   1100 Cash                  -170,123,591    ₦-1,701,235.91
   1200 Loans receivable       816,457,900     ₦8,164,579.00
   4100 Interest income       -591,642,888    ₦-5,916,428.88
   4200 Fee income             -82,342,000      ₦-823,420.00
   4300 Late-fee income         -6,150,000       ₦-61,500.00
   5100 Loss on write-off       33,800,579       ₦338,005.79
4. The book's outstanding principal         850,258,479  ₦8,502,584.79
   less principal written off                33,800,579  ₦338,005.79
   Loans receivable in the ledger           816,457,900  ₦8,164,579.00
   receivable + written off - book = 0
5. Loans whose receivable differs from the book: 0 of 372
6. interest income = paid_interest_kobo: 591,642,888 vs 591,642,888 -> OK
6. fee income = fee_kobo: 82,342,000 vs 82,342,000 -> OK
6. late-fee income = paid_late_fees_kobo: 6,150,000 vs 6,150,000 -> OK
7. Cash: received 6,064,534,409 - paid out 6,234,658,000 = -170,123,591; ledger says -170,123,591

Read check 4 as arithmetic you can redo: 850,258,479 − 33,800,579 = 816,457,900 kobo. The ledger’s loans receivable is the book’s outstanding principal (₦8,502,584.79) less the two written-off loans’ principal (₦338,005.79), which now sits in loss on write-off. Check 5 compares the ledger with the loan table loan by loan, so a principal posted to the wrong loan, which would cancel out in the total, still shows up. Checks 6 and 7 compare totals of the income and cash accounts with the loan tables.

Break the ledger and watch it refuse. Copy post.py, delete the late-fee posting from the repayment lines, and run the copy:

sed 's/(4300, 0, int(r\["late_fee_kobo"\]))/(4300, 0, 0)/' post.py > post_bad.py
python3 post_bad.py 2>&1 | tail -1
rm post_bad.py

The last line is ValueError: L000001 repayment 1: debits 825000 != credits 775000. L000001 paid its first instalment late, and its customer paid a ₦500 late fee on top of the ₦7,750 instalment. Cash was debited for 825,000 kobo and nothing was credited for the 50,000 kobo of fee, so the guard in post stopped the run on the first such repayment. Without the guard the unbalanced entries would have been stored, and the ledger would have been out of balance with no sign of which loan caused it. Then say which check in prove.py would have caught the same mistake if the guard did not exist, and which would not.

ARTEFACT Write the engine acceptance report and ledger sign-off ~45 MIN
YOU PRODUCEAn engine acceptance test report and ledger sign-off

Template

# Acceptance report: <engine and ledger names>, <book, cut-off date>
Prepared by <engineer or analyst>. Signed by <head of finance>.

## 1. Scope
What was tested (engine version, posting job, data and seed) and what was not.

## 2. Test cases
| # | Test | Expected | Actual | Result |
One row per test. Expected is written before the run, in kobo.

## 3. Ledger against schedule
- Entries posted: <count>, lines: <count>. Entries that do not balance: <n>
- Loans receivable <kobo> + principal written off <kobo> - book <kobo> = <difference>
- Income and cash accounts against the loan tables: <each, OK or DIFFERENT>

## 4. Breaks
| Break | Size (kobo) | Cause | Defect or by design | Owner, fix date |
Write "none" if there were none.

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

## 6. Sign-off
Rules accepted: <rounding rule, posting dates>. Decision needed: <what, from whom, by when>.
Out of scope: <what this report does not cover>.
Prepared <name, date>. Approved <name, date>.
WORKED EXAMPLE

At Owoleaf, Bola, who built the engine, writes this report, and Hafsat, who runs finance, signs it before the month-end is closed on the new ledger. This one covers the seed-42 book to the 2026-10-28 cut-off.

Test cases.

# Test Expected Actual Result
1 L000043 schedule six instalments of 6,010,230; fee 310,000 same Pass
2 Flat interest, ₦310,000, 450 bps, 6 periods 8,370,000 (31,000,000 × 4.5% × 6) 8,370,000 Pass
3 Every schedule, half-even 372 of 372 372 of 372 Pass
4 Entries balance 0 that do not 0 of 1,265 Pass
5 Late fee left out of a copy the guard refuses L000001 repayment 1: debits 825000 != credits 775000 Pass

Ledger against schedule. In kobo: receivable 816,457,900 + written off 33,800,579 − book 850,258,479 = 0. Receivable differs on 0 of 372 loans. Interest, fee and late-fee income match the loan tables, and cash is −170,123,591 kobo (−₦1,701,235.91) on both sides.

Breaks. One apparent break: receivable is ₦8,164,579.00 against ₦8,502,584.79 in the book, ₦338,005.79 apart. Cause: the book keeps the two written-off loans’ principal, the ledger moves it to loss. By design, not a defect.

Could be wrong. Both sides come from loans.py, so the proof is internal. The partner bank’s statement could show a different cash figure. Interest is booked when paid, not as it accrues.

Sign-off. Hafsat is asked to accept half-even rounding and a write-off dated at the cut-off. Provisioning and funding are out of scope.

Now you

You are an analyst at a 30-person digital lender in Abuja. Its engineer has delivered a new engine and ledger job, built from the pricing spreadsheet, and the head of finance signs the month-end. Treat the lab’s 372-loan book to 2026-10-28 as the lender’s own. Two facts about the delivery: the engine rounds half up, and the ledger job was shipped without write-off postings. Reproduce both. Run verify.py and read its 'up' line. Copy post.py, change the write-off condition to if False:, run the copy, then run prove.py and read checks 3, 4 and 5. Run post.py again afterwards to restore the ledger. Write the acceptance report: which tests pass, which are breaks, what causes each, and whether you would recommend sign-off as it stands. Your head of finance reads it to decide whether to sign this month’s close or hold it until the rounding rule and the write-off posting are fixed.

Self-check

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: Credit analysis as a lender does it: the five Cs →