Skip to content

Fraud, Credit and Financial NLP

Beyond stock trading and portfolio allocation, the quiet majority of machine learning deployed across global banks and payment networks runs behind everyday loans, card swipes, and earnings transcripts. This file examines how lenders estimate credit default risk and survival times, how real-time fraud pipelines combine streaming velocity features with Graph Neural Networks under extreme class imbalance, how financial Transformers extract market signals from corporate language and alternative data, and why strict regulatory laws require Shapley explainability, counterfactual recourse, and fairness audits.

  • Picture a neighbourhood grocer deciding which regular shoppers may run a monthly tab. She quietly weighs steady wages against unpaid bills, notices if someone suddenly buys ten crates of champagne at midnight using a borrowed card, and listens carefully when a local factory manager hints that overtime shifts are drying up. Modern banking AI performs those exact three judgements at planetary scale across billions of transactions and documents every week, subject to millisecond latency limits and strict legal accountability.

Credit Scoring and Default Risk

  • Whenever a bank issues a mortgage, credit card, or business loan, its core financial exposure is summarised by Expected Loss (EL), broken into three distinct components.
\[\text{EL} = \text{PD} \times \text{LGD} \times \text{EAD}\]
  • Here Probability of Default (PD) is the chance the borrower fails to repay within a horizon (commonly 12 months), Loss Given Default (LGD) is the fraction of the loan still lost after selling collateral or recovering funds, and Exposure at Default (EAD) is the balance owed at the moment default strikes. Machine learning focuses most heavily on predicting \(\text{PD}\) accurately.

Logistic Regression Scorecards vs Gradient Boosted Trees

  • For decades, consumer credit bureaus and retail banks relied on logistic regression scorecards (Chapter 06). Continuous variables such as age, income, and credit utilisation are grouped into discrete bins and converted via Weight of Evidence (WoE) encoding into log-odds ratios. Because the predicted default log-odds are strictly linear in the binned features,
\[\log \frac{p}{1 - p} = \beta_0 + \sum_{j=1}^{d} \beta_j x_j\]
  • Every feature bin maps transparently to an integer number of score points (for instance, adding 35 points for five years of clean payment history or subtracting 40 points for a missed mortgage instalment). Risk committees and regulators love scorecards because every weight is auditable by eye.

  • Modern digital lenders increasingly deploy Gradient Boosted Decision Trees (GBDTs) such as XGBoost and LightGBM (Chapter 06). Trees naturally capture rich non-linear interactions that additive scorecards miss, such as recognising that a £40,000 debt load is benign for a high-earning surgeon yet dangerous for a seasonal worker. To stay compliant with common sense and banking supervision, practitioners attach monotonicity constraints forcing predicted default risk never to decrease when missed payments go up.

Survival Analysis for Time-to-Default

  • A binary classifier asks whether a borrower defaults within 12 months, throwing away valuable timing information. A loan that defaults in month 2 costs the bank far more interest income than one that pays faithfully for four years before stumbling in month 49. Worse, half the active loans in a bank's training database have not finished their term yet, making them right-censored observations (we know they survived up to today, not what happens tomorrow).

  • Survival analysis models the full time-to-default distribution \(T\) using the survival function \(S(t) = \mathbb{P}(T > t)\) and the hazard rate \(h(t)\), the instantaneous probability of defaulting right at time \(t\) given survival up to \(t\). The workhorse Cox Proportional Hazards model separates a shared macroeconomic baseline hazard \(h_0(t)\) from borrower-specific risk features \(\mathbf{x}\).

\[h(t \mid \mathbf{x}) = h_0(t) \exp\!\left(\boldsymbol{\beta}^T \mathbf{x}\right)\]
  • Survival models seamlessly incorporate right-censored loans into their partial likelihood, letting banks forecast lifetime expected credit losses (required under accounting standards IFRS 9 and CECL) across changing economic cycles.

Probability Calibration

  • Ranking risky borrowers above safe borrowers (high ROC-AUC) is only half the battle when pricing loans. Suppose a bank charges 6% interest assuming a cohort's default probability is 3%, yet the model's uncalibrated tree scores actually correspond to a 9% real-world default rate. The bank loses money on every loan even if its AUC looks impressive.

  • A classifier is well-calibrated when events assigned predicted probability \(\hat{p} \approx 0.10\) genuinely occur roughly 10% of the time. Practitioners diagnose miscalibration using reliability diagrams and the Brier score \(\frac{1}{n}\sum_i (\hat{p}_i - y_i)^2\), then apply post-hoc calibration such as Platt scaling (fitting a logistic curve on validation logits) or isotonic regression before translating scores into interest rates and capital reserves.

Real-Time Fraud Detection

  • Credit underwriting can take seconds or minutes, whereas card-payment fraud scoring must reach a verdict inside 30 to 50 milliseconds before a shopper even pulls their contactless card away from a coffee-shop terminal.

Extreme Class Imbalance and Cost-Sensitive Thresholding

  • Across healthy payment networks, genuine fraud accounts for roughly 0.1% of transactions (about one in every thousand swipes). Under this extreme skew, classification accuracy is completely useless. A lazy dummy script that stamps "Legitimate" on every single transaction boasts 99.9% accuracy while haemorrhaging millions of pounds to criminals.

  • Fraud teams instead evaluate models with Precision (of the transactions we blocked, how many were truly fraudulent?), Recall (of all real fraud attacks, what share did we stop?), and the Precision-Recall Area Under the Curve (PR-AUC), which zooms straight into the rare positive class without letting 999,000 easy true negatives inflate the score.

  • Picking the decision threshold \(\tau\) is an explicit economic optimisation. Every missed fraud (false negative) costs the principal stolen plus chargeback fees \(C_{\text{FN}}\), whereas every falsely declined legitimate customer (false positive) causes embarrassment, call-centre overhead, and customer churn \(C_{\text{FP}}\). Rather than defaulting blindly to \(\tau = 0.5\), systems route medium-risk transactions to step-up authentication (such as a banking app biometric prompt) and block outright only when expected fraud loss outweighs customer friction.

Streaming Velocity Features and Delayed Labels

  • A stolen card number looks perfectly ordinary on a static spreadsheet row until you inspect its behaviour over time. Connecting directly to the online feature stores and streaming pipelines from Chapter 21, real-time fraud engines maintain sliding time windows in low-latency in-memory stores (such as Redis or Apache Flink) to compute velocity features on the fly.

  • Burst counts and spend spikes track how many transactions occurred in the last 60 seconds, 10 minutes, and 24 hours, plus the ratio of the current basket size to the cardholder's 30-day average.

  • Geo-velocity compares the physical distance and elapsed time since the previous card swipe, immediately flagging an "impossible travel" jump from London to Singapore inside twenty minutes.

  • Delayed feedback handling confronts a subtle operational trap from Chapter 21. Legitimate customers often do not spot a sneaky stolen-card charge until their monthly statement arrives, meaning confirmed chargeback labels trickle in 30 to 90 days late. Retraining pipelines must carefully separate immature recent transactions from matured labelled windows so unconfirmed fraud is never mistakenly treated as clean training data.

Real-time fraud detection architecture combining live streaming velocity features from an online feature store with a heterogeneous entity graph and GNN message passing to expose coordinated fraud rings under a 50 millisecond latency budget

Graph Neural Networks Catching Coordinated Fraud Rings

  • Professional cybercriminals rarely operate single isolated accounts. Instead, they run coordinated fraud rings and money-mule networks using dozens of synthetic identities that look squeaky-clean individually when inspected one row at a time. What betrays them is shared hidden infrastructure, such as five unrelated newly opened accounts logging in from the same handset fingerprint, shipping electronics to the same drop-box address, or rotating through the same proxy IP subnet.

  • Modelling accounts, cards, devices, merchants, and IP addresses as a heterogeneous entity graph brings Graph Neural Networks (Chapter 15) straight into the defence stack. At each message-passing layer \(l\), every node \(v\) updates its hidden risk embedding \(\mathbf{h}_v\) by aggregating representations from its graph neighbours \(\mathcal{N}(v)\).

\[\mathbf{h}_v^{(l+1)} = \sigma\!\left(W_0 \mathbf{h}_v^{(l)} + \sum_{u \in \mathcal{N}(v)} \frac{1}{|\mathcal{N}(v)|} W_1 \mathbf{h}_u^{(l)}\right)\]
  • After two hops of message passing, suspicion attached to one confirmed mule account automatically flows through a shared device node to flag its accomplices before they drain credit lines. Production banks run inductive neighbour-sampling GNNs (such as GraphSAGE) to refresh node embeddings continuously and feed those graph risk scores alongside streaming velocity features into the sub-50-millisecond decision engine.

Financial NLP and Alternative Data

  • Numbers in quarterly balance sheets tell you what already happened last month. Words spoken by executives and physical signals observed across the real economy often hint at what is about to happen next.

Domain-Adapted Transformers for Corporate Language

  • General-purpose sentiment dictionaries stumble badly on financial text. Words like "liability", "depreciation", "tax", or "exposure" look negative to a movie-review classifier, yet appear routinely in upbeat insurance and accounting filings. Conversely, polite corporate hedging such as "we are experiencing modest headwinds in enterprise renewal cycles" signals serious trouble to an experienced analyst.

  • Transformers (Chapter 07) pre-trained or fine-tuned on financial corpora, pioneered by FinBERT and extended by modern domain-adapted large language models, read context deeply across four major text streams.

  • Earnings call transcripts capture not just prepared management scripts, but unscripted Q&A exchanges where hesitant wording or sudden evasiveness from a chief financial officer correlates strongly with future earnings misses.

  • Regulatory filings (SEC 10-K and 10-Q) span hundreds of pages. Comparing subtle wording edits inside the "Risk Factors" section between consecutive quarters frequently reveals emerging supply-chain or litigation risks well before headlines break.

  • Central bank communications and breaking news wires move bond yields and currencies within seconds. Models classify policy statements along a hawkish-versus-dovish spectrum to gauge whether interest-rate rises are becoming more likely.

  • Two strict engineering safeguards govern financial NLP. First, practitioners must prevent look-ahead contamination by ensuring historical backtests never evaluate a language model whose pre-training weights already memorised future news articles. Second, production research desks pair LLMs with Retrieval-Augmented Generation (RAG) grounded strictly in cited filings to eliminate fabricated numbers.

Alternative Data Signals

  • Quantitative hedge funds also look beyond financial exchanges altogether to alternative data, non-traditional measurements of real-world economic activity.

  • Computer vision on satellite imagery (Chapter 08) counts parked cars outside retail superstores to forecast quarterly sales, measures shadows cast inside floating-roof crude oil storage tanks to estimate global supply, and monitors infrared vegetation health across farmland to predict grain harvests.

  • Digital exhaust and web signals aggregate anonymised credit-card receipt panels, app download velocity, shipping vessel GPS transponders (AIS) tracking port congestion, and engineering job-posting surges hinting at unannounced product launches.

  • Alternative datasets rarely stay magical forever. They typically carry short historical spans (making overfitting dangerously easy), suffer alpha decay and crowding once competing funds purchase the same vendor feed, and demand careful legal vetting around consumer privacy and material non-public information.

Regulatory Explainability and Fairness

  • If a movie recommender suggests a bad comedy, nobody calls a lawyer. If a bank's neural network rejects a family's mortgage application, strict consumer-protection laws step in immediately. Regulations including the US Equal Credit Opportunity Act (ECOA), the EU AI Act (which classifies credit scoring as high-risk AI), and the UK FCA Consumer Duty legally entitle declined applicants to clear, accurate adverse action notices stating the principal reasons behind the decision.

Shapley Values and SHAP

  • How can you assign fair blame or credit to each input feature inside a complex non-linear model like a 500-tree GBDT? SHAP (SHapley Additive exPlanations) borrows Lloyd Shapley's Nobel-winning solution from cooperative game theory (1953).

  • Imagine five friends teaming up to win a pub quiz prize of £100 and debating how to split the winnings fairly. Shapley proved there is one unique fair payout rule. Check how much extra score player \(i\) adds when joining every possible subset (coalition) \(S\) of the other teammates, and take a weighted average across all orderings. Translating players into input features \(F = \{1, \dots, d\}\) and prize money into model output \(f(\mathbf{x})\) gives the Shapley value \(\phi_i\).

\[\phi_i(f, \mathbf{x}) = \sum_{S \subseteq F \setminus \{i\}} \frac{|S|!\,(|F| - |S| - 1)!}{|F|!} \left[ f_S(\mathbf{x}_{S \cup \{i\}}) - f_S(\mathbf{x}_S) \right]\]
  • Here \(f_S(\mathbf{x}_S)\) denotes the expected model prediction when only features in coalition \(S\) are known and missing features are marginalised out. Shapley values satisfy four coveted axioms (efficiency, symmetry, dummy, and additivity). In particular, efficiency guarantees that every feature's contribution sums exactly to the gap between the baseline population average and this individual applicant's prediction.
\[f(\mathbf{x}) = \mathbb{E}[f(\mathbf{X})] + \sum_{i=1}^{d} \phi_i\]
  • Naive enumeration scales as \(O(2^d)\), which becomes slow beyond twenty features, yet Lundberg et al.'s TreeSHAP algorithm exploits tree path structure to compute exact Shapley values for gradient boosted ensembles in polynomial time. Banks rank the largest positive \(\phi_i\) risk drivers to generate legally defensible adverse action reason codes.

SHAP waterfall chart decomposing a declined credit applicant default probability from baseline 0.14 to final 0.41 across five features, paired with adverse action reason codes, counterfactual recourse guidance, and a disparate-impact fairness audit

Counterfactual Explanations

  • Knowing "your debt-to-income ratio added +0.18 to your default probability" explains the past, yet a rejected customer naturally asks a more practical question. "What is the smallest realistic change I could make so you approve me next time?"

  • Counterfactual explanations answer this directly by solving a constrained distance-minimisation problem for a nearby hypothetical profile \(\mathbf{x}'\) that flips the model's decision across approval threshold \(\tau\).

\[\mathbf{x}^* = \arg\min_{\mathbf{x}'} \; d(\mathbf{x}, \mathbf{x}') \qquad \text{subject to} \quad f(\mathbf{x}') \le \tau, \quad \mathbf{x}' \in \mathcal{A}(\mathbf{x})\]
  • The actionability constraint \(\mathcal{A}(\mathbf{x})\) is vital in human terms. Telling an applicant to lower their debt-to-income ratio from 52% to 36% by clearing a credit card is genuinely helpful algorithmic recourse, whereas telling them to become ten years younger or change their birthplace is absurd and unlawful.

Disparate-Impact Fairness Audits

  • A tempting naive instinct is "fairness through unawareness", simply deleting sensitive columns like gender, ethnicity, or age from the training table. In reality, rich financial data brims with proxy variables. Postcodes, university names, shopping categories, and phone models correlate tightly with protected demographics, letting expressive trees reconstruct historical lending biases right through the back door.

  • Responsible institutions therefore run rigorous fairness audits before and after deployment (connecting directly to Chapter 21 slice-based monitoring).

  • Disparate Impact Ratio (the Four-Fifths Rule) compares approval rates between an unprivileged group (\(A = 0\)) and a reference group (\(A = 1\)), flagging potential indirect discrimination whenever the ratio dips below 0.80.

\[\text{DI} = \frac{\mathbb{P}(\hat{Y} = 1 \mid A = 0)}{\mathbb{P}(\hat{Y} = 1 \mid A = 1)} \ge 0.80\]
  • Equal opportunity and group calibration look deeper, verifying that genuinely creditworthy borrowers enjoy comparable true approval rates across demographic slices and that a predicted 10% default probability means the exact same empirical risk for every community.

  • As we leave Chapter 22, notice how finance compresses almost every mathematical thread of this compendium into one high-stakes arena. Linear algebra, probability, deep sequence models, graph networks, low-latency systems engineering, and cooperative game theory must all work together under unforgiving economic reality and human accountability.

Take-Home

  • Credit risk models balance accuracy, timing, and calibration, pairing expected loss (\(\text{PD} \times \text{LGD} \times \text{EAD}\)) with survival analysis for right-censored loans and probability calibration so interest rates reflect real-world default frequencies.
  • Extreme 0.1% fraud imbalance renders accuracy meaningless, pushing real-time payment engines toward PR-AUC, cost-sensitive thresholds, sub-50-millisecond streaming velocity features, and delayed-chargeback training pipelines.
  • Graph Neural Networks uncover coordinated fraud rings by passing risk messages across shared devices, IP addresses, and shipping drop-boxes that single-row tabular models cannot see.
  • Financial Transformers and alternative data turn unstructured language and physical observations into forecasts, provided engineers guard rigorously against look-ahead bias, hallucinations, and signal crowding.
  • Lawful lending demands transparent accountability, uniting game-theoretic SHAP attributions for adverse action notices, actionable counterfactual recourse for applicants, and disparate-impact audits that catch hidden proxy discrimination.

Coding Tasks (use CoLab or notebook)

  1. Simulate an imbalanced fraud dataset (1% fraud rate) driven by streaming velocity and spend-spike features. Show why a trivial all-zero baseline reaches 99% accuracy with 0% recall, train a class-weighted logistic model in JAX, plot the Precision-Recall curve, and choose the cost-optimal decision threshold.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # 4,000 transactions with 1% fraud: [txns_last_5min, spend_ratio, geo_velocity]
    k1, k2, k3 = jax.random.split(jax.random.PRNGKey(12), 3)
    k4, k5, k6 = jax.random.split(jax.random.PRNGKey(99), 3)
    n_legit, n_fraud = 3960, 40
    X_legit = jnp.stack([jax.random.normal(k1, (n_legit,)) * 0.8 + 1.0,
                         jax.random.normal(k2, (n_legit,)) * 0.6 + 1.0,
                         jax.random.normal(k3, (n_legit,)) * 0.7 + 0.2], axis=1)
    X_fraud = jnp.stack([jax.random.normal(k4, (n_fraud,)) * 1.1 + 3.4,
                         jax.random.normal(k5, (n_fraud,)) * 1.1 + 3.1,
                         jax.random.normal(k6, (n_fraud,)) * 1.2 + 2.6], axis=1)
    X_raw = jnp.concatenate([X_legit, X_fraud], axis=0)
    X = (X_raw - jnp.mean(X_raw, axis=0)) / (jnp.std(X_raw, axis=0) + 1e-6)
    y = jnp.concatenate([jnp.zeros(n_legit), jnp.ones(n_fraud)], axis=0)
    
    # Class-weighted binary cross-entropy (separate w, b args for Pyodide-safe jax.grad)
    def loss_fn(w, b):
        p = jax.nn.sigmoid(X @ w + b)
        bce = -(25.0 * y * jnp.log(p + 1e-6) + (1.0 - y) * jnp.log(1.0 - p + 1e-6))
        return jnp.mean(bce) + 1e-3 * jnp.sum(w ** 2)
    
    grad_fn = jax.grad(loss_fn, argnums=(0, 1))
    w, b = jnp.zeros(3), jnp.array([-2.0])
    for _ in range(250):
        gw, gb = grad_fn(w, b)
        w, b = w - 0.15 * gw, b - 0.15 * gb
    
    scores = jax.nn.sigmoid(X @ w + b)
    thresholds = jnp.linspace(0.05, 0.99, 80)
    precs, recs, costs = [], [], []
    for tau in thresholds:
        pred = (scores >= tau).astype(jnp.float32)
        tp = float(jnp.sum((pred == 1) & (y == 1)))
        fp = float(jnp.sum((pred == 1) & (y == 0)))
        fn = float(jnp.sum((pred == 0) & (y == 1)))
        precs.append(tp / (tp + fp + 1e-8)); recs.append(tp / (tp + fn + 1e-8))
        costs.append(500.0 * fn + 15.0 * fp)  # Missed fraud = £500, false decline = £15
    
    best_i = int(jnp.argmin(jnp.array(costs)))
    order = jnp.argsort(jnp.array(recs))
    r_s, p_s = jnp.array(recs)[order], jnp.array(precs)[order]
    pr_auc = float(jnp.sum((r_s[1:] - r_s[:-1]) * 0.5 * (p_s[1:] + p_s[:-1])))
    
    print(f"Dummy all-zero -> Accuracy: {float(jnp.mean(y == 0)):.2%}, Recall: 0.0%, Loss: £{500*n_fraud:,.0f}")
    print(f"Fraud Model    -> PR-AUC: {pr_auc:.3f}, Opt tau: {float(thresholds[best_i]):.2f}, "
          f"Prec: {precs[best_i]:.1%}, Rec: {recs[best_i]:.1%}, Cost: £{costs[best_i]:,.0f}")
    
    fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.9))
    axes[0].plot(r_s, p_s, color="#3498db", lw=2.5, label=f"PR-AUC = {pr_auc:.3f}")
    axes[0].scatter([recs[best_i]], [precs[best_i]], color="#e74c3c", s=80, zorder=5, label="Cost-optimal")
    axes[0].set_xlabel("Recall"); axes[0].set_ylabel("Precision")
    axes[0].set_title("Precision-Recall Curve (1% Fraud)"); axes[0].legend(); axes[0].grid(alpha=0.3)
    axes[1].plot(thresholds, costs, color="#9b59b6", lw=2.2)
    axes[1].axvline(float(thresholds[best_i]), color="#e74c3c", ls="--", label=f"tau = {float(thresholds[best_i]):.2f}")
    axes[1].set_xlabel("Threshold tau"); axes[1].set_ylabel("Expected Total Cost (£)")
    axes[1].set_title("Cost-Sensitive Threshold Choice"); axes[1].legend(); axes[1].grid(alpha=0.3)
    plt.tight_layout(); plt.show()
    

  2. Catch a coordinated fraud ring with a 2-hop Graph Neural Network versus a tabular node-only classifier. Build 24 accounts where 5 ring members share compromised devices, yet 3 mule accounts look innocent individually, and watch message passing expose the ring.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    N = 24  # Accounts 0..18 legitimate, 19..23 form a 5-account fraud ring
    y_true = jnp.array([0.0] * 19 + [1.0] * 5)
    X_base = jax.random.normal(jax.random.PRNGKey(2026), (N, 2)) * 0.45
    ring_sig = jnp.array([[0.0, 0.0]] * 19 + [[2.6, 2.2], [2.4, 2.0], [0.2, 0.1], [0.1, 0.2], [0.15, 0.1]])
    X_node = X_base + ring_sig
    
    # Symmetric shared-device / IP adjacency built with pure Python lists -> jnp.array
    adj_rows = [[1.0 if i == j else 0.0 for j in range(N)] for i in range(N)]
    for u, v in [(0, 1), (4, 5), (9, 10), (14, 15), (19, 20), (19, 21), (20, 22), (21, 22), (21, 23), (22, 23), (20, 23)]:
        adj_rows[u][v] = 1.0; adj_rows[v][u] = 1.0
    A = jnp.array(adj_rows)
    A_norm = A / jnp.sum(A, axis=1, keepdims=True)
    train_mask = jnp.array([1.0] * 8 + [0.0] * 11 + [1.0] + [0.0] * 4)
    
    def fit_linear(features, steps=200, lr=0.25):
        def loss(w, b):
            p = jax.nn.sigmoid(features @ w + b)
            bce = -(y_true * jnp.log(p + 1e-6) + (1.0 - y_true) * jnp.log(1.0 - p + 1e-6))
            return jnp.sum(bce * train_mask) / jnp.sum(train_mask) + 0.02 * jnp.sum(w ** 2)
        gfn = jax.grad(loss, argnums=(0, 1))
        w, b = jnp.zeros(features.shape[1]), jnp.array([0.0])
        for _ in range(steps):
            gw, gb = gfn(w, b)
            w, b = w - lr * gw, b - lr * gb
        return jax.nn.sigmoid(features @ w + b)
    
    H_gnn = jnp.concatenate([X_node, A_norm @ X_node, A_norm @ (A_norm @ X_node)], axis=1)
    p_tab, p_gnn = fit_linear(X_node), fit_linear(H_gnn)
    
    print("Hidden mule scores [21, 22, 23] -> Tabular:", [round(float(p_tab[i]), 3) for i in [21, 22, 23]],
          "| GNN:", [round(float(p_gnn[i]), 3) for i in [21, 22, 23]])
    print(f"Full ring recall at 0.5 -> Tabular: {float(jnp.mean(p_tab[19:] > 0.5)):.0%} | GNN: {float(jnp.mean(p_gnn[19:] > 0.5)):.0%}")
    
    fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.9))
    idx = jnp.arange(N)
    axes[0].bar(idx - 0.18, p_tab, width=0.36, color="#3498db", alpha=0.8, label="Tabular (row only)")
    axes[0].bar(idx + 0.18, p_gnn, width=0.36, color="#e74c3c", alpha=0.85, label="2-Hop GNN")
    axes[0].axvspan(18.5, 23.5, color="#e74c3c", alpha=0.1, label="True Fraud Ring")
    axes[0].axhline(0.5, color="#333", ls="--", lw=1)
    axes[0].set_xlabel("Account ID"); axes[0].set_ylabel("Fraud Risk Score")
    axes[0].set_title("GNN Exposes Mule Accounts via Shared Devices"); axes[0].legend(fontsize=8); axes[0].grid(alpha=0.3)
    axes[1].imshow(A, cmap="Purples")
    axes[1].set_xlabel("Account ID"); axes[1].set_ylabel("Account ID"); axes[1].set_title("Shared-Device Adjacency Matrix")
    plt.tight_layout(); plt.show()
    

  3. Compute exact Shapley values (SHAP) across all \(2^4 = 16\) coalitions per feature for a declined credit applicant, verify the efficiency identity \(\sum_i \phi_i = f(\mathbf{x}) - \mathbb{E}[f(\mathbf{X})]\), and run projected gradient descent in JAX to find a minimal actionable counterfactual.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    import math
    
    names = ["Debt-to-Income", "Missed Payments", "Short Credit File", "Job Tenure", "Savings Ratio"]
    weights, bias = jnp.array([2.4, 0.95, 1.1, -0.18, -1.6]), jnp.array(-2.2)
    predict_pd = lambda x: jax.nn.sigmoid(jnp.dot(x, weights) + bias)
    
    x_base = jnp.array([0.28, 0.30, 0.30, 5.0, 0.30])
    x_app  = jnp.array([0.55, 2.00, 0.85, 7.0, 0.45])
    cutoff, d = 0.30, len(names)
    base_pd, app_pd = float(predict_pd(x_base)), float(predict_pd(x_app))
    
    # Exact Shapley values via cooperative game coalition enumeration
    shap_vals = []
    for i in range(d):
        others = [j for j in range(d) if j != i]
        phi_i = 0.0
        for mask in range(1 << (d - 1)):
            S = [others[bit] for bit in range(d - 1) if (mask >> bit) & 1]
            coeff = math.factorial(len(S)) * math.factorial(d - len(S) - 1) / math.factorial(d)
            x_S  = jnp.where(jnp.array([1.0 if j in S else 0.0 for j in range(d)]) > 0.5, x_app, x_base)
            x_Si = jnp.where(jnp.array([1.0 if (j in S or j == i) else 0.0 for j in range(d)]) > 0.5, x_app, x_base)
            phi_i += coeff * (float(predict_pd(x_Si)) - float(predict_pd(x_S)))
        shap_vals.append(phi_i)
    
    print(f"Baseline PD: {base_pd:.4f} | Applicant PD: {app_pd:.4f} (Cutoff {cutoff:.2f} -> DECLINED)")
    print(f"Efficiency check -> Base + sum(SHAP) = {base_pd + sum(shap_vals):.4f} vs f(x) = {app_pd:.4f}")
    
    # Actionable counterfactual: only Debt-to-Income (0) and Savings Ratio (4) can change right now
    action_mask = jnp.array([1.0, 0.0, 0.0, 0.0, 1.0])
    def cf_loss(x_cf):
        return 40.0 * jnp.maximum(0.0, predict_pd(x_cf) - (cutoff - 0.03)) ** 2 + jnp.sum(((x_cf - x_app) * action_mask) ** 2)
    
    grad_cf, x_cf = jax.grad(cf_loss), x_app.copy()
    lo, hi = jnp.array([0.10, 0.0, 0.0, 0.0, 0.05]), jnp.array([0.90, 10.0, 1.0, 40.0, 0.90])
    for _ in range(250):
        x_cf = jnp.clip(x_cf - 0.05 * grad_cf(x_cf) * action_mask, lo, hi)
    
    print(f"Counterfactual -> DTI {float(x_app[0]):.2f} -> {float(x_cf[0]):.2f}, Savings {float(x_app[4]):.2f} -> {float(x_cf[4]):.2f} | New PD: {float(predict_pd(x_cf)):.4f}")
    
    plt.figure(figsize=(8.0, 3.9))
    plt.barh(names[::-1], shap_vals[::-1], color=["#e74c3c" if v > 0 else "#27ae60" for v in shap_vals[::-1]], alpha=0.85)
    plt.axvline(0.0, color="#333", lw=1.0)
    plt.xlabel("SHAP Contribution to Default Probability (phi_i)")
    plt.title(f"Exact Shapley Explanation (Base {base_pd:.2f} -> Applicant {app_pd:.2f}, Cutoff {cutoff:.2f})")
    plt.grid(axis="x", alpha=0.3); plt.tight_layout(); plt.show()