financial-risk-api / src /labels.py
octavioloffaro's picture
Claude Opus 5
Fix default label to use the worst episode, and consolidate at snapshot time
ca7ca11
Raw History Blame Contribute Delete
9.15 kB
import datetime
import pandas as pd
from pathlib import Path
from database import get_db_connection, DB_PATH
from features import get_historical_balances
def parse_datetime(dt_str):
"""Robustly parses datetime strings with or without fractional seconds."""
if not dt_str:
return None
return pd.to_datetime(dt_str).to_pydatetime()
def compute_labels_for_snapshots(db_path=DB_PATH):
"""Processes all snapshots that are at least 90 days old and computes their
corresponding 90-day risk outcome labels.
"""
conn = get_db_connection(db_path)
cursor = conn.cursor()
# 1. Fetch feature snapshots that need outcomes (snapshot_date <= current_date - 90 days)
# To keep it simple and clean, we calculate for all snapshots that have enough forward history in the DB.
# Check max transaction date in the DB to know what date we can look forward to.
cursor.execute("SELECT max(transaction_date) FROM transactions")
max_tx_date_str = cursor.fetchone()[0]
if not max_tx_date_str:
print("No transactions found. Cannot generate labels.")
conn.close()
return
max_tx_date = parse_datetime(max_tx_date_str)
max_snapshot_allowed = max_tx_date - datetime.timedelta(days=90)
cursor.execute("""
SELECT snapshot_id, user_id, snapshot_date, total_balance
FROM feature_snapshots
WHERE snapshot_date <= ?
""", (max_snapshot_allowed.strftime("%Y-%m-%d %H:%M:%S"),))
snapshots = cursor.fetchall()
print(f"Found {len(snapshots)} snapshots eligible for 90-day outcome labels (prior to {max_snapshot_allowed.strftime('%Y-%m-%d')}).")
if len(snapshots) == 0:
conn.close()
return
outcomes_to_insert = []
# Fetch all transactions that might fall in the outcome window (optimization: read all transactions)
# We will process user by user to keep memory low and calculations simple
for snap in snapshots:
snap_id = snap["snapshot_id"]
uid = snap["user_id"]
snap_date_str = snap["snapshot_date"]
snap_date = parse_datetime(snap_date_str)
target_date = snap_date + datetime.timedelta(days=90)
# 1. Fetch transactions in the [snap_date, target_date] interval for this user
cursor.execute("""
SELECT account_id, transaction_date, amount, category, description, is_failed
FROM transactions
WHERE user_id = ? AND transaction_date >= ? AND transaction_date <= ?
ORDER BY transaction_date ASC
""", (uid, snap_date_str, target_date.strftime("%Y-%m-%d %H:%M:%S")))
txs = cursor.fetchall()
# 2. Get CC balances at snap_date and target_date to calculate debt increase
# Reconstruct balance at target_date
target_bals = get_historical_balances(cursor, [uid], target_date)
snap_bals = get_historical_balances(cursor, [uid], snap_date)
# cc balance is negative, so CC debt = -cc_balance
cc_debt_snap = 0.0
cc_debt_target = 0.0
for acc_id, acc in snap_bals.items():
if acc["account_type"] == "CREDIT_CARD":
cc_debt_snap += -acc["reconstructed_balance"]
for acc_id, acc in target_bals.items():
if acc["account_type"] == "CREDIT_CARD":
cc_debt_target += -acc["reconstructed_balance"]
# 3. Calculate sub-labels
# A. Missed payment
missed_payment_90d = 0
for tx in txs:
if tx["is_failed"] == 1 and tx["category"] in ["DEBT_PAYMENT", "RENT_MORTGAGE"]:
missed_payment_90d = 1
break
if tx["category"] == "FEES" and "Late Payment" in (tx["description"] or ""):
missed_payment_90d = 1
break
# B. Overdraft Usage
overdraft_usage_90d = 0
for tx in txs:
if tx["category"] == "FEES" and "Overdraft" in (tx["description"] or ""):
overdraft_usage_90d = 1
break
# C. Negative Balance > 3 consecutive days
# We need to trace checking balance day-by-day in [snap_date, target_date]
# Reconstruct checking balance at snap_date
checking_bal = 0.0
checking_acc_ids = []
for acc_id, acc in snap_bals.items():
if acc["account_type"] == "CHECKING":
checking_bal += acc["reconstructed_balance"]
checking_acc_ids.append(acc_id)
negative_balance_90d = 0
consecutive_negative_days = 0
current_bal = checking_bal
# We look day-by-day
# Let's map daily net transactions
daily_changes = {}
for tx in txs:
if tx["account_id"] in checking_acc_ids and tx["is_failed"] == 0:
tx_day = parse_datetime(tx["transaction_date"]).date()
daily_changes[tx_day] = daily_changes.get(tx_day, 0.0) + tx["amount"]
# Step through 90 days.
# max_consecutive_negative_days records the LONGEST run in the window.
# consecutive_negative_days is only a running counter and is zero whenever
# the balance recovers, so reading it after the loop reports the state on
# day 90 rather than the worst episode -- see the default label below.
max_consecutive_negative_days = 0
temp_date = snap_date.date()
for d in range(91):
curr_day = temp_date + datetime.timedelta(days=d)
# Add changes of the day
current_bal += daily_changes.get(curr_day, 0.0)
if current_bal < 0:
consecutive_negative_days += 1
if consecutive_negative_days > max_consecutive_negative_days:
max_consecutive_negative_days = consecutive_negative_days
if current_bal < -100.0: # Check if overdraft usage is significant
overdraft_usage_90d = 1
else:
consecutive_negative_days = 0
if consecutive_negative_days > 3:
negative_balance_90d = 1
# D. Debt Increase > 20%
# CC debt goes up by > 20% and the increase is significant (> $200), orCC debt goes from 0 to > $500
debt_increase_90d = 0
if cc_debt_snap > 100.0:
if (cc_debt_target - cc_debt_snap) / cc_debt_snap > 0.20 and (cc_debt_target - cc_debt_snap) > 200.0:
debt_increase_90d = 1
elif cc_debt_target > 500.0:
debt_increase_90d = 1
# E. Emergency Borrowing
emergency_borrowing_90d = 0
for tx in txs:
if tx["category"] == "CASH_ADVANCE":
emergency_borrowing_90d = 1
break
# --- Combined Target Labels ---
# financial_stress_90d = 1 if ANY occur
financial_stress_90d = 1 if (
missed_payment_90d == 1 or
overdraft_usage_90d == 1 or
negative_balance_90d == 1 or
debt_increase_90d == 1 or
emergency_borrowing_90d == 1
) else 0
# Default = severe delinquency: multiple missed payments (>= 3) or a
# prolonged negative balance (> 25 consecutive days) at any point in the
# window.
#
# This previously tested consecutive_negative_days, whose value after the
# loop is the run length on day 90, not the longest run. A borrower who
# spent 60 straight days overdrawn and recovered by day 88 was labelled
# healthy, while one who happened to be 26 days into a run on the final
# day was labelled a default. The target for the more severe of the two
# models was measuring the wrong thing.
default_90d = 0
failed_pay_count = sum(1 for tx in txs if tx["is_failed"] == 1 and tx["category"] in ["DEBT_PAYMENT", "RENT_MORTGAGE"])
if failed_pay_count >= 3 or max_consecutive_negative_days > 25:
default_90d = 1
outcomes_to_insert.append((
f"outcome_{snap_id}", uid, snap_date_str, target_date.strftime("%Y-%m-%d %H:%M:%S"),
financial_stress_90d, default_90d, missed_payment_90d, overdraft_usage_90d,
negative_balance_90d, debt_increase_90d, emergency_borrowing_90d
))
# Bulk insert outcomes
cursor.executemany("""
INSERT OR REPLACE INTO risk_outcomes (
outcome_id, user_id, snapshot_date, target_date,
financial_stress_90d, default_90d, missed_payment_90d, overdraft_usage_90d,
negative_balance_90d, debt_increase_90d, emergency_borrowing_90d
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", outcomes_to_insert)
conn.commit()
conn.close()
print(f"Computed and saved {len(outcomes_to_insert)} risk outcome labels in the database.")
if __name__ == "__main__":
compute_labels_for_snapshots()