File size: 5,938 Bytes
e0ca18d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
"""Data Fusion "Default": real bank transactions with real credit outcomes.

2.1M transactions across 7,080 clients, 262 of whom defaulted on a credit product
(3.7%). Every client has exactly 300 transactions carrying a merchant category
code, a signed amount and a timestamp.

This is the first dataset in the project that is BOTH real and in the shape the
product actually consumes: transactions in, default out. Berka is real but has 63
events; Taiwan and GiveMeSomeCredit have thousands of events but are card
statements and bureau records, so a transaction-fed model cannot learn from them.

The features below are the same concepts validated elsewhere, rebuilt from raw
transactions with no balance column available:

  cashflow path   cumulative signed amount stands in for the balance, so trough,
                  time-spent-low and volatility can be computed at all
  cash withdrawal MCC 6011 is ATM cash. Heavy cash use is the closest available
                  analogue to the emergency-borrowing signal
  income rhythm   regularity and size of inflows
"""
import os
import warnings

warnings.filterwarnings("ignore")
import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.metrics import average_precision_score, brier_score_loss, roc_auc_score
from sklearn.model_selection import StratifiedKFold

ROOT = r"C:\Users\piplu\financial_risk_system"
D = os.path.join(ROOT, "db", "datafusion")

CASH_MCC = {6011, 6010}          # ATM / manual cash disbursement
GAMBLING_MCC = {7995, 7801, 7802}
LOAN_MCC = {6012, 6051}          # financial institutions / quasi-cash


def build():
    tx = pd.read_csv(os.path.join(D, "transactions_finetune.csv"),
                     parse_dates=["transaction_dttm"])
    tgt = pd.read_csv(os.path.join(D, "target_finetune.csv"))
    tx = tx.sort_values(["user_id", "transaction_dttm"])

    rows = []
    for uid, g in tx.groupby("user_id", sort=False):
        amt = g["transaction_amt"].values
        mcc = g["mcc_code"].values
        ts = g["transaction_dttm"].values

        inflow = amt[amt > 0]
        outflow = -amt[amt < 0]
        span_days = max(1.0, (ts[-1] - ts[0]) / np.timedelta64(1, "D"))
        months = max(1.0, span_days / 30.0)

        income = inflow.sum() / months if inflow.size else 1.0
        income = max(1.0, income)
        spend = outflow.sum() / months if outflow.size else 0.0

        # Cumulative cashflow: the only available stand-in for a balance path.
        path = np.cumsum(amt)
        trough = path.min()

        # Monthly inflow regularity
        month_idx = ((ts - ts[0]) / np.timedelta64(30, "D")).astype(int)
        inc_by_month = pd.Series(np.where(amt > 0, amt, 0)).groupby(month_idx).sum().values
        inc_vol = float(inc_by_month.std() / max(1.0, inc_by_month.mean())) if inc_by_month.size > 1 else 0.0
        months_no_income = float((inc_by_month <= 0).mean()) if inc_by_month.size else 0.0

        cash = -amt[np.isin(mcc, list(CASH_MCC)) & (amt < 0)].sum()
        gamb = -amt[np.isin(mcc, list(GAMBLING_MCC)) & (amt < 0)].sum()
        loan = -amt[np.isin(mcc, list(LOAN_MCC)) & (amt < 0)].sum()

        rows.append({
            "user_id": uid,
            # cashflow path
            "cf_trough_months": trough / income,
            "cf_p10_months": np.percentile(path, 10) / income,
            "cf_frac_below_zero": float((path < 0).mean()),
            "cf_frac_near_low": float((path < path.max() * 0.25).mean()),
            "cf_volatility": float(path.std() / income),
            "cf_trend": float(np.polyfit(np.arange(len(path)), path, 1)[0] / income),
            "cf_net_monthly": (income - spend) / income,
            # income
            "income_volatility": inc_vol,
            "months_without_income": months_no_income,
            "log_income": float(np.log1p(income)),
            # behaviour
            "cash_ratio": float(cash / max(1.0, outflow.sum())),
            "gambling_ratio": float(gamb / max(1.0, outflow.sum())),
            "loan_mcc_ratio": float(loan / max(1.0, outflow.sum())),
            "spend_to_income": float(spend / income),
            "n_distinct_mcc": int(len(np.unique(mcc))),
            "tx_per_month": float(len(amt) / months),
        })

    feats = pd.DataFrame(rows).merge(tgt, on="user_id", how="inner")
    return feats


def evaluate(X, y, label, seed=42):
    cv = StratifiedKFold(5, shuffle=True, random_state=seed)
    oof = np.zeros(len(y))
    for tr, te in cv.split(X, y):
        m = xgb.XGBClassifier(n_estimators=400, max_depth=3, learning_rate=0.05,
                              subsample=0.9, colsample_bytree=0.8, min_child_weight=15,
                              reg_lambda=3.0, eval_metric="logloss", random_state=seed)
        m.fit(X.iloc[tr], y[tr])
        oof[te] = m.predict_proba(X.iloc[te])[:, 1]
    auc = roc_auc_score(y, oof)
    o = np.argsort(-oof); d = np.array_split(o, 10)
    print(f"  {label:28s} n_feat={X.shape[1]:<3} AUC {auc:.4f}  PR {average_precision_score(y, oof):.4f}"
          f"  Brier {brier_score_loss(y, oof):.4f}  lift {y[d[0]].mean()/y.mean():.2f}x")
    return auc, oof


def main():
    print("building features from 2.1M real transactions...", flush=True)
    f = build()
    y = f["target"].values
    X = f.drop(columns=["user_id", "target"])
    print(f"n={len(f)} clients, {y.sum()} real defaults ({y.mean():.4f})\n")

    print("Single-feature AUC on real credit defaults:")
    for c, a in sorted(((c, roc_auc_score(y, X[c].values)) for c in X.columns),
                       key=lambda t: -max(t[1], 1 - t[1]))[:10]:
        print(f"   {c:24s} {max(a, 1-a):.4f}  ({'higher=worse' if a > .5 else 'higher=better'})")

    print()
    cf = [c for c in X.columns if c.startswith("cf_")]
    evaluate(X, y, "ALL features")
    evaluate(X[cf], y, "cashflow path ONLY")
    evaluate(X[[c for c in X.columns if c not in cf]], y, "everything EXCEPT path")


if __name__ == "__main__":
    main()