File size: 36,687 Bytes
bc308f6
 
 
 
 
 
 
 
 
 
b025087
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
096fb77
 
 
 
 
 
 
 
 
 
 
 
 
bc308f6
 
096fb77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b025087
bc308f6
 
 
 
 
 
 
 
 
096fb77
 
 
 
 
 
 
 
 
 
 
 
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
096fb77
bc308f6
 
 
 
 
 
096fb77
 
 
 
 
 
 
 
 
 
bc308f6
 
 
096fb77
bc308f6
 
 
 
 
 
 
 
 
 
096fb77
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
096fb77
bc308f6
 
096fb77
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9abc98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb0b2ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d13dd0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b025087
 
 
 
 
 
 
 
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
096fb77
 
 
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
096fb77
bc308f6
 
 
 
096fb77
bc308f6
 
 
 
 
 
 
 
 
 
 
 
096fb77
 
 
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9abc98
 
 
 
 
eb0b2ae
 
 
 
 
 
d13dd0c
 
 
b025087
 
bc308f6
 
 
 
 
b025087
 
 
 
 
 
 
 
 
 
 
 
bc308f6
 
b025087
bc308f6
b025087
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc308f6
ca7ca11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22cc1d6
 
 
 
ca7ca11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca7ca11
bc308f6
 
 
 
 
 
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
import datetime
import numpy as np
import pandas as pd
import sys
from pathlib import Path
from database import get_db_connection, DB_PATH

# Import universal behavioural signals
sys.path.append(str(Path(__file__).resolve().parent))
import universal_signals
from merchant_intelligence import compute_merchant_features, MERCHANT_FEATURE_NAMES

def get_historical_balances(cursor, user_ids, snapshot_date):
    """Reconstructs the account balances for a set of users at a specific snapshot_date.
    SQLite doesn't maintain history of balance, so we reconstruct it by subtracting
    transactions that occurred after the snapshot_date from the current account balance.
    """
    if isinstance(snapshot_date, str):
        snapshot_date = pd.to_datetime(snapshot_date).to_pydatetime()
        
    user_ids_str = ",".join(str(uid) for uid in user_ids)
    
    # Get current balances
    cursor.execute(f"""
        SELECT account_id, user_id, account_type, balance, credit_limit, overdraft_limit 
        FROM accounts 
        WHERE user_id IN ({user_ids_str})
    """)
    current_accounts = cursor.fetchall()
    
    balances = {}
    for row in current_accounts:
        balances[row["account_id"]] = {
            "account_id": row["account_id"],
            "user_id": row["user_id"],
            "account_type": row["account_type"],
            "current_balance": row["balance"],
            "credit_limit": row["credit_limit"] or 0.0,
            "overdraft_limit": row["overdraft_limit"] or 0.0,
            "reconstructed_balance": row["balance"]
        }
        
    # Get all transactions that occurred AFTER the snapshot_date
    cursor.execute(f"""
        SELECT account_id, amount 
        FROM transactions 
        WHERE user_id IN ({user_ids_str}) AND transaction_date > ? AND is_failed = 0
    """, (snapshot_date.strftime("%Y-%m-%d %H:%M:%S"),))
    future_txs = cursor.fetchall()
    
    # Subtract future transactions from current balance to get balance at snapshot_date
    # since: current_balance = balance_at_T + future_txs_sum => balance_at_T = current_balance - future_txs_sum
    for tx in future_txs:
        acc_id = tx["account_id"]
        if acc_id in balances:
            balances[acc_id]["reconstructed_balance"] -= tx["amount"]
            
    return balances

def compute_user_features(db_path, user_ids, snapshot_date, source_data=None):
    """Computes features for a list of user_ids at a given snapshot_date.

    Args:
        source_data (dict|None): when supplied, features are computed from this
            in-memory data instead of querying db_path. Expected keys:
            'users'        -> {user_id: profile dict}
            'accounts'     -> list of account dicts (with reconstructed_balance)
            'transactions' -> DataFrame of transactions
            This is what the stateless /score endpoint uses: the payload arrives
            in the request and nothing is read from or written to a database.
            See payload.build_source_data().
    """
    if isinstance(snapshot_date, str):
        snapshot_date = pd.to_datetime(snapshot_date).to_pydatetime()

    if source_data is not None:
        users_data = source_data.get("users") or {}
        user_accounts = {uid: [] for uid in user_ids}
        for acc in source_data.get("accounts") or []:
            user_accounts.setdefault(acc.get("user_id"), []).append(acc)
        df_tx = source_data.get("transactions")
        if df_tx is None:
            df_tx = pd.DataFrame()
        df_tx = df_tx.copy()
        if not df_tx.empty:
            df_tx["transaction_date"] = pd.to_datetime(df_tx["transaction_date"])
            date_90d_prior = snapshot_date - datetime.timedelta(days=90)
            df_tx = df_tx[
                (df_tx["transaction_date"] >= pd.Timestamp(date_90d_prior))
                & (df_tx["transaction_date"] <= pd.Timestamp(snapshot_date))
            ].sort_values("transaction_date")
        return _features_from_frames(users_data, user_accounts, df_tx, user_ids, snapshot_date)

    conn = get_db_connection(db_path)
    cursor = conn.cursor()
    
    user_ids_str = ",".join(str(uid) for uid in user_ids)
    
    # 1. Fetch User Profiles
    cursor.execute(f"""
        SELECT user_id, age, dob, employment_status, housing_type, credit_score,
               impulse_spending, tracking_habits, income_stability_report, 
               debt_self_report, savings_habits, gross_income, net_income
        FROM users 
        WHERE user_id IN ({user_ids_str})
    """)
    users_data = {row["user_id"]: dict(row) for row in cursor.fetchall()}
    
    # 2. Reconstruct account balances at snapshot_date
    account_balances = get_historical_balances(cursor, user_ids, snapshot_date)
    
    # Group account balances by user
    user_accounts = {uid: [] for uid in user_ids}
    for acc_id, acc_info in account_balances.items():
        user_accounts[acc_info["user_id"]].append(acc_info)
        
    # 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, description
        FROM transactions
        WHERE user_id IN ({user_ids_str}) 
          AND transaction_date >= ? 
          AND transaction_date <= ?
        ORDER BY transaction_date ASC
    """, (date_90d_prior.strftime("%Y-%m-%d %H:%M:%S"), snapshot_date.strftime("%Y-%m-%d %H:%M:%S")))
    
    tx_rows = cursor.fetchall()
    df_tx = pd.DataFrame([dict(r) for r in tx_rows])
    if not df_tx.empty:
        df_tx["transaction_date"] = pd.to_datetime(df_tx["transaction_date"])
    conn.close()
    return _features_from_frames(users_data, user_accounts, df_tx, user_ids, snapshot_date)


def _features_from_frames(users_data, user_accounts, df_tx, user_ids, snapshot_date):
    """Computes the feature rows from already-materialised data.

    Shared by the database path and the stateless payload path so both produce
    byte-identical features from equivalent inputs.
    """
    if not df_tx.empty:
        df_tx["transaction_date"] = pd.to_datetime(df_tx["transaction_date"])
        
    features_list = []
    
    for uid in user_ids:
        # Defaults
        profile = users_data.get(uid, {})
        accs = user_accounts.get(uid, [])
        
        # Calculate balances
        checking_bal = 0.0
        savings_bal = 0.0
        cc_bal = 0.0
        total_limit = 0.0
        
        for acc in accs:
            bal = acc["reconstructed_balance"]
            if acc["account_type"] == "CHECKING":
                checking_bal += bal
            elif acc["account_type"] == "SAVINGS":
                savings_bal += bal
            elif acc["account_type"] == "CREDIT_CARD":
                cc_bal += bal # Reconstructed cc balance is negative for debt, e.g. -1500
                total_limit += acc["credit_limit"]
                
        total_balance = checking_bal + savings_bal + cc_bal
        
        # Filter transactions for this user
        u_tx = df_tx[df_tx["user_id"] == uid] if not df_tx.empty else pd.DataFrame()
        
        # 3a. Presence Flags
        has_income_data = 1 if not u_tx.empty and len(u_tx[(u_tx["category"] == "INCOME") & (u_tx["is_failed"] == 0)]) > 0 else 0
        has_debt_data = 1 if ((profile.get("debt_self_report") or 0) > 0) or (not u_tx.empty and len(u_tx[u_tx["category"] == "DEBT_PAYMENT"]) > 0) else 0
        has_transaction_history = 1 if not u_tx.empty and len(u_tx) >= 1 else 0
        has_credit_score = 1 if profile.get("credit_score") is not None else 0
        has_questionnaire_data = 1 if profile.get("impulse_spending") is not None else 0
        
        # 3b. Cashflow aggregates
        tx_90 = u_tx[u_tx["is_failed"] == 0] if not u_tx.empty else pd.DataFrame()

        # Monthly rates are derived by dividing the windowed totals by the number
        # of months ACTUALLY observed, not by a fixed 3. A caller supplying 30
        # days of history would otherwise have income, expenses and debt service
        # understated threefold, which inflates runway and distorts every ratio
        # built on them.
        months_observed = 3.0
        if not tx_90.empty:
            span_days = (snapshot_date - tx_90["transaction_date"].min().to_pydatetime()).days + 1
            months_observed = float(min(3.0, max(0.5, span_days / 30.0)))
        
        # Income in past 90 days
        income_90 = tx_90[tx_90["category"] == "INCOME"]["amount"].sum() if not tx_90.empty else 0.0
        monthly_income = max(1.0, income_90 / months_observed)
        
        # If income transactions are missing, fallback to net_income from profile
        if income_90 == 0.0 and profile.get("net_income"):
            monthly_income = profile["net_income"]
            
        # Expenses in past 90 days (exclude savings transfers and credit card payments to avoid double counting)
        expense_categories = ['RENT_MORTGAGE', 'UTILITIES', 'GROCERIES', 'DISCRETIONARY', 'SUBSCRIPTION', 'GAMBLING', 'CASH_ADVANCE', 'FEES']
        expenses_90 = 0.0
        if not tx_90.empty:
            expenses_90 = abs(tx_90[tx_90["category"].isin(expense_categories)]["amount"].sum())
        monthly_expenses = max(1.0, expenses_90 / months_observed)
        
        # 3c. Runway Months
        # Runway = Total Balance / Monthly Expenses. If negative or zero, runway is 0.
        runway_months = max(0.0, total_balance / monthly_expenses) if total_balance > 0 else 0.0
        
        # 3d. Savings Rate
        # Savings Rate = (Income - Expense) / Income. Clip to [-1.0, 1.0].
        savings_rate = (monthly_income - monthly_expenses) / monthly_income if monthly_income > 1.0 else 0.0
        savings_rate = max(-1.0, min(1.0, savings_rate))
        
        # 3e. Debt to Income Ratio
        debt_payment_90 = 0.0
        if not tx_90.empty:
            debt_payment_90 = abs(tx_90[tx_90["category"] == "DEBT_PAYMENT"]["amount"].sum())
        monthly_debt_payment = debt_payment_90 / months_observed
        
        # If transaction has no debt payments but user reports self debt, estimate monthly payment as 5% of debt
        if monthly_debt_payment == 0.0 and (profile.get("debt_self_report") or 0) > 0:
            monthly_debt_payment = profile["debt_self_report"] * 0.05
            
        debt_to_income_ratio = monthly_debt_payment / monthly_income
        
        # 3f. Income and Expense Volatility
        # Volatility = Standard Deviation of weekly sums divided by mean (coefficient of variation)
        income_volatility = 0.0
        expense_volatility = 0.0
        
        if not tx_90.empty:
            # Create a weekly timeseries of sums
            tx_90_weekly = tx_90.copy()
            # Assign weeks (1-12)
            tx_90_weekly["week"] = ((snapshot_date - tx_90_weekly["transaction_date"]).dt.days // 7).clip(0, 11)
            
            # Weekly income sums
            inc_weekly = tx_90_weekly[tx_90_weekly["category"] == "INCOME"].groupby("week")["amount"].sum()
            # Ensure we have 12 entries
            inc_series = pd.Series([inc_weekly.get(w, 0.0) for w in range(12)])
            if inc_series.mean() > 0:
                income_volatility = inc_series.std() / inc_series.mean()
                
            # Weekly expense sums
            exp_weekly = tx_90_weekly[tx_90_weekly["category"].isin(expense_categories)].groupby("week")["amount"].sum().abs()
            exp_series = pd.Series([exp_weekly.get(w, 0.0) for w in range(12)])
            if exp_series.mean() > 0:
                expense_volatility = exp_series.std() / exp_series.mean()
                
        # 3g. Liquidity Decay Rate
        # Calculate slope of checking balance over last 30 days
        # We sample checking balance at days T, T-5, T-10, T-15, T-20, T-25, T-30
        liquidity_decay_rate = 0.0
        if has_transaction_history:
            days_points = [0, 5, 10, 15, 20, 25, 30]
            bals_at_points = []
            for d in days_points:
                pt_date = snapshot_date - datetime.timedelta(days=d)
                pt_txs = u_tx[(u_tx["transaction_date"] > pt_date) & (u_tx["is_failed"] == 0)]
                pt_balance = checking_bal
                # Subtract checking transactions that happened after pt_date
                if not pt_txs.empty:
                    # Filter checking account
                    checking_acc_ids = [a["account_id"] for a in accs if a["account_type"] == "CHECKING"]
                    pt_balance -= pt_txs[pt_txs["account_id"].isin(checking_acc_ids)]["amount"].sum()
                bals_at_points.append(pt_balance)
            
            # Run linear regression: bals = m * days + c
            # days: 0, -5, -10, -15, -20, -25, -30
            # slope m tells us the daily decay. We normalize decay rate: slope / checking_bal (if positive)
            x = np.array([0, -5, -10, -15, -20, -25, -30])
            y = np.array(bals_at_points)
            slope, _ = np.polyfit(x, y, 1)
            
            # Divide daily slope by checking balance to get decay rate percentage
            # (e.g. slope = -10 means balance decays $10/day. If balance is $1000, decay rate is -0.01 or -1% per day)
            denom = max(100.0, checking_bal)
            # Decay rate is positive for decay (loss of funds)
            liquidity_decay_rate = -slope / denom
            
        # 3h-bis. Balance TRAJECTORY features.
        #
        # Validated on 620 real loans with bank-adjudicated outcomes (PKDD'99
        # Berka). The share of time an account runs near-empty scores 0.857 AUC
        # on real defaults BY ITSELF, against 0.708 for the whole previous
        # feature set and 0.553 for the model trained on synthetic labels.
        #
        # The existing features could not see this: total_balance is a single
        # point in time and overdraft_days_30d only looks back a month. What
        # predicts real default is how close to zero someone habitually runs, and
        # for how long -- which needs the path, not a snapshot of it.
        min_balance_months = 0.0
        frac_near_empty = 0.0
        p10_balance_months = 0.0
        balance_volatility = 0.0
        balance_trend = 0.0

        if has_transaction_history and not tx_90.empty:
            checking_ids = [a["account_id"] for a in accs if a["account_type"] == "CHECKING"]
            chk = tx_90[tx_90["account_id"].isin(checking_ids)].sort_values("transaction_date")
            if not chk.empty:
                # Walk the balance backwards from the snapshot to recover the path.
                deltas = chk["amount"].values[::-1]
                path = checking_bal + np.concatenate(([0.0], np.cumsum(deltas)))
                path = path[::-1]

                denom_income = max(1.0, monthly_income)
                min_balance_months = float(path.min() / denom_income)
                p10_balance_months = float(np.percentile(path, 10) / denom_income)
                # "Near empty" = under a quarter of one month's income.
                frac_near_empty = float((path < denom_income * 0.25).mean())
                balance_volatility = float(path.std() / denom_income)
                if len(path) > 2:
                    xs = np.arange(len(path), dtype=float)
                    balance_trend = float(np.polyfit(xs, path, 1)[0] / denom_income)

        # 3h-ter. DELINQUENCY LADDER over 12 months.
        #
        # On the UCI Taiwan set (30,000 clients, 6,636 real defaults) delinquency
        # history dominated everything else: four of the top five features by gain
        # were delinquency-derived, ever_60dpd alone took 30.9% of total gain, and
        # a simple count of months in arrears scored 0.726 AUC by itself.
        #
        # This engine had almost none of that. recent_failed_payments_30d looks
        # back thirty days, which cannot see a borrower who missed three payments
        # last quarter and has been quiet since. What matters in real credit is
        # the worst point, how often, and how recently -- so record the ladder.
        arrears_months_12m = 0
        worst_arrears_streak = 0
        ever_missed_payment = 0
        months_since_last_miss = 12
        failed_payment_count_12m = 0
        arrears_trend = 0.0

        if not u_tx.empty:
            credit_tx = u_tx[u_tx["category"].isin(["DEBT_PAYMENT", "RENT_MORTGAGE"])]
            missed = credit_tx[credit_tx["is_failed"] == 1]
            failed_payment_count_12m = int(len(missed))
            ever_missed_payment = int(failed_payment_count_12m > 0)

            if not missed.empty:
                # Month index counting back from the snapshot: 0 = most recent.
                back = ((snapshot_date - missed["transaction_date"]).dt.days // 30).astype(int)
                months_hit = sorted(set(int(b) for b in back if b >= 0))
                arrears_months_12m = len(months_hit)
                months_since_last_miss = int(min(months_hit)) if months_hit else 12

                streak = best = 1
                for prev, cur in zip(months_hit, months_hit[1:]):
                    streak = streak + 1 if cur == prev + 1 else 1
                    best = max(best, streak)
                worst_arrears_streak = best

                # Positive means arrears are concentrated in the recent half.
                recent = sum(1 for b in back if 0 <= b < 6)
                older = sum(1 for b in back if b >= 6)
                arrears_trend = float(recent - older) / max(1.0, recent + older)

        # 3h-quater. External credit exposure and income continuity.
        #
        # Measured on 7,080 real clients with 262 real credit defaults (Data Fusion):
        #   share of outflow to other credit products   0.625 AUC alone, the single
        #                                               strongest signal in the set
        #   gambling present                            6.97% default vs 3.58%
        #   any month with no income at all             3.78% default vs 0.00%
        #
        # The first is effectively detecting OTHER lenders in the transaction feed:
        # a borrower already servicing debt elsewhere is the one this engine could
        # not previously see. The third is the cleanest single separator found in
        # any of the real datasets, though on a small subgroup.
        other_credit_ratio = 0.0
        gambling_ratio = 0.0
        months_without_income_ratio = 0.0

        if not tx_90.empty:
            outflow_total = abs(tx_90[tx_90["amount"] < 0]["amount"].sum())
            if outflow_total > 0:
                other_credit = abs(tx_90[tx_90["category"].isin(
                    ["DEBT_PAYMENT", "CASH_ADVANCE"])]["amount"].sum())
                other_credit_ratio = float(min(1.0, other_credit / outflow_total))
                gambling = abs(tx_90[tx_90["category"] == "GAMBLING"]["amount"].sum())
                gambling_ratio = float(min(1.0, gambling / outflow_total))

            # Income continuity across the window, month by month.
            month_back = ((snapshot_date - tx_90["transaction_date"]).dt.days // 30).astype(int)
            inc_by_month = tx_90.assign(_m=month_back).groupby("_m").apply(
                lambda g: g.loc[g["category"] == "INCOME", "amount"].sum())
            if 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 days
        subscription_growth_rate = 0.0
        if not tx_90.empty:
            sub_tx = tx_90[tx_90["category"] == "SUBSCRIPTION"]
            if not sub_tx.empty:
                t_30 = snapshot_date - datetime.timedelta(days=30)
                t_60 = snapshot_date - datetime.timedelta(days=60)
                
                sub_0_30 = abs(sub_tx[sub_tx["transaction_date"] >= t_30]["amount"].sum())
                sub_30_60 = abs(sub_tx[(sub_tx["transaction_date"] >= t_60) & (sub_tx["transaction_date"] < t_30)]["amount"].sum())
                
                if sub_30_60 > 0:
                    subscription_growth_rate = (sub_0_30 - sub_30_60) / sub_30_60
                elif sub_0_30 > 0:
                    subscription_growth_rate = 1.0 # Infinite growth if started from 0, clamp to 1.0
                    
        # 3i. Spending Trend Velocity
        # Discretionary spend in last 30 days divided by the average discretionary spend in the prior 60 days (days 30 to 90)
        spending_trend_velocity = 1.0
        if not tx_90.empty:
            disc_tx = tx_90[tx_90["category"] == "DISCRETIONARY"]
            if not disc_tx.empty:
                t_30 = snapshot_date - datetime.timedelta(days=30)
                disc_0_30 = abs(disc_tx[disc_tx["transaction_date"] >= t_30]["amount"].sum())
                disc_30_90 = abs(disc_tx[disc_tx["transaction_date"] < t_30]["amount"].sum())
                
                avg_prior_30d = disc_30_90 / 2.0 # 60 days, so average for 30 days is / 2.0
                
                if avg_prior_30d > 10.0:
                    spending_trend_velocity = disc_0_30 / avg_prior_30d
                elif disc_0_30 > 10.0:
                    spending_trend_velocity = 1.5 # Arbitrary cap if prior was near zero
                    
        # 3j. Structural/Extra Features
        recent_failed_payments_30d = 0
        overdraft_days_30d = 0
        emergency_borrowing_30d = 0.0
        discretionary_spend_ratio = 0.0
        
        if not u_tx.empty:
            t_30 = snapshot_date - datetime.timedelta(days=30)
            # Failed payments
            recent_failed_payments_30d = len(u_tx[(u_tx["transaction_date"] >= t_30) & (u_tx["is_failed"] == 1)])
            
            # Emergency borrowing (cash advances)
            emergency_borrowing_30d = abs(u_tx[(u_tx["transaction_date"] >= t_30) & (u_tx["category"] == "CASH_ADVANCE")]["amount"].sum())
            
            # Discretionary spend ratio (Discretionary spend / Total spend in 90 days)
            total_spend_90 = abs(u_tx[(u_tx["is_failed"] == 0) & (u_tx["amount"] < 0) & (u_tx["category"] != "TRANSFER")]["amount"].sum())
            disc_spend_90 = abs(u_tx[(u_tx["is_failed"] == 0) & (u_tx["category"] == "DISCRETIONARY")]["amount"].sum())
            if total_spend_90 > 0:
                discretionary_spend_ratio = disc_spend_90 / total_spend_90
                
        # Overdraft days 30d (number of days where checking balance was negative)
        if has_transaction_history:
            for d in range(30):
                pt_date = snapshot_date - datetime.timedelta(days=d)
                pt_txs = u_tx[(u_tx["transaction_date"] > pt_date) & (u_tx["is_failed"] == 0)]
                pt_balance = checking_bal
                if not pt_txs.empty:
                    checking_acc_ids = [a["account_id"] for a in accs if a["account_type"] == "CHECKING"]
                    pt_balance -= pt_txs[pt_txs["account_id"].isin(checking_acc_ids)]["amount"].sum()
                if pt_balance < 0:
                    overdraft_days_30d += 1
                    
        # 3k. Behavioural Risk Score (heuristic 0-100)
        # Base: Questionnaire (if exists). Up to 40 points
        if has_questionnaire_data:
            impulse = profile.get("impulse_spending") or 3
            tracking = profile.get("tracking_habits") or 3
            savings = profile.get("savings_habits") or 3
            base_score = ((impulse + tracking + (6 - savings)) / 15.0) * 40.0
        else:
            base_score = 20.0 # Impute median
            
        # Penalties: up to 60 points
        failed_pay_penalty = min(30.0, recent_failed_payments_30d * 10.0)
        
        # Gambling ratio
        gambling_90 = abs(tx_90[tx_90["category"] == "GAMBLING"]["amount"].sum()) if not tx_90.empty else 0.0
        gambling_ratio = gambling_90 / monthly_income
        gambling_penalty = min(30.0, gambling_ratio * 300.0) # 10% gambling ratio leads to 30 point penalty
        
        # Cash advances
        cash_advances_90 = len(tx_90[tx_90["category"] == "CASH_ADVANCE"]) if not tx_90.empty else 0
        cash_adv_penalty = min(30.0, cash_advances_90 * 15.0)
        
        behavioural_risk_score = min(100.0, base_score + failed_pay_penalty + gambling_penalty + cash_adv_penalty)
        
        # Universal Behavioural Signals
        runway_deterioration_slope = 0.0
        liquidity_collapse_velocity = 0.0
        overdraft_persistence_ratio = 0.0
        expense_acceleration_instability = 1.0
        recovery_half_life = 0.0
        debt_servicing_stress_index = 0.0
        emergency_depletion_velocity = 0.0
        
        if has_transaction_history:
            runway_deterioration_slope = universal_signals.compute_runway_deterioration_slope(u_tx, accs, checking_bal, snapshot_date)
            liquidity_collapse_velocity = universal_signals.compute_liquidity_collapse_velocity(u_tx, accs, checking_bal, snapshot_date)
            overdraft_persistence_ratio = universal_signals.compute_overdraft_persistence_ratio(u_tx, accs, checking_bal, snapshot_date)
            expense_acceleration_instability = universal_signals.compute_expense_acceleration_instability(u_tx, snapshot_date)
            recovery_half_life = universal_signals.compute_recovery_half_life(u_tx, accs, checking_bal, snapshot_date)
            debt_servicing_stress_index = universal_signals.compute_debt_servicing_stress_index(u_tx, (profile.get("net_income") or 0.0), snapshot_date)
            emergency_depletion_velocity = universal_signals.compute_emergency_depletion_velocity(u_tx, snapshot_date)
            
        # Calculate dynamic age based on DOB and snapshot_date
        dob_str = profile.get("dob")
        computed_age = profile.get("age") or 30
        if dob_str:
            try:
                dob_date = datetime.datetime.strptime(dob_str.split()[0], "%Y-%m-%d")
                computed_age = snapshot_date.year - dob_date.year - ((snapshot_date.month, snapshot_date.day) < (dob_date.month, dob_date.day))
            except Exception:
                pass
                
        features_list.append({
            "snapshot_id": f"{uid}_{snapshot_date.strftime('%Y%m%d')}",
            "user_id": uid,
            "snapshot_date": snapshot_date.strftime("%Y-%m-%d %H:%M:%S"),
            "age": int(computed_age),
            "dob": (profile.get("dob") or "1996-01-01"),
            "employment_status": (profile.get("employment_status") or "UNKNOWN"),
            "housing_type": (profile.get("housing_type") or "UNKNOWN"),
            "credit_score": profile.get("credit_score"), # Keep as is, can be NULL
            "impulse_spending": profile.get("impulse_spending"),
            "tracking_habits": profile.get("tracking_habits"),
            "income_stability_report": profile.get("income_stability_report"),
            "savings_habits": profile.get("savings_habits"),
            "debt_self_report": float(profile.get("debt_self_report", 0.0)) if profile.get("debt_self_report") is not None else 0.0,
            "gross_income": float(profile.get("gross_income", 0.0)) if profile.get("gross_income") is not None else 0.0,
            "net_income": float(profile.get("net_income", 0.0)) if profile.get("net_income") is not None else 0.0,
            "runway_months": float(runway_months),
            "debt_to_income_ratio": float(debt_to_income_ratio),
            "savings_rate": float(savings_rate),
            "income_volatility": float(income_volatility),
            "expense_volatility": float(expense_volatility),
            "liquidity_decay_rate": float(liquidity_decay_rate),
            "behavioural_risk_score": float(behavioural_risk_score),
            "subscription_growth_rate": float(subscription_growth_rate),
            "spending_trend_velocity": float(spending_trend_velocity),
            "total_balance": float(total_balance),
            "recent_failed_payments_30d": int(recent_failed_payments_30d),
            "overdraft_days_30d": int(overdraft_days_30d),
            "emergency_borrowing_30d": float(emergency_borrowing_30d),
            "discretionary_spend_ratio": float(discretionary_spend_ratio),
            "runway_deterioration_slope": float(runway_deterioration_slope),
            "liquidity_collapse_velocity": float(liquidity_collapse_velocity),
            "overdraft_persistence_ratio": float(overdraft_persistence_ratio),
            "expense_acceleration_instability": float(expense_acceleration_instability),
            "recovery_half_life": float(recovery_half_life),
            "debt_servicing_stress_index": float(debt_servicing_stress_index),
            "emergency_depletion_velocity": float(emergency_depletion_velocity),
            "has_income_data": int(has_income_data),
            "has_debt_data": int(has_debt_data),
            "has_transaction_history": int(has_transaction_history),
            "has_credit_score": int(has_credit_score),
            "has_questionnaire_data": int(has_questionnaire_data),
            "min_balance_months": float(min_balance_months),
            "frac_near_empty": float(frac_near_empty),
            "p10_balance_months": float(p10_balance_months),
            "balance_volatility": float(balance_volatility),
            "balance_trend": float(balance_trend),
            "arrears_months_12m": int(arrears_months_12m),
            "worst_arrears_streak": int(worst_arrears_streak),
            "ever_missed_payment": int(ever_missed_payment),
            "months_since_last_miss": int(months_since_last_miss),
            "failed_payment_count_12m": int(failed_payment_count_12m),
            "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 the
    moment a feature is added. That went wrong twice while extending the feature
    set: once writing 33 placeholders for 44 columns, once listing 44 columns for
    47 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 no
    column are skipped rather than raising, which keeps an older database working.
    """
    if df_features.empty:
        return

    conn = 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 exist
            cursor.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.columns
                   if 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:
            pass
        raise
    finally:
        conn.close()


def apply_multi_account_consolidation(df_features, db_path, snapshot_date):
    """Overwrites five features with entity-level consolidated values.

    Scoring applies exactly this transform before predicting, but snapshot
    generation did not, so the model was trained on per-account figures and
    served consolidated ones. That skew pushed the out-of-distribution rate on
    the live path from the 5% the detector was fitted for to 86.7%; removing the
    override at scoring time dropped it back to 25%.

    The correct fix is to consolidate on BOTH sides, which is what this does.
    Applying it here means the model learns the distribution it will be served.
    """
    if df_features.empty:
        return df_features

    from multi_account_intelligence import MultiAccountAggregator
    aggregator = MultiAccountAggregator(db_path)
    df_out = df_features.copy()

    for idx in df_out.index:
        # int() is load-bearing: sqlite3 binds a numpy.int64 as something that
        # matches no row and returns an EMPTY result set rather than raising, so
        # every consolidated feature silently came back 0.0 for every user.
        user_id = int(df_out.at[idx, "user_id"])
        try:
            profile = aggregator.aggregate_entity_profile(user_id, snapshot_date)
        except Exception as e:
            # A user whose consolidation fails keeps their per-account values
            # rather than being dropped from training.
            print(f"  Consolidation failed for user {user_id}: {e}")
            continue

        df_out.at[idx, "runway_months"] = profile["consolidated_runway_months"]
        df_out.at[idx, "total_balance"] = profile["unified_liquidity"]
        df_out.at[idx, "debt_to_income_ratio"] = profile["consolidated_debt_burden"]
        df_out.at[idx, "income_volatility"] = profile["entity_level_income_stability"]

        corrected_income = profile["transfer_reconciliation_summary"]["corrected_monthly_income"]
        if corrected_income > 1.0:
            df_out.at[idx, "savings_rate"] = max(-1.0, min(
                1.0, profile["entity_level_cashflow"] / corrected_income))
        else:
            df_out.at[idx, "savings_rate"] = 0.0

    return df_out


def generate_historical_snapshots(db_path=DB_PATH):
    """Generates monthly snapshots for all users dynamically relative to max transaction date."""
    conn = get_db_connection(db_path)
    cursor = conn.cursor()
    
    cursor.execute("SELECT user_id FROM users")
    user_ids = [row["user_id"] for row in cursor.fetchall()]
    
    # Retrieve max transaction date dynamically from DB
    cursor.execute("SELECT max(transaction_date) FROM transactions")
    max_date_str = cursor.fetchone()[0]
    conn.close()
    
    if not max_date_str:
        print("No transactions found in database. Cannot generate snapshots.")
        return
        
    max_date = pd.to_datetime(max_date_str).to_pydatetime()
    print(f"Max transaction date in DB: {max_date.strftime('%Y-%m-%d %H:%M:%S')}")
    
    # Generate snapshots at 330, 300, 270, 240, 210, 180, 150, 120, 90, 60, and 30 days prior to max_date
    snapshot_intervals = [330, 300, 270, 240, 210, 180, 150, 120, 90, 60, 30]
    
    print("Generating batch historical snapshots...")
    for days_prior in snapshot_intervals:
        snap_date = max_date - datetime.timedelta(days=days_prior)
        print(f"Processing snapshot date: {snap_date.strftime('%Y-%m-%d')}")
        df_snap = compute_user_features(db_path, user_ids, snap_date)
        df_snap = apply_multi_account_consolidation(df_snap, db_path, snap_date)
        save_feature_snapshots(df_snap, db_path)
        
    print("Historical snapshots generation complete.")

if __name__ == "__main__":
    generate_historical_snapshots()