github-actions[bot] commited on
Commit ·
b025087
1
Parent(s): f38e611
Deploy 3429bb9: Read the counterparty, not just the amount: provider-level transaction analysis
Browse filesFiles changed (3)
- db/schema.sql+19
- src/features.py+62-42
- src/merchant_intelligence.pyAdded+225
127 unmodified lines128129130131132133127 unmodified linesgambling_ratio REAL NOT NULL DEFAULT 0,months_without_income_ratio REAL NOT NULL DEFAULT 0,FOREIGN KEY(user_id) REFERENCES users(user_id));127 unmodified lines128129130131132133134135136137138139140141142143144145146147148149150151152127 unmodified linesgambling_ratio REAL NOT NULL DEFAULT 0,months_without_income_ratio REAL NOT NULL DEFAULT 0,-- Counterparty analysis: who the money goes to. On real defaults the share of-- outflow reaching other credit providers was the strongest single signal-- obtainable from a transaction feed.credit_provider_ratio REAL NOT NULL DEFAULT 0,distinct_credit_providers INTEGER NOT NULL DEFAULT 0,bnpl_ratio REAL NOT NULL DEFAULT 0,high_cost_credit_ratio REAL NOT NULL DEFAULT 0,payday_or_collections_flag INTEGER NOT NULL DEFAULT 0,salary_advance_flag INTEGER NOT NULL DEFAULT 0,crypto_ratio REAL NOT NULL DEFAULT 0,overdraft_fee_events INTEGER NOT NULL DEFAULT 0,fee_escalation REAL NOT NULL DEFAULT 0,max_purchase_months REAL NOT NULL DEFAULT 0,large_purchase_count INTEGER NOT NULL DEFAULT 0,purchase_spike_ratio REAL NOT NULL DEFAULT 0,merchant_diversity INTEGER NOT NULL DEFAULT 0,recurring_commitment_ratio REAL NOT NULL DEFAULT 0,has_merchant_descriptions INTEGER NOT NULL DEFAULT 0,FOREIGN KEY(user_id) REFERENCES users(user_id));
7 unmodified lines8910111213102 unmodified lines116117118119120121122267 unmodified lines390391392393394395167 unmodified lines5635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166177 unmodified lines# Import universal behavioural signalssys.path.append(str(Path(__file__).resolve().parent))import universal_signalsdef get_historical_balances(cursor, user_ids, snapshot_date):"""Reconstructs the account balances for a set of users at a specific snapshot_date.102 unmodified lines# 3. Fetch Transactions prior to snapshot_date (up to 90 days prior for aggregations)date_90d_prior = snapshot_date - datetime.timedelta(days=90)cursor.execute(f"""SELECT user_id, account_id, transaction_date, amount, category, is_failedFROM transactionsWHERE user_id IN ({user_ids_str})AND transaction_date >= ?267 unmodified linesif len(inc_by_month) > 0:months_without_income_ratio = float((inc_by_month <= 0).mean())# 3h. Subscription Growth Rate# Subscription spend in last 30 days vs prior 30-to-60 dayssubscription_growth_rate = 0.0167 unmodified lines"arrears_trend": float(arrears_trend),"other_credit_ratio": float(other_credit_ratio),"gambling_ratio": float(gambling_ratio),"months_without_income_ratio": float(months_without_income_ratio)})return pd.DataFrame(features_list)def save_feature_snapshots(df_features, db_path=DB_PATH):"""Saves a DataFrame of computed feature snapshots into the DB."""if df_features.empty:returnconn = get_db_connection(db_path)cursor = conn.cursor()# We convert df to tuplesrecords = []for _, row in df_features.iterrows():records.append((row["snapshot_id"], row["user_id"], row["snapshot_date"], row["age"], row["employment_status"],row["housing_type"], row["credit_score"], row["runway_months"], row["debt_to_income_ratio"],row["savings_rate"], row["income_volatility"], row["expense_volatility"], row["liquidity_decay_rate"],row["behavioural_risk_score"], row["subscription_growth_rate"], row["spending_trend_velocity"],row["total_balance"], row["recent_failed_payments_30d"], row["overdraft_days_30d"],row["emergency_borrowing_30d"], row["discretionary_spend_ratio"],row["runway_deterioration_slope"], row["liquidity_collapse_velocity"], row["overdraft_persistence_ratio"],row["expense_acceleration_instability"], row["recovery_half_life"], row["debt_servicing_stress_index"],row["emergency_depletion_velocity"],row["has_income_data"], row["has_debt_data"], row["has_transaction_history"], row["has_credit_score"], row["has_questionnaire_data"],row["min_balance_months"], row["frac_near_empty"], row["p10_balance_months"], row["balance_volatility"], row["balance_trend"], row["arrears_months_12m"], row["worst_arrears_streak"], row["ever_missed_payment"], row["months_since_last_miss"], row["failed_payment_count_12m"], row["arrears_trend"], row["other_credit_ratio"], row["gambling_ratio"], row["months_without_income_ratio"]))cursor.executemany("""INSERT OR REPLACE INTO feature_snapshots (snapshot_id, user_id, snapshot_date, age, employment_status, housing_type, credit_score,runway_months, debt_to_income_ratio, savings_rate, income_volatility, expense_volatility,liquidity_decay_rate, behavioural_risk_score, subscription_growth_rate, spending_trend_velocity,total_balance, recent_failed_payments_30d, overdraft_days_30d, emergency_borrowing_30d,discretionary_spend_ratio,runway_deterioration_slope, liquidity_collapse_velocity, overdraft_persistence_ratio,expense_acceleration_instability, recovery_half_life, debt_servicing_stress_index,emergency_depletion_velocity,has_income_data, has_debt_data, has_transaction_history,has_credit_score, has_questionnaire_data,min_balance_months, frac_near_empty, p10_balance_months, balance_volatility, balance_trend, arrears_months_12m, worst_arrears_streak, ever_missed_payment, months_since_last_miss, failed_payment_count_12m, arrears_trend, other_credit_ratio, gambling_ratio, months_without_income_ratio) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", records)conn.commit()conn.close()print(f"Saved {len(records)} feature snapshots to the database.")def apply_multi_account_consolidation(df_features, db_path, snapshot_date):"""Overwrites five features with entity-level consolidated values.7 unmodified lines891011121314102 unmodified lines117118119120121122123267 unmodified lines391392393394395396397398399400401402403404167 unmodified lines5725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366377 unmodified lines# Import universal behavioural signalssys.path.append(str(Path(__file__).resolve().parent))import universal_signalsfrom merchant_intelligence import compute_merchant_features, MERCHANT_FEATURE_NAMESdef get_historical_balances(cursor, user_ids, snapshot_date):"""Reconstructs the account balances for a set of users at a specific snapshot_date.102 unmodified lines# 3. Fetch Transactions prior to snapshot_date (up to 90 days prior for aggregations)date_90d_prior = snapshot_date - datetime.timedelta(days=90)cursor.execute(f"""SELECT user_id, account_id, transaction_date, amount, category, is_failed, descriptionFROM transactionsWHERE user_id IN ({user_ids_str})AND transaction_date >= ?267 unmodified linesif len(inc_by_month) > 0:months_without_income_ratio = float((inc_by_month <= 0).mean())# 3h-quinquies. Counterparty analysis.## Who the money goes to, not just how much. A DEBT_PAYMENT to a mortgage# and one to a payday lender are the same row to a category-only view and# opposite signals in reality. Degrades to zeros with a coverage flag when# the caller sends no descriptions, rather than reading as "no exposure".merchant_feats = compute_merchant_features(u_tx, monthly_income, snapshot_date)# 3h. Subscription Growth Rate# Subscription spend in last 30 days vs prior 30-to-60 dayssubscription_growth_rate = 0.0167 unmodified lines"arrears_trend": float(arrears_trend),"other_credit_ratio": float(other_credit_ratio),"gambling_ratio": float(gambling_ratio),"months_without_income_ratio": float(months_without_income_ratio),**{k: merchant_feats[k] for k in MERCHANT_FEATURE_NAMES}})return pd.DataFrame(features_list)def save_feature_snapshots(df_features, db_path=DB_PATH):"""Saves computed feature snapshots, matching whatever columns the table has.This used to carry three hand-maintained parallel lists -- the column names,the value tuple and the placeholder string -- which silently drift apart themoment a feature is added. That went wrong twice while extending the featureset: once writing 33 placeholders for 44 columns, once listing 44 columns for47 values. Both are the kind of mistake that only surfaces at runtime.The table is now inspected and the intersection with the DataFrame is written,so adding a feature needs a schema column and nothing else. Features with nocolumn are skipped rather than raising, which keeps an older database working."""if df_features.empty:returnconn = get_db_connection(db_path)try:cursor = conn.cursor()try:cursor.execute("PRAGMA table_info(feature_snapshots)")table_cols = [row[1] for row in cursor.fetchall()]except Exception:table_cols = []if not table_cols: # Postgres, where PRAGMA does not existcursor.execute("SELECT * FROM feature_snapshots LIMIT 0")table_cols = [d[0] for d in cursor.description]cols = [c for c in table_cols if c in df_features.columns]missing = [c for c in df_features.columnsif c not in table_cols and c not in ("snapshot_id",)]if missing:print(f" Note: {len(missing)} computed feature(s) have no column and were "f"not stored: {', '.join(sorted(missing)[:6])}"f"{' ...' if len(missing) > 6 else ''}")placeholders = ", ".join("?" for _ in cols)collist = ", ".join(cols)records = [tuple(row[c] for c in cols) for _, row in df_features.iterrows()]cursor.executemany(f"INSERT OR REPLACE INTO feature_snapshots ({collist}) VALUES ({placeholders})",records)conn.commit()print(f"Saved {len(records)} feature snapshots to the database.")except Exception:try:conn.rollback()except Exception:passraisefinally:conn.close()def apply_multi_account_consolidation(df_features, db_path, snapshot_date):"""Overwrites five features with entity-level consolidated values.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225"""Reads the counterparty, not just the amount.
The strongest single signal found across the real datasets was not how muchsomeone spends or on what: it was whether they are already servicing creditsomewhere else. On 7,080 real clients with 262 adjudicated defaults, the share ofoutflow going to financial-institution merchant categories scored 0.625 AUC onits own, ahead of every cashflow and spending measure tested.
A category label cannot express that. "DEBT_PAYMENT" of 200 says nothing aboutwhether it went to a mortgage or to a payday lender, and those carry oppositerisk. The merchant does.
Two kinds of evidence are used, and they degrade independently:
NAMED providers, from the description text. A curated list, because there is no way to infer from data alone that Klarna is buy-now-pay-later. Descriptions are optional in the API, so everything here returns 0 and sets a coverage flag when they are absent rather than silently reading as "no exposure".
STRUCTURAL patterns, from amounts and timing alone. Recurring identical debits, outsized single purchases, escalating fees. These need no merchant name and so keep working for callers who send none."""
import re
import numpy as npimport pandas as pd
# Provider classes ordered by how much they say about credit stress. A borrower# using a payday lender or in contact with a collections agency is in a different# position from one paying a mortgage, even though both look like DEBT_PAYMENT.PROVIDER_PATTERNS = { "DEBT_COLLECTION": [ r"\b(cabot|lowell|intrum|arrow global|moorcroft|robinson way|link financial)\b", r"\b(debt (recovery|collect|manage)|collections?|arrears|recovery agen)", r"\b(stepchange|payplan|christians against poverty|national debtline)\b", ], "PAYDAY_LENDER": [ r"\b(wonga|sunny|quickquid|lending stream|satsuma|peachy|mr lender|drafty)\b", r"\b(cashfloat|myjar|piggy ?bank|the money shop|dot ?dot ?loans|fernovo)\b", r"\b(payday|short.?term loan|cash advance loan)\b", ], "BNPL": [ r"\b(klarna|clearpay|laybuy|zilch|payl8r|openpay|afterpay|sezzle)\b", r"\b(buy now pay later|pay in 3|pay in 4|split ?pay)\b", ], "SALARY_ADVANCE": [ r"\b(wagestream|hastee|salary ?finance|level ?financial|earned wage)\b", r"\b(salary advance|wage advance|pay ?advance)\b", ], "HIGH_COST_CREDIT": [ r"\b(provident|morses club|loans ?at ?home|shopacheck|brighthouse|perfecthome)\b", r"\b(guarantor loan|logbook loan|doorstep (loan|lend)|rent ?to ?own)\b", r"\b(vanquis|aqua|marbles|capital one|ocean finance|likely ?loans)\b", ], "MAINSTREAM_CREDIT": [ r"\b(barclaycard|amex|american express|mbna|halifax card|natwest card)\b", r"\b(credit card|card payment to|loan repayment|personal loan|hire purchase)\b", ], "GAMBLING": [ r"\b(bet365|william hill|paddy ?power|ladbrokes|coral|betfair|sky ?bet)\b", r"\b(betway|unibet|888|pokerstars|casino|bingo|lottery|betfred|gala)\b", r"\b(gambl|wager|sportsbook|slots)\b", ], "CRYPTO": [ r"\b(coinbase|binance|kraken|crypto\.com|etoro|revolut crypto|bitstamp)\b", r"\b(bitcoin|crypto|ethereum)\b", ], "OVERDRAFT_FEE": [ r"\b(unarranged|unauthorised|overdraft (fee|interest|charge)|returned (item|dd))\b", r"\b(insufficient funds|unpaid (item|dd|transaction)|refer to payer)\b", ],}
_COMPILED = {k: [re.compile(p, re.I) for p in v] for k, v in PROVIDER_PATTERNS.items()}
# Classes that represent borrowing from, or distress with, another provider.CREDIT_EXPOSURE_CLASSES = ("DEBT_COLLECTION", "PAYDAY_LENDER", "BNPL", "SALARY_ADVANCE", "HIGH_COST_CREDIT", "MAINSTREAM_CREDIT")# Classes that are adverse regardless of amount.DISTRESS_CLASSES = ("DEBT_COLLECTION", "PAYDAY_LENDER", "SALARY_ADVANCE", "HIGH_COST_CREDIT", "OVERDRAFT_FEE")
def classify_provider(description, category=None): """Returns a provider class, or None when nothing is recognised.
Falls back to the transaction category so that a caller sending no descriptions still gets the coarse signal the categories carry. """ text = str(description or "").strip() if text: for cls, patterns in _COMPILED.items(): if any(p.search(text) for p in patterns): return cls if category == "GAMBLING": return "GAMBLING" if category == "CASH_ADVANCE": return "HIGH_COST_CREDIT" return None
def _recurring_commitments(df): """Debits that repeat at a near-constant amount: rent, subscriptions, loans.
Found structurally rather than by name, so it works with no descriptions. A borrower whose fixed obligations consume most of their income has little room to absorb a shock, whatever their headline balance looks like. """ out = df[df["amount"] < 0].copy() if out.empty: return 0.0, 0 out["rounded"] = (-out["amount"]).round(0) groups = out.groupby("rounded").size() recurring = groups[groups >= 2] if recurring.empty: return 0.0, 0 # One instance per repeat, valued at the repeating amount. monthly = float((recurring.index.values * 1.0).sum()) return monthly, int(recurring.sum())
def compute_merchant_features(df_tx, monthly_income, snapshot_date, window_days=90): """Provider-level and structural features over the window.
Returns a flat dict. Every value is 0.0 when the evidence is absent, and `has_merchant_descriptions` records whether the named-provider half of this could run at all -- so a caller that sends no descriptions can be told its score is missing the strongest available signal rather than being quietly scored as though it had none. """ blank = { "credit_provider_ratio": 0.0, "distinct_credit_providers": 0, "bnpl_ratio": 0.0, "high_cost_credit_ratio": 0.0, "payday_or_collections_flag": 0, "salary_advance_flag": 0, "crypto_ratio": 0.0, "overdraft_fee_events": 0, "fee_escalation": 0.0, "max_purchase_months": 0.0, "large_purchase_count": 0, "purchase_spike_ratio": 0.0, "merchant_diversity": 0, "recurring_commitment_ratio": 0.0, "has_merchant_descriptions": 0, } if df_tx is None or len(df_tx) == 0: return blank
df = df_tx.copy() df["transaction_date"] = pd.to_datetime(df["transaction_date"]) start = pd.Timestamp(snapshot_date) - pd.Timedelta(days=window_days) df = df[(df["transaction_date"] >= start) & (df["transaction_date"] <= pd.Timestamp(snapshot_date))] if df.empty: return blank
income = max(1.0, float(monthly_income or 0.0)) if "description" not in df.columns: df["description"] = "" described = df["description"].astype(str).str.strip().ne("").sum()
df["provider"] = [classify_provider(d, c) for d, c in zip(df["description"], df.get("category", [None] * len(df)))]
outflow = df[df["amount"] < 0] outflow_total = float(-outflow["amount"].sum()) if not outflow.empty else 0.0
def share(classes): if outflow_total <= 0: return 0.0 sel = outflow[outflow["provider"].isin(classes)] return float(min(1.0, -sel["amount"].sum() / outflow_total))
credit_rows = outflow[outflow["provider"].isin(CREDIT_EXPOSURE_CLASSES)]
# Fee escalation: are bank charges accelerating? Compares the recent third of # the window against the earliest third, so it reads as a trend rather than a # count that a single bad month can dominate. fees = df[(df.get("category") == "FEES") | (df["provider"] == "OVERDRAFT_FEE")] fee_escalation = 0.0 if not fees.empty: age = (pd.Timestamp(snapshot_date) - fees["transaction_date"]).dt.days recent = int((age <= window_days / 3).sum()) oldest = int((age >= 2 * window_days / 3).sum()) fee_escalation = float((recent - oldest) / max(1, recent + oldest))
# Outsized purchases, measured against income rather than an absolute figure, # so the same rule works for someone on 1,200 a month and someone on 12,000. max_purchase_months = 0.0 large_purchase_count = 0 purchase_spike_ratio = 0.0 if not outflow.empty: amounts = -outflow["amount"].values max_purchase_months = float(amounts.max() / income) large_purchase_count = int((amounts > income * 0.5).sum()) typical = float(np.median(amounts)) if typical > 0: purchase_spike_ratio = float(min(20.0, amounts.max() / typical))
recurring_total, _ = _recurring_commitments(df)
return { "credit_provider_ratio": share(CREDIT_EXPOSURE_CLASSES), "distinct_credit_providers": int(credit_rows["provider"].nunique()), "bnpl_ratio": share(["BNPL"]), "high_cost_credit_ratio": share(["PAYDAY_LENDER", "HIGH_COST_CREDIT"]), "payday_or_collections_flag": int( outflow["provider"].isin(["PAYDAY_LENDER", "DEBT_COLLECTION"]).any()), "salary_advance_flag": int((df["provider"] == "SALARY_ADVANCE").any()), "crypto_ratio": share(["CRYPTO"]), "overdraft_fee_events": int((df["provider"] == "OVERDRAFT_FEE").sum()), "fee_escalation": fee_escalation, "max_purchase_months": max_purchase_months, "large_purchase_count": large_purchase_count, "purchase_spike_ratio": purchase_spike_ratio, "merchant_diversity": int(df["description"].astype(str).str.lower().str.strip().nunique()), "recurring_commitment_ratio": float(min(3.0, recurring_total / income)), "has_merchant_descriptions": int(described > 0), }
MERCHANT_FEATURE_NAMES = list(compute_merchant_features(None, 1.0, pd.Timestamp.now()).keys())db/schema.sql+19
src/features.py+62-42
src/merchant_intelligence.pyAdded+225