Spaces:
Sleeping
Sleeping
github-actions[bot]
Deploy 07c02ae: Make the model defensible: state transitions, monotonic constraints, log-odds penalties
5975f7a Download src/generator.py from frigate-global/financial-risk-api: direct link, hf CLI and curl.
- Browser
- Download file 30.5 kB
-
https://huggingface.co/spaces/frigate-global/financial-risk-api/resolve/main/src/generator.py
- Command line
-
hf download hf://spaces/frigate-global/financial-risk-api/src/generator.py
-
curl -L -o generator.py https://huggingface.co/spaces/frigate-global/financial-risk-api/resolve/main/src/generator.py
30.5 kB
| import random | |
| import uuid | |
| from datetime import datetime, timedelta | |
| import sqlite3 | |
| from pathlib import Path | |
| from database import get_db_connection, DB_PATH | |
| # Set seed for reproducibility | |
| random.seed(42) | |
| PERSONAS = { | |
| "HEALTHY": { | |
| "age_range": (28, 55), | |
| "income_range": (5000, 12000), | |
| "employment": "EMPLOYED", | |
| "housing": "MORTGAGE", | |
| "dependents": (0, 3), | |
| "goals": "SAVING", | |
| "impulse": (1, 2), | |
| "tracking": (1, 2), | |
| "stability": (1, 2), | |
| "savings_habit": (1, 2), | |
| "has_credit_score": True, | |
| "credit_score_range": (700, 850), | |
| "discretionary_frac": (0.15, 0.3), | |
| "debt_payment_frac": (0.1, 0.2), | |
| "failed_pay_prob": 0.001, | |
| "overdraft_usage_prob": 0.0, | |
| }, | |
| "IMPULSIVE": { | |
| "age_range": (21, 35), | |
| "income_range": (3500, 7000), | |
| "employment": "EMPLOYED", | |
| "housing": "RENT", | |
| "dependents": (0, 1), | |
| "goals": "INVESTING", | |
| "impulse": (4, 5), | |
| "tracking": (4, 5), | |
| "stability": (2, 3), | |
| "savings_habit": (3, 5), | |
| "has_credit_score": True, | |
| "credit_score_range": (580, 680), | |
| "discretionary_frac": (0.45, 0.65), | |
| "debt_payment_frac": (0.15, 0.3), | |
| "failed_pay_prob": 0.02, | |
| "overdraft_usage_prob": 0.08, | |
| }, | |
| "VOLATILE": { | |
| "age_range": (23, 45), | |
| "income_range": (2500, 6000), | |
| "employment": "SELF_EMPLOYED", | |
| "housing": "RENT", | |
| "dependents": (0, 2), | |
| "goals": "DEBT_REPAYMENT", | |
| "impulse": (2, 4), | |
| "tracking": (2, 3), | |
| "stability": (4, 5), | |
| "savings_habit": (2, 4), | |
| "has_credit_score": False, # Thin file | |
| "credit_score_range": (None, None), | |
| "discretionary_frac": (0.2, 0.4), | |
| "debt_payment_frac": (0.05, 0.15), | |
| "failed_pay_prob": 0.015, | |
| "overdraft_usage_prob": 0.05, | |
| }, | |
| "STRESSED": { | |
| "age_range": (20, 50), | |
| "income_range": (1800, 3500), | |
| "employment": "EMPLOYED", | |
| "housing": "RENT", | |
| "dependents": (1, 4), | |
| "goals": "DEBT_REPAYMENT", | |
| "impulse": (4, 5), | |
| "tracking": (4, 5), | |
| "stability": (3, 5), | |
| "savings_habit": (4, 5), | |
| "has_credit_score": True, | |
| "credit_score_range": (350, 570), | |
| "discretionary_frac": (0.35, 0.5), | |
| "debt_payment_frac": (0.35, 0.6), # Extremely high debt burden | |
| "failed_pay_prob": 0.08, | |
| "overdraft_usage_prob": 0.25, | |
| }, | |
| "THIN_FILE": { | |
| "age_range": (18, 24), | |
| "income_range": (1000, 2200), | |
| "employment": "STUDENT", | |
| "housing": "OTHER", | |
| "dependents": (0, 0), | |
| "goals": "SAVING", | |
| "impulse": (2, 3), | |
| "tracking": (2, 3), | |
| "stability": (2, 4), | |
| "savings_habit": (2, 3), | |
| "has_credit_score": False, | |
| "credit_score_range": (None, None), | |
| "discretionary_frac": (0.2, 0.4), | |
| "debt_payment_frac": (0.0, 0.05), | |
| "failed_pay_prob": 0.005, | |
| "overdraft_usage_prob": 0.01, | |
| } | |
| } | |
| CATEGORIES = [ | |
| 'INCOME', 'RENT_MORTGAGE', 'UTILITIES', 'SUBSCRIPTION', | |
| 'GROCERIES', 'DISCRETIONARY', 'DEBT_PAYMENT', 'GAMBLING', | |
| 'CASH_ADVANCE', 'FEES', 'TRANSFER' | |
| ] | |
| # Monthly behavioural state transitions. | |
| # | |
| # Rows are the current state, values the probability of next month's state. | |
| # Deliberately sticky -- people do not reinvent themselves monthly -- but not | |
| # absorbing, so a healthy borrower can drift into difficulty and a distressed one | |
| # can recover. This is what makes a 90-day forecast a genuine forecast. | |
| STATE_TRANSITIONS = { | |
| "HEALTHY": {"HEALTHY": 0.94, "IMPULSIVE": 0.03, "VOLATILE": 0.02, "STRESSED": 0.01}, | |
| "IMPULSIVE": {"HEALTHY": 0.10, "IMPULSIVE": 0.82, "VOLATILE": 0.02, "STRESSED": 0.06}, | |
| "VOLATILE": {"HEALTHY": 0.08, "IMPULSIVE": 0.03, "VOLATILE": 0.83, "STRESSED": 0.06}, | |
| "STRESSED": {"HEALTHY": 0.12, "IMPULSIVE": 0.05, "VOLATILE": 0.05, "STRESSED": 0.78}, | |
| # Thin-file describes missing history rather than behaviour, so it mostly | |
| # persists until the borrower accumulates a record. | |
| "THIN_FILE": {"THIN_FILE": 0.85, "HEALTHY": 0.10, "STRESSED": 0.05}, | |
| } | |
| # Probability per month that any borrower suffers an external shock (job loss, | |
| # medical bill, relationship breakdown) that forces distress regardless of how | |
| # they were behaving. Without this, distress is only ever reachable by gradual | |
| # drift and the model can rule it out from a clean recent history. | |
| SHOCK_PROB_PER_MONTH = 0.012 | |
| SHOCK_DURATION_MONTHS = (2, 5) | |
| def build_state_schedule(start_state, n_months): | |
| """Returns a list of behavioural states, one per month.""" | |
| schedule = [] | |
| state = start_state | |
| shock_remaining = 0 | |
| for _ in range(n_months): | |
| if shock_remaining > 0: | |
| schedule.append("STRESSED") | |
| shock_remaining -= 1 | |
| continue | |
| if start_state != "THIN_FILE" and random.random() < SHOCK_PROB_PER_MONTH: | |
| shock_remaining = random.randint(*SHOCK_DURATION_MONTHS) - 1 | |
| state = "STRESSED" | |
| schedule.append(state) | |
| continue | |
| row = STATE_TRANSITIONS.get(state, {state: 1.0}) | |
| states, probs = list(row.keys()), list(row.values()) | |
| state = random.choices(states, weights=probs, k=1)[0] | |
| schedule.append(state) | |
| return schedule | |
| def generate_users(db_path=DB_PATH, num_users=500): | |
| """Generates user profiles and stores them in the DB.""" | |
| conn = get_db_connection(db_path) | |
| cursor = conn.cursor() | |
| # Check if we already have users | |
| cursor.execute("SELECT count(*) FROM users") | |
| if cursor.fetchone()[0] > 0: | |
| print("Users already generated.") | |
| conn.close() | |
| return | |
| print(f"Generating {num_users} users...") | |
| # Calculate sizes of each persona group | |
| ratios = { | |
| "HEALTHY": 0.70, # 350 users | |
| "IMPULSIVE": 0.10, # 50 users | |
| "VOLATILE": 0.10, # 50 users | |
| "STRESSED": 0.07, # 35 users | |
| "THIN_FILE": 0.03 # 15 users | |
| } | |
| user_list = [] | |
| for persona_name, ratio in ratios.items(): | |
| count = int(num_users * ratio) | |
| persona = PERSONAS[persona_name] | |
| for _ in range(count): | |
| age = random.randint(*persona["age_range"]) | |
| dob = (datetime.now() - timedelta(days=age*365.25 + random.randint(0, 365))).strftime("%Y-%m-%d") | |
| gross_income = round(random.uniform(*persona["income_range"]), 2) | |
| net_income = round(gross_income * random.uniform(0.75, 0.85), 2) | |
| employment_status = persona["employment"] | |
| housing_type = persona["housing"] | |
| dependents = random.randint(*persona["dependents"]) | |
| goals = persona["goals"] | |
| # Questionnaire | |
| impulse = random.randint(*persona["impulse"]) | |
| tracking = random.randint(*persona["tracking"]) | |
| stability = random.randint(*persona["stability"]) | |
| savings_habit = random.randint(*persona["savings_habit"]) | |
| debt_self_report = round(net_income * random.uniform(0, 3) * (0.0 if persona_name == "THIN_FILE" else 1.0), 2) | |
| expected_events = str(random.sample(['BABY', 'MOVING', 'WEDDING', 'CAR', 'EDUCATION', 'NONE'], k=random.randint(1, 2))) | |
| # Credit score | |
| credit_score = None | |
| if persona["has_credit_score"]: | |
| credit_score = random.randint(*persona["credit_score_range"]) | |
| user_list.append(( | |
| age, dob, gross_income, net_income, employment_status, housing_type, dependents, goals, | |
| impulse, tracking, stability, debt_self_report, savings_habit, expected_events, credit_score, | |
| persona_name # Store persona name temporarily or keep in mind for transaction generation | |
| )) | |
| # Insert users and capture IDs | |
| inserted_users = [] | |
| for u in user_list: | |
| cursor.execute(""" | |
| INSERT INTO users ( | |
| age, dob, gross_income, net_income, employment_status, housing_type, dependents, financial_goals, | |
| impulse_spending, tracking_habits, income_stability_report, debt_self_report, savings_habits, expected_life_events, credit_score | |
| ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) | |
| """, u[:-1]) | |
| user_id = cursor.lastrowid | |
| inserted_users.append((user_id, u[-1], u[3])) # (user_id, persona_name, net_income) | |
| conn.commit() | |
| conn.close() | |
| print("Users generated.") | |
| return inserted_users | |
| def generate_accounts_and_transactions(users, db_path=DB_PATH, days_history=360): | |
| """Generates bank accounts and daily transactions for all users over the timeline.""" | |
| conn = get_db_connection(db_path) | |
| cursor = conn.cursor() | |
| # Check if transaction tables are empty | |
| cursor.execute("SELECT count(*) FROM transactions") | |
| if cursor.fetchone()[0] > 0: | |
| print("Accounts and transactions already generated.") | |
| conn.close() | |
| return | |
| print(f"Generating accounts and transactions over {days_history} days...") | |
| start_date = datetime.now() - timedelta(days=days_history) | |
| accounts_to_insert = [] | |
| transactions_to_insert = [] | |
| # Prepare accounts for each user | |
| for user_id, persona_name, net_income in users: | |
| persona = PERSONAS[persona_name] | |
| # All users get a checking account | |
| checking_id = str(uuid.uuid4())[:18] | |
| # Start checking account with a reasonable balance | |
| checking_balance = round(net_income * random.uniform(0.5, 2.5), 2) | |
| if persona_name == "STRESSED": | |
| checking_balance = round(net_income * random.uniform(0.05, 0.25), 2) | |
| overdraft_limit = 0.0 | |
| if persona_name in ["IMPULSIVE", "STRESSED", "VOLATILE"]: | |
| overdraft_limit = round(net_income * random.uniform(0.2, 0.5), 2) | |
| accounts_to_insert.append(( | |
| checking_id, user_id, 'CHECKING', checking_balance, None, overdraft_limit, 'ACTIVE', start_date | |
| )) | |
| # Most healthy/impulsive/volatile users get a savings account | |
| savings_id = None | |
| if persona_name in ["HEALTHY", "IMPULSIVE", "VOLATILE"] and random.random() > 0.1: | |
| savings_id = str(uuid.uuid4())[:18] | |
| savings_balance = round(net_income * random.uniform(1.0, 10.0) if persona_name == "HEALTHY" else net_income * random.uniform(0.1, 1.0), 2) | |
| accounts_to_insert.append(( | |
| savings_id, user_id, 'SAVINGS', savings_balance, None, 0.0, 'ACTIVE', start_date | |
| )) | |
| # Stressed or Impulsive might have a Credit Card (Credit Limit) | |
| cc_id = None | |
| if persona_name in ["STRESSED", "IMPULSIVE", "HEALTHY"] and random.random() > 0.3: | |
| cc_id = str(uuid.uuid4())[:18] | |
| cc_limit = round(net_income * random.uniform(1.0, 3.0), 2) | |
| cc_balance = round(cc_limit * random.uniform(0.1, 0.9) if persona_name in ["STRESSED", "IMPULSIVE"] else cc_limit * random.uniform(0.0, 0.2), 2) | |
| accounts_to_insert.append(( | |
| cc_id, user_id, 'CREDIT_CARD', -cc_balance, cc_limit, 0.0, 'ACTIVE', start_date | |
| )) | |
| # Simulate transactions daily | |
| running_balances = {checking_id: checking_balance} | |
| if savings_id: | |
| running_balances[savings_id] = savings_balance | |
| if cc_id: | |
| running_balances[cc_id] = -cc_balance | |
| # Behavioural state over time, not a fixed type for life. | |
| # | |
| # Previously each user kept one persona for their entire history, which | |
| # made the future trivially predictable: a user's 90-day outcome label was | |
| # unchanged across consecutive windows 97.2% of the time, and | |
| # behavioural_risk_score ALONE scored 0.978 AUC. The model was reading a | |
| # static label off the features rather than inferring a trajectory, so its | |
| # discrimination figures meant nothing. | |
| # | |
| # Real borrowers deteriorate, recover, and get hit by shocks. The schedule | |
| # below moves each user between states month to month, so knowing someone | |
| # is healthy today genuinely does not tell you they will be in 90 days. | |
| original_persona = persona_name | |
| state_schedule = build_state_schedule(persona_name, days_history // 30 + 2) | |
| recovered = False | |
| # Generate transactions | |
| for day in range(days_history): | |
| curr_date = start_date + timedelta(days=day) | |
| day_of_month = curr_date.day | |
| day_of_week = curr_date.weekday() | |
| # Adopt this month's behavioural state. | |
| persona_name = state_schedule[min(day // 30, len(state_schedule) - 1)] | |
| persona = PERSONAS[persona_name] | |
| # `recovered` suppresses payment failures and income shocks; it now | |
| # simply means "not currently in distress". | |
| recovered = (persona_name != "STRESSED") | |
| # --- 1. INCOME DEPOSITS --- | |
| # Healthy/Impulsive/Stressed are employed: monthly or bi-weekly income | |
| if persona_name in ["HEALTHY", "IMPULSIVE", "STRESSED"]: | |
| pay_day = 1 if persona_name == "HEALTHY" else 15 | |
| if day_of_month == pay_day: | |
| income_amt = net_income | |
| # Stressed user might experience an income shock (drop in income towards the end) | |
| if persona_name == "STRESSED" and day > (days_history * 0.7) and not recovered: | |
| income_amt = round(net_income * random.uniform(0.5, 0.8), 2) | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, income_amt, 'INCOME', 'Salary Deposit', 0 | |
| )) | |
| running_balances[checking_id] += income_amt | |
| elif persona_name == "VOLATILE": | |
| if day_of_week == 4: # Every Friday | |
| income_amt = round((net_income / 4.3) * random.uniform(0.4, 1.8), 2) | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, income_amt, 'INCOME', 'Gig Payout', 0 | |
| )) | |
| running_balances[checking_id] += income_amt | |
| elif persona_name == "THIN_FILE": | |
| if day_of_month in [5, 20]: | |
| income_amt = round(net_income / 2.0, 2) | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, income_amt, 'INCOME', 'Student Allowance', 0 | |
| )) | |
| running_balances[checking_id] += income_amt | |
| # --- 1b. POSITIVE SHOCK (Windfall/Bonus) --- | |
| # 5% chance on the 15th for any user to receive extra funds (tax refund, bonus) | |
| if day_of_month == 15 and random.random() < 0.05: | |
| windfall = round(net_income * random.uniform(0.1, 0.4), 2) | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, windfall, 'INCOME', 'Refund/Bonus Inflow', 0 | |
| )) | |
| running_balances[checking_id] += windfall | |
| # --- 2. FIXED EXPENSES (Rent/Mortgage, Utilities, Debt Payments) --- | |
| # Rent/Mortgage on the 1st | |
| if day_of_month == 1: | |
| rent_amt = round(net_income * (0.25 if persona_name == "HEALTHY" else 0.35 if persona_name != "THIN_FILE" else 0.45), 2) | |
| # Check for failure: rent payment fails if checking available balance is insufficient, | |
| # OR based on failed_pay_prob (higher for non-recovered stressed users). | |
| is_failed = 0 | |
| available_checking = running_balances[checking_id] + overdraft_limit | |
| curr_fail_prob = 0.002 if recovered else persona["failed_pay_prob"] | |
| if available_checking < rent_amt: | |
| is_failed = 1 if random.random() < 0.85 else 0 # 85% fail rate on insufficient funds | |
| elif random.random() < curr_fail_prob: | |
| is_failed = 1 | |
| if not is_failed: | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, -rent_amt, 'RENT_MORTGAGE', 'Rent Payment', 0 | |
| )) | |
| running_balances[checking_id] -= rent_amt | |
| else: | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, -rent_amt, 'RENT_MORTGAGE', 'Rent Payment (FAILED)', 1 | |
| )) | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, -35.0, 'FEES', 'Overdraft/NSF Fee', 0 | |
| )) | |
| running_balances[checking_id] -= 35.0 | |
| # Utilities on the 5th | |
| if day_of_month == 5: | |
| utility_amt = round(random.uniform(100, 300), 2) | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, -utility_amt, 'UTILITIES', 'Energy/Water Bill', 0 | |
| )) | |
| running_balances[checking_id] -= utility_amt | |
| # Debt Payments on the 10th (Loan/Credit Card minimums) | |
| if day_of_month == 10 and persona_name != "THIN_FILE": | |
| debt_payment = round(net_income * random.uniform(*persona["debt_payment_frac"]), 2) | |
| if cc_id: | |
| # CC Payment fails if checking is short | |
| is_failed = 0 | |
| available_checking = running_balances[checking_id] + overdraft_limit | |
| if available_checking < debt_payment: | |
| is_failed = 1 if random.random() < 0.85 else 0 | |
| elif random.random() < (0.002 if recovered else persona["failed_pay_prob"]): | |
| is_failed = 1 | |
| if not is_failed: | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, -debt_payment, 'DEBT_PAYMENT', 'Credit Card Payment', 0 | |
| )) | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], cc_id, user_id, curr_date, debt_payment, 'DEBT_PAYMENT', 'Payment Received', 0 | |
| )) | |
| running_balances[checking_id] -= debt_payment | |
| running_balances[cc_id] += debt_payment | |
| else: | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, -debt_payment, 'DEBT_PAYMENT', 'Credit Card Payment (FAILED)', 1 | |
| )) | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, -15.0, 'FEES', 'Late Payment Fee', 0 | |
| )) | |
| running_balances[checking_id] -= 15.0 | |
| else: | |
| # Regular loan payment | |
| is_failed = 0 | |
| available_checking = running_balances[checking_id] + overdraft_limit | |
| if available_checking < debt_payment: | |
| is_failed = 1 if random.random() < 0.85 else 0 | |
| elif random.random() < (0.002 if recovered else persona["failed_pay_prob"]): | |
| is_failed = 1 | |
| if not is_failed: | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, -debt_payment, 'DEBT_PAYMENT', 'Loan Repayment', 0 | |
| )) | |
| running_balances[checking_id] -= debt_payment | |
| else: | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, -debt_payment, 'DEBT_PAYMENT', 'Loan Repayment (MISSED)', 1 | |
| )) | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, -15.0, 'FEES', 'Late Payment Fee', 0 | |
| )) | |
| running_balances[checking_id] -= 15.0 | |
| # --- 3. DAILY/WEEKLY VARIABLE EXPENSES (Groceries, Discretionary, Subscriptions) --- | |
| # Groceries twice a week (Wed, Sat) | |
| if day_of_week in [2, 5]: | |
| groc_amt = round(random.uniform(60, 150), 2) | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, -groc_amt, 'GROCERIES', 'Supermarket', 0 | |
| )) | |
| running_balances[checking_id] -= groc_amt | |
| # Discretionary (Shopping, dining out) | |
| disc_prob = 0.85 if persona_name == "IMPULSIVE" else 0.4 if persona_name == "HEALTHY" else 0.5 | |
| # Affordability Elasticity: scale down discretionary spend probability if cash balance is low | |
| if running_balances[checking_id] < 50.0: | |
| disc_prob = 0.03 | |
| elif running_balances[checking_id] < 150.0: | |
| disc_prob = disc_prob * 0.25 | |
| if random.random() < disc_prob: | |
| daily_limit = (net_income * random.uniform(*persona["discretionary_frac"])) / 15.0 | |
| disc_amt = round(random.uniform(5.0, daily_limit * 2.0), 2) | |
| # Route to CC if checking is low and CC space is available | |
| available_checking = running_balances[checking_id] + overdraft_limit | |
| if available_checking < disc_amt: | |
| if cc_id and (-running_balances[cc_id] + disc_amt < cc_limit): | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], cc_id, user_id, curr_date, -disc_amt, 'DISCRETIONARY', 'Credit Card POS Transaction', 0 | |
| )) | |
| running_balances[cc_id] -= disc_amt | |
| else: | |
| if random.random() < (0.002 if recovered else persona["failed_pay_prob"]): | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, -disc_amt, 'DISCRETIONARY', 'Point of Sale (FAILED)', 1 | |
| )) | |
| else: | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, -disc_amt, 'DISCRETIONARY', 'POS Transaction', 0 | |
| )) | |
| running_balances[checking_id] -= disc_amt | |
| # Subscriptions on the 20th | |
| if day_of_month == 20: | |
| sub_count = 3 | |
| if persona_name == "IMPULSIVE": | |
| sub_count = 3 + int(day / 60) | |
| elif persona_name == "HEALTHY": | |
| sub_count = 2 | |
| for s in range(sub_count): | |
| sub_amt = round(random.uniform(9.99, 29.99), 2) | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, -sub_amt, 'SUBSCRIPTION', f'Subscription {s+1}', 0 | |
| )) | |
| running_balances[checking_id] -= sub_amt | |
| # --- 4. BEHAVIORAL RISK EVENTS (Gambling, Cash Advance, Overdraft Charges) --- | |
| # Gambling (Baseline chance for all users, highest for impulsive and stressed) | |
| gambling_prob = 0.08 if (persona_name in ["IMPULSIVE", "STRESSED"] and not recovered) else 0.015 | |
| if random.random() < gambling_prob: | |
| gambling_amt = round(random.uniform(20.0, 100.0), 2) | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, -gambling_amt, 'GAMBLING', 'Online Betting', 0 | |
| )) | |
| running_balances[checking_id] -= gambling_amt | |
| # Payday loans / Cash Advance | |
| # Triggers dynamically for ANY user when checking balance goes negative, with varying persona probabilities | |
| if running_balances[checking_id] < 0: | |
| borrow_prob = 0.18 if (persona_name == "STRESSED" and not recovered) else 0.05 if persona_name in ["IMPULSIVE", "VOLATILE"] else 0.005 | |
| if random.random() < borrow_prob: | |
| borrow_amt = round(random.choice([200.0, 300.0, 500.0]), 2) | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, borrow_amt, 'CASH_ADVANCE', 'Quick Loan Deposit', 0 | |
| )) | |
| running_balances[checking_id] += borrow_amt | |
| # Schedule payback 15 days later with 20% interest | |
| payback_date = curr_date + timedelta(days=15) | |
| payback_amt = round(borrow_amt * 1.20, 2) | |
| if payback_date < start_date + timedelta(days=days_history): | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, payback_date, -payback_amt, 'DEBT_PAYMENT', 'Quick Loan Repayment', 0 | |
| )) | |
| running_balances[checking_id] -= payback_amt | |
| # Overdraft daily fee if account remains negative | |
| if running_balances[checking_id] < 0 and random.random() < persona["overdraft_usage_prob"]: | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, -5.0, 'FEES', 'Overdraft Daily Fee', 0 | |
| )) | |
| running_balances[checking_id] -= 5.0 | |
| # --- 4.5. RANDOM DAILY SHOCKS (NOISE/REALISM) --- | |
| # 0.5% chance of an emergency expense shock on any day for any user (medical bill, car repair, home issue) | |
| if random.random() < 0.005: | |
| shock_types = [ | |
| ("Medical Bill", 200, 800), | |
| ("Car Repair", 150, 600), | |
| ("Urgent Home Appliance", 100, 400), | |
| ("Unplanned Travel", 200, 1000) | |
| ] | |
| shock_desc, min_val, max_val = random.choice(shock_types) | |
| shock_amt = round(random.uniform(min_val, max_val), 2) | |
| pay_channel = checking_id | |
| if cc_id and random.random() > 0.5: | |
| pay_channel = cc_id | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], pay_channel, user_id, curr_date, -shock_amt, 'DISCRETIONARY', f'Emergency: {shock_desc}', 0 | |
| )) | |
| running_balances[pay_channel] -= shock_amt | |
| # --- 5. INTERNAL TRANSFERS --- | |
| # Savings deposits for healthy users | |
| if persona_name == "HEALTHY" and day_of_month == 2 and savings_id: | |
| savings_deposit = round(net_income * 0.15, 2) | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], checking_id, user_id, curr_date, -savings_deposit, 'TRANSFER', 'Transfer to Savings', 0 | |
| )) | |
| transactions_to_insert.append(( | |
| str(uuid.uuid4())[:18], savings_id, user_id, curr_date, savings_deposit, 'TRANSFER', 'Transfer from Checking', 0 | |
| )) | |
| running_balances[checking_id] -= savings_deposit | |
| running_balances[savings_id] += savings_deposit | |
| # Write back final balances to accounts for database state consistency | |
| cursor.execute("UPDATE accounts SET balance = ? WHERE account_id = ?", (round(running_balances[checking_id], 2), checking_id)) | |
| if savings_id: | |
| cursor.execute("UPDATE accounts SET balance = ? WHERE account_id = ?", (round(running_balances[savings_id], 2), savings_id)) | |
| if cc_id: | |
| cursor.execute("UPDATE accounts SET balance = ? WHERE account_id = ?", (round(running_balances[cc_id], 2), cc_id)) | |
| # Bulk insert accounts and transactions | |
| cursor.executemany(""" | |
| INSERT INTO accounts (account_id, user_id, account_type, balance, credit_limit, overdraft_limit, status, created_at) | |
| VALUES (?, ?, ?, ?, ?, ?, ?, ?) | |
| """, accounts_to_insert) | |
| cursor.executemany(""" | |
| INSERT INTO transactions (transaction_id, account_id, user_id, transaction_date, amount, category, description, is_failed) | |
| VALUES (?, ?, ?, ?, ?, ?, ?, ?) | |
| """, transactions_to_insert) | |
| conn.commit() | |
| conn.close() | |
| print(f"Generated {len(accounts_to_insert)} accounts and {len(transactions_to_insert)} transactions.") | |
| def setup_demo_data(db_path=DB_PATH): | |
| """Orchestrates demographic and transaction database creation using NayaOne ingest.""" | |
| import os | |
| dataset_source = os.environ.get("DATASET_SOURCE", "SME").upper() | |
| if dataset_source == "UK": | |
| print("Seeding database using NayaOne UK Open Banking Transactions dataset...") | |
| from nayaone_ingest import run_nayaone_ingest | |
| run_nayaone_ingest(db_path=db_path) | |
| elif dataset_source == "CZECH": | |
| print("Seeding database using NayaOne Czech Transactions dataset...") | |
| from czech_ingest import run_czech_ingest | |
| run_czech_ingest(db_path=db_path) | |
| elif dataset_source == "INDIA": | |
| print("Seeding database using NayaOne India Bank Transactions dataset...") | |
| from india_ingest import run_india_ingest | |
| run_india_ingest(db_path=db_path) | |
| else: | |
| print("Seeding database using NayaOne SME Bank Transactions dataset...") | |
| from sme_ingest import run_sme_ingest | |
| run_sme_ingest(db_path=db_path) | |
| if __name__ == "__main__": | |
| from database import init_db | |
| init_db() | |
| setup_demo_data() | |