SENIORAICHAPTER 25

Machine-learning fraud scoring at authorisation: features, latency budgets and false declines

A fraud model is graded on labels that arrive late and miss some frauds. Split by time, price both mistakes, and measure who gets declined before the bank's customers do

75 MINPAYMENTSUPDATED 2026-11-14
PREDICT

Owoleaf's lab data has 88 approved card top-ups that were fraud, and 71 of them are eventually reported. On 30 June you build a training set. The approved top-ups from June contain 18 that are eventually reported (by the 28 October cut-off). How many of those 18 reports have arrived by 30 June?

Where the score sits

A card authorisation is a question with a deadline. A merchant sends a card payment, the scheme routes it, and the issuer approves or declines. The card payment chapter draws the four parties. An issuer processor, the company in this chapter, runs that decision for the bank: it checks the balance and card status and asks a risk model how likely fraud is.

The model returns a number between 0 and 1. A threshold turns it into an action, and there are three actions, not two.

requestcard, amount, devicefeatureshistory and contextscore0 to 1below low: approvebetween: step up (OTP)above high: declinelookups: where the budget goesscore, threshold, replythe whole decision must fit a budget you set (this chapter uses 50 ms at the 99th percentile)

The 50 ms is this chapter’s design budget, not a scheme rule: each scheme and bank sets its own timeouts, which you read from your contracts. The lookups and the reply come out of the same total.

The lab is Owoleaf’s, a wallet company that accepts card top-ups, so it plays the merchant side of the same decision. The data has the shape an issuer would see: a card, a device, a place, an amount, and a fraud label that arrives later. An issuer sees every merchant its cardholder pays, so its history is richer: the mechanics carry over, the numbers do not.

What you can know, and when

A supervised model learns from labels. For fraud, a label is a report: a cardholder disputes a charge, or the issuer tells you a card was compromised. The AI in payments chapter listed the problem: labels are late and incomplete. Now measure it.

Delay. A report arrives after the payment, sometimes weeks after. In the lab, 71 approved payments are eventually reported. The first report for a payment arrives 5.1 days after it at the earliest, 27.8 days at the median, 52.8 days at the 90th percentile and 71.9 days at the latest. Step 2 prints the curve: 60.6% of reports are in after 30 days and 93.0% after 60, so a payment from June is mostly unlabelled on 30 June. The fix is to treat every label as a fact about a date: train with the labels you would have had that day, and leave out payments too young for their labels to have arrived.

Missing labels. Not every fraud is reported. A cardholder who does not notice leaves a payment that your table calls good. Step 6 lets you count how many. Until then you know only that it is not zero. Part of the fix is procedural: send a sample of “good” payments for manual review, so some labels do not come from a complaint.

No label at all. A payment that was declined never became a charge, so nobody disputes it. The model trains only on payments the previous rule approved, a selection effect: it is graded on a population its own decisions will change. The lab trains and grades on approved payments only, 10,280 of the 10,680 attempts. A common answer is to approve a small random sample of the payments the model would decline, so you learn what they would have done, at a cost you set.

Look-ahead is a fourth hazard, and you create it: a feature built from data after the decision gives the model an answer it will not have in production. The data leakage lesson shows the failure. The lab’s loader builds every feature as of the attempt’s own timestamp.

Features that exist at the moment of the decision

A feature is a number the scoring service can compute from what it holds when the request arrives. Step 1 builds twelve from the lab’s transactions, card_attempts, cards and customers tables.

Feature What it measures Source at decision time
n_1h, n_24h the customer’s earlier card attempts in the last hour and day the customer’s history
log_ratio how far the amount is above the customer’s median of earlier attempts (0 if below, or if there is no history) the customer’s history
log_amount the natural log of the amount in naira the request
new_device the device first seen for this customer today (device_age_days is 0) the request and history
abroad, ip_other_state the IP address places the payer abroad, or in a state other than the customer’s own the request and the profile
foreign_card the card’s issuer is outside Nigeria the card record
new_card first use of this card, for a customer who has paid before the card record and history
tier1 the customer’s KYC tier is 1 the profile
no_history the customer has no earlier attempt the history
log_age_days the log of the wallet’s age in days the profile

Two columns are in the table card_attempts and are left out on purpose. approval_code exists only when the payment was approved, so it is the outcome and not a feature. three_ds, whether the payer was challenged, is a decision taken around the authorisation by a different control. It is also drawn differently for fraud and good payments in this data, so it is a strong signal that a real service could use only if the challenge came before the score. The authenticating the payer chapter, later in this module, is the place for it; the model here goes without. device_id is an identifier, not a measurement, and status is the outcome.

One feature carries a trap. “The amount against the customer’s median” is easy to compute over all of a customer’s history, including payments that come after this one, and that is a look-ahead. log_ratio uses only earlier attempts. In this data it gets a coefficient close to zero: fraud amounts here look like good ones, so the feature a vendor’s slide would feature first carries no signal.

The velocity features count earlier attempts including declined ones, because a burst of declines is what you want to see. They are the costly features, needing the customer’s recent history at request time; step 4 times them.

A last rule is about code, not data. The service that scores a live request must compute a feature exactly as the training code did. If it does not, you have train-serve skew, and the model sees a different world from the one it learned. The lab’s step 4 recomputes every feature the way a service would and compares the vectors with the training ones: 0 of 2,000 differ, which on a real system is rare.

A logistic regression, by hand

Logistic regression turns a weighted sum of features into a probability. For one payment with standardised features z1 to z12, the score is p = 1 / (1 + e^(-s)), where s is a bias b plus the sum of each weight times its feature. Training chooses the weights that make the observed labels most likely, with a penalty on large weights (L2 regularisation) to stop 13 positive examples being chased as noise. The lab does it by gradient descent: compute the error p minus label for every payment, move each weight a small step against its average gradient, repeat 400 times. Learning rate shows why the step size matters. This model has twelve weights and no hidden layer; larger models are the AI Engineering course’s subject, starting from what an LLM is.

Why so small? Not because it is the best. It scores in microseconds, you can print every weight, and it gives reason codes for free: multiply each weight by the payment’s standardised feature value, and the largest positive products are the reasons the score is high. A gradient-boosted tree ensemble or a neural network can find interactions this model cannot, such as a new device and a foreign card together being worse than either, but it earns its place only when you have measured the gain on a later period and can still explain a decline; explanation tools added afterwards, such as SHAP values, are approximations.

Split by time, not by shuffle

The lab splits the card attempts by date: train on January to March, validate on April, test on May and June. Each set has one job. One caveat: this is a hindsight design. Labels are as known on 30 June, even for April, while a live system on 1 May would have had only 2 of April’s 28 reports (step 2). Step 7’s variant 2 measures that gap, so treat the test as better than a live run would be.

  • Train fits the weights: 2,163 approved payments, of which 13 carry a report by 30 June.
  • Validate is where you make choices: the threshold, the strength of the penalty, which features to keep. 2,018 payments, 28 reports. It is graded on labels as known on 30 June.
  • Test is touched once, for the number you report: 6,099 payments in May and June.

Fraud is not independent over time. In the lab, a ring of stolen cards works through new tier 1 wallets in April, a burst of related payments. Shuffle everything and hold out 30%, and the ring sits on both sides: the model recognises its customers and devices, and the held-out score looks wonderful. Step 7 shows it: a random split scores an average precision of 0.735 on the held-out payments against the reports and 0.835 against the truth, where the time split scores 0.510 against the truth.

Average precision sorts payments by score and, at each true fraud, records the share of payments so far that are fraud, then averages those. A random guess scores about the base rate, 0.014 in validation (28 of 2,018); the model scores 0.760, which flatters it because April is the ring’s month and a ring is easy to find. The test number, 0.427 against the reports, is closer to what you should expect.

Step 3 also checks a hand-written rule as baseline: a new device together with an IP in another state or abroad, a foreign card, or a new card. A model that does not beat its rule has no business replacing it. On April the rule flags 71 payments and 22 are labelled fraud; the model’s 71 highest scores catch all 28. Compare at equal flag volume.

The latency budget

The model is not where the time goes. In step 4 the score takes a median of 0.002 ms and the twelve features 0.005 ms. The lookups cost more: reading the customer’s earlier attempts from SQLite takes a median of 0.046 ms and a 99th percentile of 0.494 ms, and the whole SQL-per-payment path has a median of 0.067 ms. Holding the history in memory, updated as each payment arrives, brings the median to 0.007 ms. These figures are from one machine with a local database; yours will differ.

A production service is not that kind: its history lives in a feature store or cache behind a network call. Take the lab’s three lookups (history, context, card record) and an assumed 3 ms per remote call. In series they cost 9 ms, in parallel 3 ms. Now take a 99th-percentile call of 20 ms, also assumed: three in series cost 60 ms, which blows a 50 ms budget before the model has run. The tail latency lesson is why to budget at the 99th percentile and not the median: with three independent calls, a request meets at least one slow call far more often than any one call is slow.

Three design moves follow. Fetch independent features in parallel. Precompute expensive ones, such as a rolling 24-hour count, as events arrive. And decide what happens when the budget runs out, because it will: a timed-out feature takes a default, the score falls back to a rule, or the decision is made without a score. That is a business choice about which error you prefer under failure, and it belongs in writing before the incident, as the payments incidents chapter, earlier in this module, argues for money movement.

Choosing the threshold by cost

A threshold is a price. Declining a fraud saves its amount; declining a good payment costs you something. Write C for the cost of a wrongly declined good payment and L for the loss on a fraud you miss. You should decline when the probability p that the payment is fraud satisfies p times L greater than (1 minus p) times C, which rearranges to p greater than C / (C + L).

The lab puts numbers on both and says which are invented. A missed fraud costs the amount plus the ₦1,000 chargeback fee the generator charges, a mean of ₦5,750.71 in April. A false decline costs ₦300, an illustrative stand-in for margin forgone, a support contact and some churn: change it, and the answer changes. The break-even probability is 30,000 / (30,000 + 575,071) = 5.0% (all in kobo). A model’s output is a probability only if it is calibrated. This one is right on average (its mean validation score is 1.4%, the labelled share is 1.4%) but not in the tail: it scores some April frauds below 5%, so a 5% threshold would miss two of them (step 5’s 0.050 row). The cheapest threshold, 0.028, is the score of April’s lowest-scoring fraud. A threshold chosen by cost on validation absorbs that; the formula’s would not.

Step 5 scans thresholds on April and finds 0.028 cheapest: it declines 64 payments, catches all 28 labelled frauds and wrongly declines 36, at a cost of ₦10,800.00 against ₦161,020.00 for declining nothing. Applied unchanged to May and June it declines 161 of 6,099 approved payments (2.6%) and catches 23 of the 30 reported frauds, with precision 14.3%. The cost falls from ₦379,381.00 with no model to ₦117,565.00. The test is less kind, as expected when April’s ring was the easy case. The weekly decline rate wanders between 1.4% and 3.9%.

At a false-decline cost of ₦1,000, more than three times the ₦300 above, step 5’s cheapest threshold on April is still 0.028: it is pinned by one payment, the lowest-scoring April fraud, and does not respond to the price. One month of validation is thin, and this does not show the threshold is robust. Between a low and a high threshold sits the diagram’s middle band: a step-up challenge (an OTP, or a check in the banking app) lets the genuine customer through at a cost of friction. The authenticating the payer chapter covers how well that works.

Who gets declined

A model declines payments, and payments belong to people with a KYC tier, a state, a phone and a card. Step 6 opens the answer key, only now, and measures, among payments that were not fraud, the share declined at step 5’s threshold.

By KYC tier, 103 of 3,438 good tier 1 payments are declined (3.0%, 95% interval 2.5% to 3.6%), against 16 of 2,075 for tier 2 (0.8%, 0.5% to 1.2%) and 13 of 547 for tier 3 (2.4%, 1.4% to 4.0%). The fraud share of each tier is similar: 0.66%, 0.57% and 0.73%. Tier 1 customers are declined nearly four times as often as tier 2 for a fraud share within 0.1 percentage points, so the data does not support the gap as a difference in risk.

By state, Kaduna’s good payments are declined 6.9% of the time (20 of 288, interval 4.5% to 10.5%) against 1.7% in Lagos (47 of 2,764) and 0.2% in Rivers (1 of 400). The intervals are Wilson intervals, computed in pure Python: with a few hundred good payments, a rate of a few per cent is known only to within a factor of two.

A gap does not prove unfairness, and its absence would not prove fairness; it tells you where to look. Step 7 retrains without the tier1 feature. The tier 1 false-decline rate falls from 3.0% to 2.1% and the tier 2 rate rises from 0.8% to 1.9%, the average precision stays at about the same level (0.521 against 0.510), and 31 of 39 frauds are caught against 29. On 39 frauds, that shows no loss; the feature was not earning its place. The remaining gap comes from other features: a Kaduna customer’s good payments carry a foreign card more often in this data (6.6% against 2.0% elsewhere), and the model reads that as risk. Whether that is a fair signal depends on who carries a foreign card: a student abroad, a trader, a relative sending money home.

Three habits follow. Test suspected proxies by removing them and re-measuring. Prefer a step-up to a decline for groups you cannot yet explain, since it costs the customer a minute and not the payment. Keep the numbers, with intervals, in the model’s validation record. Rule engines and case management are the Compliance course’s subject.

Governing a model that declines customers

A model that refuses a customer’s money is a risk the company owns, and the rules about owning it are changing. Five sources are worth knowing, each with its limits.

The Federal Reserve’s SR 26-2, dated 17 April 2026, supersedes SR 11-7 (4 April 2011) and SR 21-8as of 2026-11. Search results confirmed this against the Fed’s letter. One commentary says the two documents coexist, which contradicts the letter’s wording, so take the letter. Summaries disagree on whether it covers generative and agentic AI, which a fraud classifier is not. It binds US banks, not a Lagos processor; read it for the expected practice of a model inventory, independent validation, monitoring and a way to switch the model off. The LLMs in operations chapter covers the same ground for language models.

The Prudential Regulation Authority’s SS1/23 sets five principles for model risk management at UK banks and was published on 17 May 2023; summaries say compliance was required from 17 May 2024 for firms with internal-model approvalas of 2026-11. Search results were mostly consultancy summaries, so check the statement for scope and transition terms.

Annex III of the EU AI Act lists, in point 5(b), AI systems that evaluate the creditworthiness of natural persons or set their credit score as high-risk, with an exception for AI systems used to detect financial fraudas of 2026-11. Commentary disagrees on how narrow that exception is: one reading limits it to systems built only for fraud, another says a fraud model feeding a credit decision is exempt only for the fraud step. Sources also disagree on when the high-risk obligations apply and mention new dates, so check the current ones. The carve-out’s edges are argued, so it is not a safe harbour.

Section 37 of the Nigeria Data Protection Act 2023, in Part VI on data subject rights, is described by commentary as giving a person protection from decisions based solely on automated processing, including profiling, that have legal or similarly significant effects, with exceptions such as explicit consent, and with a right in permitted cases to human involvement, to state a view and to contest the decisionas of 2026-11. This build could not open the section’s text, so the wording comes from law-firm commentary. Ask counsel whether declining a card payment is a significant effect. Either way, a declined customer should be able to reach a person, and the reason codes are what that person needs.

A law-firm note on the CBN’s circular of 12 March 2026 on instant payments describes requirements that took effect on 1 July 2026, including enterprise fraud monitoring that tracks both inflows and outflowsas of 2026-11. That circular concerns instant payments, not cards, and this build did not open the CBN’s own text. This chapter states no CBN rule on card fraud scoring: search summaries of the CBN’s 2020 electronic payment channels guidelines showed none.

Validation, in practice, is the table in step 6: the label error, the recall with its interval, the false-decline rates by group, and a stated purpose and limit. Monitoring is the weekly decline rate from step 5 and the share of reports arriving late. Retraining is slower than it sounds: the delay curve sets when a label can first be used.

What the lab cannot show

There are 88 approved frauds in the data: 15 in training, 34 in validation and 39 in test. The test recall of 74% has a 95% interval of 59% to 85%, which is what 39 frauds can tell you. The data is generated, and the generator draws the new device, the foreign card and the IP location from its fraud flag, so a model that finds those signals proves the maths, not the world. A real issuer has far more frauds and far less clean signals. Scale 1 gives ten times the data (about 38 seconds, 715 MB) and different numbers.

LAB Build, grade and audit a fraud score on Owoleaf's card top-ups ~75 MIN
YOU NEEDPython 3.9 or later (standard library only)labs/finance generated at seed 42, scale 0.1, with cards.py run (about 4 s)a free chat assistant or a local model for step 8 (no paid account); steps 1 to 7 need no model

You work in labs/finance. Every script is standard library only and lives in a new fraud/ folder. The sqlite3 command-line tool may not be installed, so the scripts use Python’s sqlite3 module. Steps 1 to 5 never open answers/: they work only with what Owoleaf could see. Steps 6 and 7 open answers/card_fraud_truth.csv to grade the model, and cards.py prints one number from it (92) that you should ignore until then. Results are exact for seed 42 at scale 0.1; the timings in step 4 depend on your machine.

0. Generate the data and check it. If data/ already exists at seed 42, cards.py is the only command you need.

cd labs/finance
python3 generate.py && python3 cards.py && python3 check.py
mkdir -p fraud

The last lines of the three commands (generate.py prints a table of row counts first):

1936 cards, 10680 card attempts, 99 fraud reports, 109 disputes
disputes at 2026-10-28: accepted 20, lost 28, won 61
fraud in truth: 92 of 10680 card fundings (answers/card_fraud_truth.csv)
card book: 10,680 card attempts, 109 disputes for 91,728,900 kobo; checks 12-15 run
accounts by type (debit-positive kobo): {'asset': 17355054889, 'equity': -5000000000, 'expense': 110590267, 'income': -221782321, 'liability': -12243862835}
settlement_bank in ledger 17,189,646,589 kobo; on the statement 17,192,741,324 kobo
OK: all invariants hold

cards.py prints the first three lines and check.py the rest, ending OK: all invariants hold. Invariants 12 to 15 are the card tables’.

1. Write the shared library and look at the feature table. fraudlib.py holds everything the later steps share: the loader that builds every feature as of the attempt’s own time, the logistic regression, average precision, Wilson intervals and the cost function. Money is integer kobo throughout; naira() only formats it.

cat > fraud/fraudlib.py <<'EOF'
"""Shared code for the fraud-scoring lab. Standard library only. Money is integer kobo."""
import collections, csv, datetime as dt, math, sqlite3

DB = "data/finance.sqlite"
TZ = dt.timezone(dt.timedelta(hours=1))                     # the generator's local time, +01:00


def D(month, day):
    return dt.datetime(2026, month, day, tzinfo=TZ)


TRAIN_END, VALID_END, TEST_END = D(4, 1), D(5, 1), D(7, 1)   # train Jan-Mar, validate Apr, test May-Jun
TRAIN_ASOF = D(6, 30)                                       # the day you train and tune: labels as known then
FEATURES = ["n_1h", "n_24h", "log_ratio", "log_amount", "new_device", "abroad", "ip_other_state",
            "foreign_card", "new_card", "tier1", "no_history", "log_age_days"]
DISPUTE_FEE_KOBO = 100_000        # the lab's chargeback fee (cards.py): ₦1,000
FALSE_DECLINE_KOBO = 30_000       # ILLUSTRATIVE: what a wrongly declined good payment costs you, ₦300

SQL = """
SELECT t.id, t.status, t.created_at, t.amount_kobo, t.customer_id, c.kyc_tier, c.state, c.signup_at,
       a.device_age_days, a.ip_state, k.issuer_country, k.first_used_at,
  (SELECT COUNT(*) FROM transactions p WHERE p.customer_id = t.customer_id AND p.kind = 'funding_card'
     AND p.created_at < t.created_at
     AND julianday(t.created_at) - julianday(p.created_at) <= 1.0 / 24) AS n_1h,
  (SELECT COUNT(*) FROM transactions p WHERE p.customer_id = t.customer_id AND p.kind = 'funding_card'
     AND p.created_at < t.created_at
     AND julianday(t.created_at) - julianday(p.created_at) <= 1.0) AS n_24h
FROM transactions t
JOIN customers c ON c.id = t.customer_id
JOIN card_attempts a ON a.transaction_id = t.id
JOIN cards k ON k.id = a.card_id
WHERE t.kind = 'funding_card'
ORDER BY t.created_at, t.id
"""


class Row:
    """One card attempt with its features, as known at the moment of the attempt."""
    def __init__(self, **kw):
        self.__dict__.update(kw)


def load(path=DB):
    db = sqlite3.connect(path)
    history = collections.defaultdict(list)                 # customer -> amounts of earlier attempts
    rows = []
    for (tid, status, created, amount, cid, tier, state, signup, dev_age, ip, issuer, first_used,
         n1, n24) in db.execute(SQL):
        t = dt.datetime.fromisoformat(created)
        past = sorted(history[cid])
        median = (past[len(past) // 2] + past[(len(past) - 1) // 2]) / 2 if past else None
        log_ratio = max(0.0, math.log(amount / median)) if median else 0.0
        age_days = max(0, (t - dt.datetime.fromisoformat(signup)).days)
        x = [n1, n24, log_ratio, math.log(amount / 100), 1.0 if dev_age == 0 else 0.0,
             1.0 if ip == "ABROAD" else 0.0, 1.0 if ip not in (state, "ABROAD") else 0.0,
             1.0 if issuer != "NG" else 0.0, 1.0 if (first_used == created and past) else 0.0,
             1.0 if tier == 1 else 0.0, 0.0 if past else 1.0, math.log1p(age_days)]
        rows.append(Row(id=tid, status=status, t=t, amount=amount, customer=cid, tier=tier, state=state, x=x))
        history[cid].append(amount)
    return rows


def reports(path=DB):
    """transaction id -> when Owoleaf first heard it was fraud."""
    db = sqlite3.connect(path)
    out = {}
    for tid, at in db.execute("SELECT transaction_id, reported_at FROM fraud_reports ORDER BY reported_at"):
        out.setdefault(tid, dt.datetime.fromisoformat(at))
    return out


def window(rows, start, end):
    """Approved payments only: a payment that was not approved never gets a fraud label."""
    return [r for r in rows if r.status == "succeeded" and start <= r.t < end]


def label(r, rep, as_of=None):
    """1 if a report for this payment had arrived by as_of (default: ever, to the cut-off)."""
    return 1 if r.id in rep and (as_of is None or rep[r.id] <= as_of) else 0


def sigmoid(z):
    return 1.0 / (1.0 + math.exp(-z)) if z > -30 else 0.0


def fit(xs, ys, l2=10.0, iters=400, rate=0.5):
    """Logistic regression by batch gradient descent on standardised features, with an L2 penalty."""
    d, n = len(xs[0]), len(xs)
    mu = [sum(x[j] for x in xs) / n for j in range(d)]
    sd = [max(1e-9, math.sqrt(sum((x[j] - mu[j]) ** 2 for x in xs) / n)) for j in range(d)]
    zs = [[(x[j] - mu[j]) / sd[j] for j in range(d)] for x in xs]
    w, b = [0.0] * d, math.log(sum(ys) / (n - sum(ys)))     # start at the base rate
    for _ in range(iters):
        gw, gb = [0.0] * d, 0.0
        for z, y in zip(zs, ys):
            e = sigmoid(b + sum(wi * zi for wi, zi in zip(w, z))) - y
            gb += e
            for j in range(d):
                gw[j] += e * z[j]
        w = [wi - rate * (g + l2 * wi) / n for wi, g in zip(w, gw)]
        b -= rate * gb / n
    return {"mu": mu, "sd": sd, "w": w, "b": b}


def standardise(m, x):
    return [(xi - mu) / sd for xi, mu, sd in zip(x, m["mu"], m["sd"])]


def score(m, x):
    return sigmoid(m["b"] + sum(w * z for w, z in zip(m["w"], standardise(m, x))))


def average_precision(scores, ys):
    tp, total, area = 0, sum(ys), 0.0
    for i, (_, y) in enumerate(sorted(zip(scores, ys), key=lambda p: -p[0]), 1):
        if y:
            tp += 1
            area += tp / i
    return area / total


def wilson(k, n, z=1.96):
    """95% interval for a share k of n."""
    if n == 0:
        return (0.0, 0.0)
    p = k / n
    d = 1 + z * z / n
    c = (p + z * z / (2 * n)) / d
    h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
    return (c - h, c + h)


def confusion(rows, scores, ys, threshold):
    tp = sum(1 for s, y in zip(scores, ys) if s >= threshold and y)
    fp = sum(1 for s, y in zip(scores, ys) if s >= threshold and not y)
    fn = sum(1 for s, y in zip(scores, ys) if s < threshold and y)
    return tp, fp, fn


def cost_kobo(rows, scores, ys, threshold):
    """Missed fraud costs the amount plus the chargeback fee; a false decline costs FALSE_DECLINE_KOBO."""
    total = 0
    for r, s, y in zip(rows, scores, ys):
        if s >= threshold and not y:
            total += FALSE_DECLINE_KOBO
        elif s < threshold and y:
            total += r.amount + DISPUTE_FEE_KOBO
    return total


def naira(kobo):
    return f"₦{kobo // 100:,}.{kobo % 100:02d}"
EOF
cat > fraud/step1_features.py <<'EOF'
"""Step 1: build the as-of feature table and look at it. Never opens answers/."""
import collections
from fraudlib import *

rows = load()
rep = reports()
print(f"{len(rows)} card attempts; {sum(r.status == 'succeeded' for r in rows)} approved; {len(rep)} payments with a fraud report")
by = collections.defaultdict(lambda: [0, 0, 0])
for r in rows:
    m = by[r.t.strftime("%Y-%m")]
    m[0] += 1
    m[1] += r.status == "succeeded"
    m[2] += label(r, rep) if r.status == "succeeded" else 0
print("month    attempts  approved  reported fraud")
for k in sorted(by):
    print(f"{k}  {by[k][0]:8d}  {by[k][1]:8d}  {by[k][2]:8d}")
print()
for name, start, end in [("train", D(1, 1), TRAIN_END), ("validate", TRAIN_END, VALID_END), ("test", VALID_END, TEST_END)]:
    w = window(rows, start, end)
    print(f"{name:9s} {start.date()} to {end.date()}: {len(w)} approved payments")
print()
print("feature means over approved payments:")
ok = [r for r in rows if r.status == "succeeded"]
for j, f in enumerate(FEATURES):
    print(f"  {f:15s}{sum(r.x[j] for r in ok) / len(ok):8.3f}")
EOF
python3 fraud/step1_features.py
10680 card attempts; 10280 approved; 71 payments with a fraud report
month    attempts  approved  reported fraud
2026-01       229       224         1
2026-02       681       655         3
2026-03      1330      1284         9
2026-04      2103      2018        28
2026-05      3008      2902        12
2026-06      3329      3197        18

train     2026-01-01 to 2026-04-01: 2163 approved payments
validate  2026-04-01 to 2026-05-01: 2018 approved payments
test      2026-05-01 to 2026-07-01: 6099 approved payments

feature means over approved payments:
  n_1h              0.008
  n_24h             0.169
  log_ratio         0.347
  log_amount        8.647
  new_device        0.193
  abroad            0.002
  ip_other_state    0.092
  foreign_card      0.022
  new_card          0.034
  tier1             0.569
  no_history        0.146
  log_age_days      3.675

The ring is visible in April: 28 reported frauds in 2,018 approved payments. The three windows are the split the chapter uses. Declined attempts (400 in all) are excluded: they never get a label.

2. Measure how late the labels are. This prints the delay between a payment and its first fraud report, the share of reports that have arrived after a number of days, and what each month’s label count looks like on three different days.

cat > fraud/step2_labels.py <<'EOF'
"""Step 2: how late do labels arrive? Never opens answers/."""
import datetime as dt
from fraudlib import *

rows = {r.id: r for r in load()}
rep = reports()
days = sorted((rep[i] - rows[i].t).total_seconds() / 86400 for i in rep)
n = len(days)
print(f"{n} reported payments; days from payment to first report: "
      f"min {days[0]:.1f}, median {days[n // 2]:.1f}, 90th percentile {days[int(n * .9)]:.1f}, max {days[-1]:.1f}")
print()
print("share of all eventual reports that had arrived d days after the payment:")
for d in (7, 14, 30, 45, 60, 75):
    print(f"  after {d:2d} days: {sum(1 for x in days if x <= d) / n:6.1%}")
print()
print("what a label looks like depends on the day you look (approved payments, reported fraud):")
print("payments in   looked at 30 Apr   looked at 30 Jun   looked at 28 Oct (cut-off)")
for name, start, end in [("March", D(3, 1), D(4, 1)), ("April", D(4, 1), D(5, 1)),
                         ("May", D(5, 1), D(6, 1)), ("June", D(6, 1), D(7, 1))]:
    w = window(list(rows.values()), start, end)
    a = [sum(label(r, rep, d) for r in w) for d in (D(4, 30), D(6, 30), None)]
    print(f"{name:12s}  {a[0]:14d}   {a[1]:15d}   {a[2]:15d}")
EOF
python3 fraud/step2_labels.py
71 reported payments; days from payment to first report: min 5.1, median 27.8, 90th percentile 52.8, max 71.9

share of all eventual reports that had arrived d days after the payment:
  after  7 days:   2.8%
  after 14 days:  16.9%
  after 30 days:  60.6%
  after 45 days:  81.7%
  after 60 days:  93.0%
  after 75 days: 100.0%

what a label looks like depends on the day you look (approved payments, reported fraud):
payments in   looked at 30 Apr   looked at 30 Jun   looked at 28 Oct (cut-off)
March                      8                 9                 9
April                      2                28                28
May                        0                10                12
June                       0                 5                18

June shows 5 reported frauds on 30 June and 18 at the cut-off. April shows 2 on 30 April, the day you might have trained, and 28 two months later. A model trained on 30 April’s labels is told that April was nearly clean.

3. Train on January to March, check on April, and beat the rule. The labels are those known on 30 June. The script saves the model to fraud/model.json.

cat > fraud/step3_train.py <<'EOF'
"""Step 3: train on January-March, check on April. Labels are what Owoleaf knew on 30 June. Never opens answers/."""
import json
from fraudlib import *

rows, rep = load(), reports()
train, valid = window(rows, D(1, 1), TRAIN_END), window(rows, TRAIN_END, VALID_END)
ytr = [label(r, rep, TRAIN_ASOF) for r in train]
yva = [label(r, rep, TRAIN_ASOF) for r in valid]
print(f"train {len(train)} payments, {sum(ytr)} labelled fraud; validate {len(valid)}, {sum(yva)} labelled fraud")

model = fit([r.x for r in train], ytr)
json.dump(model, open("fraud/model.json", "w"))
print("\ncoefficients (per standard deviation of the feature), largest first:")
for w, f in sorted(zip(model["w"], FEATURES), key=lambda p: -abs(p[0])):
    print(f"  {f:15s}{w:8.3f}")

sva = [score(model, r.x) for r in valid]
print(f"\nvalidation average precision: {average_precision(sva, yva):.3f}  (all-zero guess: {sum(yva) / len(yva):.3f})")

# A hand-written rule as the baseline the model has to beat.
def rule(r):
    f = dict(zip(FEATURES, r.x))
    return f["new_device"] and (f["abroad"] or f["ip_other_state"] or f["foreign_card"] or f["new_card"])
flagged = [r for r in valid if rule(r)]
tp = sum(label(r, rep, TRAIN_ASOF) for r in flagged)
print(f"\nrule 'new device and (abroad, other state, foreign or new card)': flags {len(flagged)}, "
      f"{tp} labelled fraud, precision {tp / len(flagged):.1%}, recall {tp / sum(yva):.1%}")
top = sorted(range(len(valid)), key=lambda i: -sva[i])[:len(flagged)]
tp2 = sum(yva[i] for i in top)
print(f"model, same {len(flagged)} flags (highest scores): {tp2} labelled fraud, "
      f"precision {tp2 / len(flagged):.1%}, recall {tp2 / sum(yva):.1%}")
EOF
python3 fraud/step3_train.py
train 2163 payments, 13 labelled fraud; validate 2018, 28 labelled fraud

coefficients (per standard deviation of the feature), largest first:
  ip_other_state    0.427
  new_device        0.396
  new_card          0.345
  foreign_card      0.295
  abroad            0.239
  n_1h              0.206
  tier1             0.182
  log_amount        0.155
  log_age_days      0.090
  no_history        0.043
  n_24h             0.021
  log_ratio        -0.008

validation average precision: 0.760  (all-zero guess: 0.014)

rule 'new device and (abroad, other state, foreign or new card)': flags 71, 22 labelled fraud, precision 31.0%, recall 78.6%
model, same 71 flags (highest scores): 28 labelled fraud, precision 39.4%, recall 100.0%

Thirteen positive examples is a small sample, so read the coefficients as a sketch: an IP in another state, a new device and a new or foreign card carry the most weight, and log_ratio carries none. The validation average precision of 0.760 flatters the model (April is the ring’s month). At equal flag volume the model finds all 28 where the rule finds 22.

4. Time the features and check for train-serve skew. The script recomputes each feature from raw facts the way a service would, in two ways: three SQL queries per payment, and history held in memory.

cat > fraud/step4_latency.py <<'EOF'
"""Step 4: what each way of getting the features costs, and whether the served features match the trained ones."""
import bisect, collections, datetime as dt, math, sqlite3, time
from fraudlib import *

model = __import__("json").load(open("fraud/model.json"))
rows = load()
test = window(rows, VALID_END, TEST_END)[:2000]
db = sqlite3.connect(DB)

def features_from(created, amount, past, dev_age, ip, issuer, first_used, tier, state, signup):
    """The same 12 features as fraudlib.load, from raw facts. `past` = (epoch seconds, amount) of earlier attempts."""
    t = dt.datetime.fromisoformat(created)
    now = t.timestamp()
    n1 = sum(1 for e, _ in past if now - e <= 3600)
    n24 = sum(1 for e, _ in past if now - e <= 86400)
    amts = sorted(a for _, a in past)
    med = (amts[len(amts) // 2] + amts[(len(amts) - 1) // 2]) / 2 if amts else None
    age = max(0, (t - dt.datetime.fromisoformat(signup)).days)
    return [n1, n24, max(0.0, math.log(amount / med)) if med else 0.0, math.log(amount / 100),
            1.0 if dev_age == 0 else 0.0, 1.0 if ip == "ABROAD" else 0.0, 1.0 if ip not in (state, "ABROAD") else 0.0,
            1.0 if issuer != "NG" else 0.0, 1.0 if (first_used == created and past) else 0.0,
            1.0 if tier == 1 else 0.0, 0.0 if past else 1.0, math.log1p(age)]

# Way A: three SQL queries per payment, as a service with no cache would do.
Q_PAST = """SELECT created_at, amount_kobo FROM transactions
            WHERE customer_id = ? AND kind = 'funding_card' AND created_at < ?"""
Q_COLS = """t.created_at, t.amount_kobo, a.device_age_days, a.ip_state, k.issuer_country, k.first_used_at,
            c.kyc_tier, c.state, c.signup_at
            FROM transactions t JOIN card_attempts a ON a.transaction_id = t.id JOIN cards k ON k.id = a.card_id
            JOIN customers c ON c.id = t.customer_id"""
Q_ROW = "SELECT " + Q_COLS + " WHERE t.id = ?"
t_row, t_past, t_feat, t_score, t_total, skew = [], [], [], [], [], 0
for r in test:
    s0 = time.perf_counter()
    row = db.execute(Q_ROW, (r.id,)).fetchone()
    s1 = time.perf_counter()
    past = [(dt.datetime.fromisoformat(c).timestamp(), a) for c, a in db.execute(Q_PAST, (r.customer, row[0]))]
    s2 = time.perf_counter()
    x = features_from(*row[:2], past, *row[2:])
    s3 = time.perf_counter()
    p = score(model, x)
    s4 = time.perf_counter()
    t_row.append(s1 - s0); t_past.append(s2 - s1); t_feat.append(s3 - s2); t_score.append(s4 - s3); t_total.append(s4 - s0)
    skew += any(abs(a - b) > 1e-9 for a, b in zip(x, r.x))

# Way B: the history held in memory, updated as each payment arrives.
mem = collections.defaultdict(list)
for r in rows:
    if r.t < VALID_END:
        mem[r.customer].append((r.t.timestamp(), r.amount))
t_mem = []
facts = {r[0]: r[1:] for r in db.execute("SELECT t.id, " + Q_COLS)}
for r in test:
    s0 = time.perf_counter()
    row = facts[r.id]
    x = features_from(*row[:2], mem[r.customer], *row[2:])
    score(model, x)
    t_mem.append(time.perf_counter() - s0)
    mem[r.customer].append((r.t.timestamp(), r.amount))

def pct(v, q):
    return sorted(v)[min(len(v) - 1, int(len(v) * q))] * 1000

print(f"{len(test)} payments from May. Milliseconds per payment on this machine (yours will differ):")
print(f"{'step':36s}{'median':>9s}{'p99':>9s}")
for name, v in [("A. SQL: the attempt's own row", t_row), ("A. SQL: the customer's earlier attempts", t_past),
                ("   compute 12 features", t_feat), ("   compute the score", t_score),
                ("A. total, SQL per payment", t_total), ("B. total, history in memory", t_mem)]:
    print(f"{name:36s}{pct(v, .5):9.3f}{pct(v, .99):9.3f}")
print(f"\nfeature vectors that differ from the training ones: {skew} of {len(test)}")

BUDGET, HOP = 50.0, 3.0
print(f"\nBudget arithmetic: {BUDGET:.0f} ms for the whole score (the chapter's design budget, not a scheme rule).")
print(f"If each of 3 features lives behind a remote call of {HOP:.0f} ms (an ASSUMPTION): serial {3 * HOP:.0f} ms, "
      f"parallel {HOP:.0f} ms; with a 99th-percentile call of 20 ms: serial {3 * 20} ms.")
EOF
python3 fraud/step4_latency.py
2000 payments from May. Milliseconds per payment on this machine (yours will differ):
step                                   median      p99
A. SQL: the attempt's own row           0.008    0.057
A. SQL: the customer's earlier attempts    0.046    0.494
   compute 12 features                  0.005    0.053
   compute the score                    0.002    0.026
A. total, SQL per payment               0.067    0.570
B. total, history in memory             0.007    0.051

feature vectors that differ from the training ones: 0 of 2000

Budget arithmetic: 50 ms for the whole score (the chapter's design budget, not a scheme rule).
If each of 3 features lives behind a remote call of 3 ms (an ASSUMPTION): serial 9 ms, parallel 3 ms; with a 99th-percentile call of 20 ms: serial 60 ms.

Your milliseconds will differ, and the 99th percentile moves between runs more than the median does. What should hold: the score is the cheapest step, the SQL lookup of the customer’s history costs the most, memory beats SQL by roughly ten times, and no feature vector differs from training. The last two lines are arithmetic on assumptions you can change, not measurements.

5. Choose the threshold by cost on April, then apply it unchanged. Test labels are the reports that had arrived by the 28 October cut-off.

cat > fraud/step5_threshold.py <<'EOF'
"""Step 5: choose the threshold by cost on April, then use it, unchanged, on May-June. Never opens answers/."""
import collections, json
from fraudlib import *

model = json.load(open("fraud/model.json"))
rows, rep = load(), reports()
valid, test = window(rows, TRAIN_END, VALID_END), window(rows, VALID_END, TEST_END)
sva, ste = [score(model, r.x) for r in valid], [score(model, r.x) for r in test]
yva = [label(r, rep, TRAIN_ASOF) for r in valid]          # what you knew on 30 June
yte = [label(r, rep) for r in test]                        # what had arrived by the 28 October cut-off

print(f"costs: missed fraud = amount + {naira(DISPUTE_FEE_KOBO)} fee; false decline = {naira(FALSE_DECLINE_KOBO)} (illustrative)")
print("\nvalidation (April), labels as known on 30 June:")
print("threshold  declined  caught  false declines  cost")
grid = [i / 1000 for i in range(2, 400, 2)]
best = min(grid, key=lambda th: (cost_kobo(valid, sva, yva, th), th))
for th in (0.005, 0.01, best, 0.05, 0.1, 0.2, 0.5):
    tp, fp, fn = confusion(valid, sva, yva, th)
    mark = "  <- cheapest" if th == best else ""
    print(f"{th:9.3f}  {tp + fp:8d}  {tp:6d}  {fp:14d}  {naira(cost_kobo(valid, sva, yva, th))}{mark}")
loss = [r.amount + DISPUTE_FEE_KOBO for r, y in zip(valid, yva) if y]
mean_loss = sum(loss) // len(loss)
print(f"mean loss per missed fraud in April: {naira(mean_loss)}; break-even probability "
      f"{FALSE_DECLINE_KOBO} / ({FALSE_DECLINE_KOBO} + {mean_loss}) = {FALSE_DECLINE_KOBO / (FALSE_DECLINE_KOBO + mean_loss):.1%}")
print(f"no model (decline nothing): {naira(sum(r.amount + DISPUTE_FEE_KOBO for r, y in zip(valid, yva) if y))}")

print(f"\nthreshold {best} applied, unchanged, to May and June (labels that had arrived by the cut-off):")
tp, fp, fn = confusion(test, ste, yte, best)
print(f"declined {tp + fp} of {len(test)} approved payments ({(tp + fp) / len(test):.1%}); caught {tp} of {tp + fn} reported frauds; "
      f"precision {tp / (tp + fp):.1%}")
print(f"cost {naira(cost_kobo(test, ste, yte, best))}; no model {naira(sum(r.amount + DISPUTE_FEE_KOBO for r, y in zip(test, yte) if y))}")
print(f"average precision on test: {average_precision(ste, yte):.3f} (validation: {average_precision(sva, yva):.3f})")

print("\ndecline rate by week at that threshold (watch for drift):")
wk = collections.defaultdict(lambda: [0, 0])
for r, s in zip(test, ste):
    k = r.t.strftime("%G-W%V")
    wk[k][0] += 1
    wk[k][1] += s >= best
for k in sorted(wk):
    print(f"  {k}  {wk[k][0]:4d} payments  {wk[k][1] / wk[k][0]:6.1%} declined")
json.dump({"threshold": best}, open("fraud/threshold.json", "w"))
EOF
python3 fraud/step5_threshold.py
costs: missed fraud = amount + ₦1,000.00 fee; false decline = ₦300.00 (illustrative)

validation (April), labels as known on 30 June:
threshold  declined  caught  false declines  cost
    0.005       522      28             494  ₦148,200.00
    0.010       252      28             224  ₦67,200.00
    0.028        64      28              36  ₦10,800.00  <- cheapest
    0.050        52      26              26  ₦31,300.00
    0.100        33      22              11  ₦54,356.00
    0.200        22      16               6  ₦88,653.00
    0.500        17      14               3  ₦93,771.00
mean loss per missed fraud in April: ₦5,750.71; break-even probability 30000 / (30000 + 575071) = 5.0%
no model (decline nothing): ₦161,020.00

threshold 0.028 applied, unchanged, to May and June (labels that had arrived by the cut-off):
declined 161 of 6099 approved payments (2.6%); caught 23 of 30 reported frauds; precision 14.3%
cost ₦117,565.00; no model ₦379,381.00
average precision on test: 0.427 (validation: 0.760)

decline rate by week at that threshold (watch for drift):
  2026-W18   263 payments    2.7% declined
  2026-W19   564 payments    1.4% declined
  2026-W20   656 payments    3.0% declined
  2026-W21   675 payments    1.9% declined
  2026-W22   744 payments    2.4% declined
  2026-W23   689 payments    2.0% declined
  2026-W24   794 payments    3.9% declined
  2026-W25   827 payments    2.8% declined
  2026-W26   778 payments    3.2% declined
  2026-W27   109 payments    1.8% declined

The cheapest threshold on April, 0.028, catches every labelled fraud and declines 36 good payments. On May and June it declines 2.6% of payments and catches 23 of 30 reported frauds. The break-even probability of 5.0% is above the chosen threshold because two April frauds score below 5%: the threshold is pinned by the lowest-scoring April fraud.

6. Open the answer key. Only now. The script counts how wrong the labels were, grades the same model against the reports and against the truth, shows which frauds it misses, and measures false declines by tier and state with 95% Wilson intervals. It ends with reason codes for the three good payments the model scored highest.

cat > fraud/step6_truth.py <<'EOF'
"""Step 6: open the answer key. Only now. Compare what you could see with what was true."""
import collections, csv, json
from fraudlib import *

truth = {int(r["transaction_id"]): (int(r["is_fraud"]), r["pattern"]) for r in csv.DictReader(open("data/answers/card_fraud_truth.csv"))}
model, best = json.load(open("fraud/model.json")), json.load(open("fraud/threshold.json"))["threshold"]
rows, rep = load(), reports()
train, test = window(rows, D(1, 1), TRAIN_END), window(rows, VALID_END, TEST_END)
fr = lambda r: truth[r.id][0]

print("1. How wrong were the labels? (approved payments)")
for name, w, asof in [("train, as known 30 Jun", train, TRAIN_ASOF), ("test, as known 30 Jun", test, TRAIN_ASOF),
                      ("test, at the 28 Oct cut-off", test, None)]:
    seen, real = sum(label(r, rep, asof) for r in w), sum(fr(r) for r in w)
    print(f"   {name:30s} labelled fraud {seen:3d}, really fraud {real:3d}, missing {real - seen:3d} ({(real - seen) / real:.0%})")
print(f"   reported but not fraud: {sum(1 for r in rows if r.id in rep and not fr(r))} (a chargeback for fraud always is one in this data)")

ste = [score(model, r.x) for r in test]
yv, yt = [label(r, rep) for r in test], [fr(r) for r in test]
print(f"\n2. The same model, graded two ways on May-June at threshold {best}")
for name, ys in [("against the reports", yv), ("against the truth", yt)]:
    tp, fp, fn = confusion(test, ste, ys, best)
    lo, hi = wilson(tp, tp + fn)
    print(f"   {name:20s} caught {tp}/{tp + fn} (recall {tp / (tp + fn):.0%}, 95% interval {lo:.0%} to {hi:.0%}), "
          f"precision {tp / (tp + fp):.1%}, average precision {average_precision(ste, ys):.3f}")

print("\n3. Which frauds does it miss? (truth, test)")
pat = collections.defaultdict(lambda: [0, 0])
for r, s in zip(test, ste):
    if fr(r):
        p = pat[truth[r.id][1]]
        p[0] += 1
        p[1] += s >= best
for k, (n, c) in sorted(pat.items()):
    print(f"   {k:18s} {c} of {n} caught")

print("\n4. False declines among the payments that were really good, by KYC tier")
good = [(r, s) for r, s in zip(test, ste) if not fr(r)]
fraud_rate = collections.defaultdict(lambda: [0, 0])
for r, s in zip(test, ste):
    fraud_rate[r.tier][0] += 1
    fraud_rate[r.tier][1] += fr(r)
for tier in (1, 2, 3):
    g = [s for r, s in good if r.tier == tier]
    k = sum(s >= best for s in g)
    lo, hi = wilson(k, len(g))
    n, f = fraud_rate[tier]
    print(f"   tier {tier}: {k:3d} of {len(g):4d} good payments declined = {k / len(g):5.1%} (95% interval {lo:.1%} to {hi:.1%}); fraud share of tier {f / n:.2%}")

print("\n5. The same by state (states with at least 250 good payments), highest first")
bs = collections.defaultdict(list)
for r, s in good:
    bs[r.state].append(s >= best)
for st, v in sorted(bs.items(), key=lambda p: -sum(p[1]) / len(p[1])):
    if len(v) >= 250:
        lo, hi = wilson(sum(v), len(v))
        print(f"   {st:9s} {sum(v):3d} of {len(v):4d} = {sum(v) / len(v):5.1%} (95% interval {lo:.1%} to {hi:.1%})")

print("\n6. Reason codes for the three highest-scoring good payments (what pushed the score up)")
for r, s in sorted(good, key=lambda p: -p[1])[:3]:
    z = standardise(model, r.x)
    contrib = sorted(((w * zi, f) for w, zi, f in zip(model["w"], z, FEATURES)), reverse=True)[:3]
    print(f"   payment {r.id}, {r.state}, tier {r.tier}, {naira(r.amount)}, score {s:.3f}: " +
          ", ".join(f"{f} (+{c:.2f})" for c, f in contrib))
EOF
python3 fraud/step6_truth.py
1. How wrong were the labels? (approved payments)
   train, as known 30 Jun         labelled fraud  13, really fraud  15, missing   2 (13%)
   test, as known 30 Jun          labelled fraud  15, really fraud  39, missing  24 (62%)
   test, at the 28 Oct cut-off    labelled fraud  30, really fraud  39, missing   9 (23%)
   reported but not fraud: 0 (a chargeback for fraud always is one in this data)

2. The same model, graded two ways on May-June at threshold 0.028
   against the reports  caught 23/30 (recall 77%, 95% interval 59% to 88%), precision 14.3%, average precision 0.427
   against the truth    caught 29/39 (recall 74%, 95% interval 59% to 85%), precision 18.0%, average precision 0.510

3. Which frauds does it miss? (truth, test)
   account_takeover   6 of 14 caught
   stolen_card        23 of 25 caught

4. False declines among the payments that were really good, by KYC tier
   tier 1: 103 of 3438 good payments declined =  3.0% (95% interval 2.5% to 3.6%); fraud share of tier 0.66%
   tier 2:  16 of 2075 good payments declined =  0.8% (95% interval 0.5% to 1.2%); fraud share of tier 0.57%
   tier 3:  13 of  547 good payments declined =  2.4% (95% interval 1.4% to 4.0%); fraud share of tier 0.73%

5. The same by state (states with at least 250 good payments), highest first
   Kaduna     20 of  288 =  6.9% (95% interval 4.5% to 10.5%)
   Oyo        12 of  452 =  2.7% (95% interval 1.5% to 4.6%)
   FCT        14 of  549 =  2.6% (95% interval 1.5% to 4.2%)
   Anambra     7 of  293 =  2.4% (95% interval 1.2% to 4.8%)
   Kano        9 of  483 =  1.9% (95% interval 1.0% to 3.5%)
   Ogun        7 of  397 =  1.8% (95% interval 0.9% to 3.6%)
   Lagos      47 of 2764 =  1.7% (95% interval 1.3% to 2.3%)
   Rivers      1 of  400 =  0.2% (95% interval 0.0% to 1.4%)

6. Reason codes for the three highest-scoring good payments (what pushed the score up)
   payment 69121, Enugu, tier 2, ₦23,813.00, score 0.492: foreign_card (+2.37), new_card (+2.04), ip_other_state (+1.37)
   payment 65378, Kaduna, tier 1, ₦46,063.00, score 0.267: foreign_card (+2.37), ip_other_state (+1.37), new_device (+0.59)
   payment 48259, Lagos, tier 1, ₦4,428.00, score 0.244: foreign_card (+2.37), ip_other_state (+1.37), new_device (+0.59)

Reports miss 23% of the real frauds at the cut-off and 62% on 30 June. Graded against the truth the same model has a lower recall (74% against 77%) and a higher precision (18.0% against 14.3%): the 9 unreported frauds count as false alarms against the reports. Account takeovers are the miss: 6 of 14 caught against 23 of 25 stolen cards. Tier 1 is declined four times as often as tier 2 for a similar fraud share.

7. Change one thing at a time. The script retrains without tier1, trains on January to April with April’s labels as of 30 April and as of 30 June, and compares a random split with the time split. It takes about 11 seconds.

cat > fraud/step7_variants.py <<'EOF'
"""Step 7: three variations on the model. Each changes one thing. Opens the answer key to grade them."""
import csv, json, random
from fraudlib import *

truth = {int(r["transaction_id"]): int(r["is_fraud"]) for r in csv.DictReader(open("data/answers/card_fraud_truth.csv"))}
rows, rep = load(), reports()
train, valid, test = window(rows, D(1, 1), TRAIN_END), window(rows, TRAIN_END, VALID_END), window(rows, VALID_END, TEST_END)
yt = [truth[r.id] for r in test]
grid = [i / 1000 for i in range(2, 400, 2)]

def run(name, cols, fit_rows, fit_labels, th_rows, th_labels):
    m = fit([[r.x[j] for j in cols] for r in fit_rows], fit_labels)
    sc = lambda rs: [score(m, [r.x[j] for j in cols]) for r in rs]
    sv, st = sc(th_rows), sc(test)
    th = min(grid, key=lambda t: (cost_kobo(th_rows, sv, th_labels, t), t))
    tp, fp, fn = confusion(test, st, yt, th)
    tiers = []
    for tier in (1, 2):
        g = [s for r, s, y in zip(test, st, yt) if r.tier == tier and not y]
        tiers.append(sum(s >= th for s in g) / len(g))
    print(f"{name:34s} AP {average_precision(st, yt):.3f}  threshold {th:.3f}  caught {tp:2d}/{tp + fn}  "
          f"false declines {fp:3d}  tier 1 {tiers[0]:.1%}, tier 2 {tiers[1]:.1%}")

all_cols = list(range(len(FEATURES)))
no_tier = [j for j, f in enumerate(FEATURES) if f != "tier1"]
ytr = [label(r, rep, TRAIN_ASOF) for r in train]
yva = [label(r, rep, TRAIN_ASOF) for r in valid]
print("graded against the truth, May-June, threshold chosen by cost on April each time\n")
run("0. the model from step 3", all_cols, train, ytr, valid, yva)
run("1. without the tier1 feature", no_tier, train, ytr, valid, yva)

# 2. Train on January-April, but with labels as they were on 30 April: April's frauds have not been reported yet.
tv = train + valid
run("2. April labels as of 30 April", all_cols, tv, [label(r, rep, D(4, 30)) for r in tv], valid, yva)
run("   same, April labels as of 30 June", all_cols, tv, [label(r, rep, TRAIN_ASOF) for r in tv], valid, yva)

# 3. A random split of January-June instead of a time split.
pool = window(rows, D(1, 1), TEST_END)
random.Random(1).shuffle(pool)
cut = int(len(pool) * 0.7)
a, b = pool[:cut], pool[cut:]
m = fit([r.x for r in a], [label(r, rep) for r in a])
sb = [score(m, r.x) for r in b]
print(f"\n3. random 70/30 split of Jan-Jun, final labels: AP on the held-out 30% = "
      f"{average_precision(sb, [label(r, rep) for r in b]):.3f}, against the truth {average_precision(sb, [truth[r.id] for r in b]):.3f}")
print(f"   (the time split's AP on May-June, against the truth: {average_precision([score(json.load(open('fraud/model.json')), r.x) for r in test], yt):.3f})")
EOF
python3 fraud/step7_variants.py
graded against the truth, May-June, threshold chosen by cost on April each time

0. the model from step 3           AP 0.510  threshold 0.028  caught 29/39  false declines 132  tier 1 3.0%, tier 2 0.8%
1. without the tier1 feature       AP 0.521  threshold 0.026  caught 31/39  false declines 131  tier 1 2.1%, tier 2 1.9%
2. April labels as of 30 April     AP 0.554  threshold 0.018  caught 29/39  false declines  67  tier 1 1.1%, tier 2 1.0%
   same, April labels as of 30 June AP 0.599  threshold 0.054  caught 29/39  false declines 120  tier 1 3.0%, tier 2 0.6%

3. random 70/30 split of Jan-Jun, final labels: AP on the held-out 30% = 0.735, against the truth 0.835
   (the time split's AP on May-June, against the truth: 0.510)

Removing tier1 narrows the tier gap (3.0% against 0.8% becomes 2.1% against 1.9%) at no visible cost in average precision. Immature April labels cost 0.045 of average precision (0.554 against 0.599) and push the threshold down, but with 39 frauds a single run cannot separate that from noise. The random split reads 0.835 where the time split reads 0.510.

8. Ask an assistant to check your work. The script prints two prompts. Paste them into a free assistant or a local model, three times each. No payment data goes in. Record what it says, and compare with what you now know.

cat > fraud/step8_prompts.py <<'EOF'
"""Step 8: print two prompts for a free assistant or a local model. No customer data: only the feature list and reason codes."""
from fraudlib import FEATURES

print("PROMPT A (feature review)")
print("A card-payment fraud score runs at authorisation. I plan to use these features: " + ", ".join(FEATURES) + ".")
print("Also considered: approval_code, three_ds, status, device_id, fraud_reported_at. Which of all these exist before the")
print("decision is made, and which leak the outcome? Answer as a table with one reason per row.")
print()
print("PROMPT B (customer message)")
print("A payment was declined by a risk model. The top reasons were: foreign_card, ip_other_state, new_device.")
print("Write two sentences for the customer in plain English, then in Nigerian Pidgin, then in Yoruba.")
print("Do not accuse the customer. Do not say which rule to avoid. Tell them how to reach a person.")
EOF
python3 fraud/step8_prompts.py
PROMPT A (feature review)
A card-payment fraud score runs at authorisation. I plan to use these features: n_1h, n_24h, log_ratio, log_amount, new_device, abroad, ip_other_state, foreign_card, new_card, tier1, no_history, log_age_days.
Also considered: approval_code, three_ds, status, device_id, fraud_reported_at. Which of all these exist before the
decision is made, and which leak the outcome? Answer as a table with one reason per row.

PROMPT B (customer message)
A payment was declined by a risk model. The top reasons were: foreign_card, ip_other_state, new_device.
Write two sentences for the customer in plain English, then in Nigerian Pidgin, then in Yoruba.
Do not accuse the customer. Do not say which rule to avoid. Tell them how to reach a person.

I did not run a model while writing this chapter, so there is no model output to quote. Check the three things in the AI box above: which columns it calls leaks, whether the Pidgin and Yoruba messages add causes the reason codes do not hold, and whether it states a recall for your model that you did not give it.

Change FALSE_DECLINE_KOBO in fraudlib.py from 30_000 to 100_000 (₦1,000) and rerun step 5. The break-even probability moves from 5.0% to 14.8%, and the cheapest threshold on April stays at 0.028, because the threshold is pinned by the score of the lowest-scoring April fraud. Then try 5_000: the break-even falls to 0.9% and the threshold still does not move. One month of validation, with the ring in it, cannot tell you what the cost estimate should be, so a threshold that does not respond to the price of a false decline is a reason to collect more months, not a reason to trust it.

ARTEFACT Write the model validation record ~60 MIN
YOU PRODUCEModel validation record (model card)

Template

# Model validation record: <model name and version>
Author <data scientist> · Validator <independent of the build> · Approver <head of risk> · Date · Status <draft / approved / approved with conditions>

## Purpose and decision
What the score decides: <approve / step up / decline>, in which product, for which client. Out of scope: <what it must not be used for>.
Who can switch it off, and what happens when it is off or late: <fallback>.

## Data and label
Training window · validation window · test window (dates, counts of payments and of labelled frauds).
Label definition: <what counts as fraud, and from which report>.
Label delay: <median, 90th percentile, share arrived after 30 and 60 days>. Label gaps: <frauds never reported, counted against the truth where known>.
Features: <list, each available at decision time>. Excluded on purpose: <list and why>.

## Out-of-time test
| Measure | Against reports | Against truth |
|---|---|---|
| Frauds caught (recall, 95% interval) | | |
| Precision | | |
| Average precision (and the baseline rule at equal volume) | | |
Why a time split, and what the validation month flatters: <...>

## Threshold and cost
Threshold <value>, chosen on <window>. Cost of a missed fraud <amount + fee>; cost of a false decline <amount, and whether it is a stated assumption>.
Cost with the model <₦> against no model <₦>. What would move the threshold: <...>

## False declines by group
| Group | Good payments declined / good payments | Rate (95% interval) | Fraud share of group |
|---|---|---|---|
What was tried to narrow a gap, and the result. What the data cannot tell: <...>

## Monitoring
<Measure, normal range, who looks, how often, what triggers a review or a switch-off.>

## Limits and how this could be wrong
<Small counts, hindsight labels, generated or thin data, one named way it could be wrong and what would show it.>

## Conditions and approval
Conditions: <what must be true before go-live, with owner and date>
Validator: <name, date, finding> · Approver: <name, date, decision>
WORKED EXAMPLE

Maryam, an engineer on Amarachi’s team at the 300-person issuer processor, writes the record for her logistic regression, version 1. An outside validator tries to break it; Amarachi, who runs fraud risk, signs.

Purpose. The score feeds the authorisation decision for a bank client’s cards: approve, step up with an OTP, or decline. This record covers the decline action only.

Data and label. Train on January to March (2,163 approved payments, 13 labelled fraud), validate on April (2,018, 28), test on May and June (6,099). A label is a first fraud report. Reports arrive a median of 27.8 days after the payment, and 60.6% are in after 30 days. On 30 June the test period showed 15 labelled frauds against 39 real, 62% missing; at the 28 October cut-off, 30 labelled and 9 missing (23%).

Test. At threshold 0.028 the model caught 23 of 30 reported frauds (recall 77%, interval 59% to 88%) and 29 of 39 real ones (74%, 59% to 85%): precision 14.3% and 18.0%, average precision 0.427 against reports, 0.510 against truth. A time split, because a random split scores 0.835; April’s 0.760 flatters. It misses account takeovers: 6 of 14 caught, against 23 of 25 stolen cards.

Threshold and cost. Chosen on April. A missed fraud costs the amount plus a ₦1,000.00 fee, a mean of ₦5,750.71 in April. A false decline costs ₦300.00, an assumption. On May and June the cost is ₦117,565.00 against ₦379,381.00 with no model.

False declines. Tier 1: 103 of 3,438 good payments (3.0%, interval 2.5% to 3.6%); tier 2: 16 of 2,075 (0.8%, 0.5% to 1.2%). The fraud share is 0.66% and 0.57%, so risk does not explain the gap.

Monitoring. The weekly decline rate (1.4% to 3.9% in the test), read each Monday by Maryam; a week outside that range opens a review.

How this could be wrong. The 74% rests on 39 frauds. A fall in recall once the next months’ reports arrive would show it.

Approval. Amarachi approves with one condition: the validator and Maryam agree what to do about the tier gap before go-live.

Now you

A month later, Maryam has a second candidate: the model retrained without the tier1 feature (step 7, variant 1). The bank client’s compliance team has asked for the false-decline rates by group before go-live in two weeks, and the validator wants a record they can sign without asking anyone for more.

You are the data scientist. Write the validation record for the new version. Use step 6’s tier and state tables for the old model and step 7’s variant 1 for the new one: average precision 0.521, 31 of 39 caught, tier 1 declined 2.1% and tier 2 1.9%. Step 7 prints no intervals for the new model, so work them out (the good payments per tier are step 6’s counts) or say they are missing. Decide what you say about Kaduna and about the ₦300 assumption. Your readers are the independent validator, then Amarachi as head of fraud risk; the record supports her decision on whether version 2 replaces version 1 at go-live.

Self-check

DECIDE

Maryam's model is ready for a bank client's go-live. Validation shows the model catches 74% of frauds on a later period, at a cost far below declining nothing. Amarachi has also seen that good tier 1 payments are declined 3.0% of the time against 0.8% for tier 2, while the fraud share is 0.66% against 0.57%. Removing the tier feature narrows the gap to 2.1% against 1.9% on 39 frauds, which cannot show a loss. The go-live date is in two weeks and the bank's compliance team has asked for the false-decline rates by group.

READING
  1. PAPER
    Credit card fraud detection: a realistic modeling and a novel learning strategy Dal Pozzolo, Boracchi, Caelen, Alippi and Bontempi, 2018

    IEEE TNNLS 29(8), written with an industrial partner. Search summaries say it treats class imbalance, concept drift and verification latency together and trains separately on alert feedback and on delayed samples. Read it for the label delay this chapter measures. Skip the experiments tables on a first pass. Read: the problem formulation, and the sections on delayed samples and the learning strategy.

  2. DOC
    SR 26-2: Revised Guidance on Model Risk Management Board of Governors of the Federal Reserve System, 2026

    The current US supervisory letter on model risk, dated 17 April 2026, which supersedes SR 11-7. Read its scope and its definition of a model first. It is guidance for US banks, so use it as a comparison for validation and monitoring practice.

  3. DOC
    SS1/23: Model risk management principles for banks Prudential Regulation Authority, Bank of England, 2023

    Five principles for UK banks, from model identification to risk mitigants. Read the validation and mitigants principles against the group table in step 6. This build saw only summaries of it, so check the scope in the document.

  4. DOC
    EU AI Act, Annex III: high-risk AI systems European Commission, AI Act Service Desk, 2024

    The list of high-risk uses. Read point 5(b) for the credit-scoring entry and its fraud exception. Commentary disagrees on how far the exception reaches and on application dates, so treat summaries with care.

  5. DOC
    Nigeria Data Protection Act 2023 Federal Republic of Nigeria (hosted by the Nigeria Data Protection Commission), 2023

    The gazetted Act. Read section 37 on automated decisions in Part VI before you decline customers by software. This build could not open the text, so check the exceptions and subsection numbers.

  6. DOC
    Reviewed and Approved Guidelines on Operations of Electronic Payment Channels in Nigeria 2020 Central Bank of Nigeria, 2020

    The CBN's guidelines covering ATMs, POS, mobile POS and web acceptance. Search summaries show it covers acquirer licensing and dispute timelines, and this build confirmed no provision on fraud scoring. Read it for any monitoring and liability duties that apply to your card business.

  7. DOC
    A primer on machine learning for fraud detection (vendor guide) Stripe, 2021

    A vendor's guide to its own system, labelled as such. Search summaries say it covers precision-recall curves, score distributions and feature engineering. An older edition, so it may not match the current product. Read it for vocabulary and for how a vendor frames the false-positive trade-off, and treat any performance claim as the vendor's own.

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: Payment messages: ISO 8583 and ISO 20022 →