-- 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' );