Spaces:
Sleeping
Sleeping
File size: 14,598 Bytes
bc308f6 fdd922a d13dd0c b025087 bc308f6 f38e611 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 | -- Database Schema for Financial Risk Scoring System
-- Designed for ANSI/PostgreSQL compatibility, running on SQLite for local verification
-- 1. Users Table (Profile + Questionnaire + Credit Bureau Data)
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
age INTEGER NOT NULL,
dob TEXT NOT NULL,
gross_income REAL NOT NULL,
net_income REAL NOT NULL,
employment_status TEXT NOT NULL, -- e.g., 'EMPLOYED', 'SELF_EMPLOYED', 'UNEMPLOYED', 'STUDENT', 'RETIRED'
housing_type TEXT NOT NULL, -- e.g., 'RENT', 'MORTGAGE', 'OWNED', 'OTHER'
dependents INTEGER DEFAULT 0,
financial_goals TEXT, -- e.g., 'SAVING', 'DEBT_REPAYMENT', 'INVESTING'
-- Questionnaire Data (1-5 scales or direct responses)
impulse_spending INTEGER, -- Self-report rating of spending control (1 = highly controlled, 5 = highly impulsive)
tracking_habits INTEGER, -- Self-report of budget tracking (1 = daily, 5 = none)
income_stability_report INTEGER, -- Self-report income stability (1 = highly stable, 5 = highly volatile)
debt_self_report REAL DEFAULT 0.0,
savings_habits INTEGER, -- Self-report savings consistency (1 = save regularly, 5 = never save)
expected_life_events TEXT, -- Expected major expenditures in next 6-12m (JSON list, e.g. "['BABY', 'MOVING']")
-- Traditional Credit Bureau Data (can be NULL for thin-file / cold-start users)
credit_score INTEGER
);
-- 2. Accounts Table
CREATE TABLE IF NOT EXISTS accounts (
account_id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL,
account_type TEXT NOT NULL, -- e.g., 'CHECKING', 'SAVINGS', 'CREDIT_CARD', 'LOAN'
balance REAL NOT NULL DEFAULT 0.0,
credit_limit REAL, -- Relevant for credit cards/lines of credit
overdraft_limit REAL DEFAULT 0.0,
status TEXT NOT NULL, -- e.g., 'ACTIVE', 'CLOSED', 'SUSPENDED'
created_at TIMESTAMP NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(user_id)
);
-- 3. Transactions Table
CREATE TABLE IF NOT EXISTS transactions (
transaction_id TEXT PRIMARY KEY,
account_id TEXT NOT NULL,
user_id INTEGER NOT NULL,
transaction_date TIMESTAMP NOT NULL,
amount REAL NOT NULL, -- Positive for inflows (credits), Negative for outflows (debits)
category TEXT NOT NULL, -- e.g., 'INCOME', 'RENT_MORTGAGE', 'UTILITIES', 'SUBSCRIPTION', 'GROCERIES', 'DISCRETIONARY', 'DEBT_PAYMENT', 'GAMBLING', 'CASH_ADVANCE', 'FEES', 'TRANSFER'
description TEXT,
is_failed BOOLEAN NOT NULL DEFAULT 0,
FOREIGN KEY(account_id) REFERENCES accounts(account_id),
FOREIGN KEY(user_id) REFERENCES users(user_id)
);
-- Indexes for performance on transaction time-series aggregations
CREATE INDEX IF NOT EXISTS idx_transactions_user_date ON transactions(user_id, transaction_date);
CREATE INDEX IF NOT EXISTS idx_transactions_category ON transactions(category);
-- 4. Feature Snapshots Table (CRITICAL: time-series snapshots, no overwriting)
CREATE TABLE IF NOT EXISTS feature_snapshots (
snapshot_id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL,
snapshot_date TIMESTAMP NOT NULL,
-- Demographics/Base Profile
age INTEGER,
employment_status TEXT,
housing_type TEXT,
credit_score INTEGER,
-- Primary Derived Features
runway_months REAL,
debt_to_income_ratio REAL,
savings_rate REAL,
income_volatility REAL,
expense_volatility REAL,
liquidity_decay_rate REAL,
behavioural_risk_score REAL,
subscription_growth_rate REAL,
spending_trend_velocity REAL,
-- Extra Transactional & Structural Features
total_balance REAL,
recent_failed_payments_30d INTEGER,
overdraft_days_30d INTEGER,
emergency_borrowing_30d REAL,
discretionary_spend_ratio REAL,
-- Universal Invariant Behavioural Signals
runway_deterioration_slope REAL,
liquidity_collapse_velocity REAL,
overdraft_persistence_ratio REAL,
expense_acceleration_instability REAL,
recovery_half_life REAL,
debt_servicing_stress_index REAL,
emergency_depletion_velocity REAL,
-- Missingness flags (1 = missing, 0 = present)
has_income_data INTEGER NOT NULL,
has_debt_data INTEGER NOT NULL,
has_transaction_history INTEGER NOT NULL,
has_credit_score INTEGER NOT NULL,
has_questionnaire_data INTEGER NOT NULL,
-- Balance-path features. On real adjudicated outcomes the share of the window
-- spent near-empty scores 0.857 AUC alone, against 0.708 for the whole
-- previous feature set: what predicts default is the path, not a snapshot.
min_balance_months REAL NOT NULL DEFAULT 0,
frac_near_empty REAL NOT NULL DEFAULT 0,
p10_balance_months REAL NOT NULL DEFAULT 0,
balance_volatility REAL NOT NULL DEFAULT 0,
balance_trend REAL NOT NULL DEFAULT 0,
-- Delinquency ladder over 12 months. On 6,636 real defaults these six match
-- all seventeen other features on AUC and beat them on decile lift.
arrears_months_12m INTEGER NOT NULL DEFAULT 0,
worst_arrears_streak INTEGER NOT NULL DEFAULT 0,
ever_missed_payment INTEGER NOT NULL DEFAULT 0,
months_since_last_miss INTEGER NOT NULL DEFAULT 0,
failed_payment_count_12m INTEGER NOT NULL DEFAULT 0,
arrears_trend REAL NOT NULL DEFAULT 0,
-- External credit exposure and income continuity. On 262 real defaults the
-- share of outflow going to other credit products was the single strongest
-- signal available from a transaction feed.
other_credit_ratio REAL NOT NULL DEFAULT 0,
gambling_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)
);
CREATE INDEX IF NOT EXISTS idx_feature_snapshots_user_date ON feature_snapshots(user_id, snapshot_date);
-- 5. Risk Outcomes Table (Aligned label targets for supervised learning)
CREATE TABLE IF NOT EXISTS risk_outcomes (
outcome_id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL,
snapshot_date TIMESTAMP NOT NULL, -- Point of time when features were snapshot
target_date TIMESTAMP NOT NULL, -- End of prediction window (snapshot_date + 90 days)
-- Labels (1 = true/occurred, 0 = false/did not occur in [snapshot_date, target_date])
financial_stress_90d INTEGER NOT NULL DEFAULT 0,
default_90d INTEGER NOT NULL DEFAULT 0,
missed_payment_90d INTEGER NOT NULL DEFAULT 0,
overdraft_usage_90d INTEGER NOT NULL DEFAULT 0,
negative_balance_90d INTEGER NOT NULL DEFAULT 0,
debt_increase_90d INTEGER NOT NULL DEFAULT 0,
emergency_borrowing_90d INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY(user_id) REFERENCES users(user_id)
);
CREATE INDEX IF NOT EXISTS idx_risk_outcomes_user_date ON risk_outcomes(user_id, snapshot_date);
-- 6. Model Predictions Table (Full auditing and drift tracking)
CREATE TABLE IF NOT EXISTS model_predictions (
prediction_id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL,
snapshot_date TIMESTAMP NOT NULL,
predicted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
model_version TEXT NOT NULL,
-- Model Output Metrics
risk_score REAL NOT NULL, -- e.g. 300 - 850 or 0 - 100
default_probability REAL NOT NULL, -- 0.0 - 1.0 calibrated
financial_stress_probability REAL NOT NULL, -- 0.0 - 1.0 calibrated
liquidity_risk REAL NOT NULL, -- 0.0 - 1.0 calibrated
confidence_score REAL NOT NULL, -- 0.0 - 1.0 based on data completeness
-- Explainability (SHAP & Factors)
shap_explanations TEXT NOT NULL, -- JSON map of feature -> SHAP value
top_risk_factors TEXT NOT NULL, -- JSON list of readable explanations
top_positive_factors TEXT NOT NULL, -- JSON list of readable explanations
FOREIGN KEY(user_id) REFERENCES users(user_id)
);
CREATE INDEX IF NOT EXISTS idx_model_predictions_user_date ON model_predictions(user_id, snapshot_date);
CREATE INDEX IF NOT EXISTS idx_model_predictions_score ON model_predictions(risk_score);
-- 7. Shadow Model Predictions Table (Telemetry and drift comparison)
CREATE TABLE IF NOT EXISTS shadow_model_predictions (
prediction_id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL,
snapshot_date TIMESTAMP NOT NULL,
predicted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
model_version TEXT NOT NULL,
risk_score REAL NOT NULL,
default_probability REAL NOT NULL,
financial_stress_probability REAL NOT NULL,
liquidity_risk REAL NOT NULL,
confidence_score REAL NOT NULL,
champion_prediction_id TEXT,
FOREIGN KEY(user_id) REFERENCES users(user_id)
);
CREATE INDEX IF NOT EXISTS idx_shadow_predictions_user_date ON shadow_model_predictions(user_id, snapshot_date);
-- 8. Repayment Outcomes Table (Actual observed customer outcomes)
CREATE TABLE IF NOT EXISTS repayment_outcomes (
outcome_id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL,
recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
outcome_type TEXT NOT NULL, -- e.g., 'MISSED_PAYMENT', 'ARREARS', 'COLLECTIONS', 'DEFAULT', 'BOUNCED_DIRECT_DEBIT', 'RESTRUCTURING', 'RECOVERY', 'SETTLEMENT', 'STABILIZATION'
severity REAL NOT NULL DEFAULT 1.0, -- numerical weight indicating event severity
label_confidence REAL NOT NULL DEFAULT 1.0,
days_past_due INTEGER DEFAULT 0,
amount REAL DEFAULT 0.0,
FOREIGN KEY(user_id) REFERENCES users(user_id)
);
CREATE INDEX IF NOT EXISTS idx_repayment_outcomes_user ON repayment_outcomes(user_id);
-- 9. Human Overrides Table (Audits analyst adjustments and AI overrides)
CREATE TABLE IF NOT EXISTS human_overrides (
override_id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL,
analyst_id TEXT NOT NULL,
action_taken TEXT NOT NULL, -- e.g., 'APPROVE_OVERRIDE', 'REJECT_OVERRIDE', 'CREDIT_LIMIT_ADJUST'
original_decision TEXT NOT NULL,
new_decision TEXT NOT NULL,
original_credit_limit REAL NOT NULL,
new_credit_limit REAL NOT NULL,
reviewer_confidence REAL NOT NULL DEFAULT 1.0,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(user_id) REFERENCES users(user_id)
);
CREATE INDEX IF NOT EXISTS idx_human_overrides_user ON human_overrides(user_id);
-- 10. Feature Trust Logs Table (Tracks Feature Trust Scores over time)
CREATE TABLE IF NOT EXISTS feature_trust_logs (
log_id INTEGER PRIMARY KEY AUTOINCREMENT,
logged_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
model_version TEXT NOT NULL,
feature_name TEXT NOT NULL,
trust_score REAL NOT NULL,
stability_score REAL NOT NULL,
drift_score REAL NOT NULL,
causal_score REAL NOT NULL,
status TEXT NOT NULL -- e.g., 'ACTIVE', 'DECAYED', 'SUPPRESSED'
);
CREATE INDEX IF NOT EXISTS idx_feature_trust_logs_feat ON feature_trust_logs(feature_name);
-- 11. Calibration Memory Table (Tracks ECE and recalibrations)
CREATE TABLE IF NOT EXISTS calibration_memory (
log_id INTEGER PRIMARY KEY AUTOINCREMENT,
logged_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
model_version TEXT NOT NULL,
ece REAL NOT NULL,
brier REAL NOT NULL,
calibration_drift REAL NOT NULL,
recalibration_triggered BOOLEAN NOT NULL DEFAULT 0,
recalibration_reason TEXT
);
-- 12. Archetype Evolution Logs Table (Tracks clustering shifts)
CREATE TABLE IF NOT EXISTS archetype_evolution_logs (
log_id INTEGER PRIMARY KEY AUTOINCREMENT,
logged_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
cluster_centroids TEXT NOT NULL, -- JSON representation of centroids
active_archetypes TEXT NOT NULL, -- JSON list of active archetype labels
transition_matrix TEXT NOT NULL, -- JSON representation of transitions
action_taken TEXT NOT NULL -- e.g., 'INITIALIZED', 'STABLE', 'MERGE', 'SPLIT'
);
-- 13. Portfolio Telemetry Table (Tracks portfolio aggregates)
CREATE TABLE IF NOT EXISTS portfolio_telemetry (
log_id INTEGER PRIMARY KEY AUTOINCREMENT,
logged_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
portfolio_size INTEGER NOT NULL,
expected_loss REAL NOT NULL,
stress_concentration REAL NOT NULL, -- ratio of vulnerable users
population_drift_psi REAL NOT NULL,
correlated_collapse_risk REAL NOT NULL
);
-- 14. Autonomous Learning Runs Table (Logs incremental run metadata)
CREATE TABLE IF NOT EXISTS autonomous_learning_runs (
run_id INTEGER PRIMARY KEY AUTOINCREMENT,
started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
micro_batches_processed INTEGER NOT NULL,
repayments_ingested INTEGER NOT NULL,
recalibrations_triggered INTEGER NOT NULL,
retrainings_triggered INTEGER NOT NULL,
governance_passed BOOLEAN NOT NULL,
real_data_ratio REAL NOT NULL,
metadata TEXT NOT NULL -- JSON representation of run details
);
-- 15. API Keys Table (Secures public and internal access)
CREATE TABLE IF NOT EXISTS api_keys (
key_id INTEGER PRIMARY KEY AUTOINCREMENT,
-- Digest of the key, not the key. A bearer secret stored verbatim means
-- anyone with read access to this table holds every live credential.
-- api_key is retained for compatibility with databases created before this
-- change, which declare it NOT NULL. It now holds the SAME digest, never a
-- usable key: no column in this table contains a credential that works.
api_key_hash TEXT UNIQUE,
api_key TEXT UNIQUE,
client_name TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
status TEXT NOT NULL DEFAULT 'ACTIVE' -- 'ACTIVE', 'REVOKED'
);
|