financial-risk-api / src /models /baseline.py
octavioloffaro's picture
Deploy financial risk API to Hugging Face
bc308f6
Raw History Blame Contribute Delete
8.43 kB
class BaselineModel:
"""A rule-based, fully-explainable financial risk scoring system
used for cold-starts, benchmark comparisons, and validation.
"""
def __init__(self):
# Weights for the 5 categories
self.weights = {
"runway": 0.25,
"debt_burden": 0.20,
"savings_rate": 0.20,
"behavioral": 0.20,
"profile": 0.15
}
def predict_user(self, features_dict):
"""Calculates risk scoring metrics and factor explanations from a single user's features dictionary.
Args:
features_dict (dict): Dictionary of user features
Returns:
dict: Risk scoring profile
"""
explanations = []
positive_factors = []
risk_factors = []
# 1. Runway (Weight: 25%)
runway = features_dict.get("runway_months", 0.0)
has_tx = features_dict.get("has_transaction_history", 0)
if not has_tx:
# Cold-start transaction imputation
runway_score = 50.0
risk_factors.append("Cold start: No transaction history to compute cashflow runway.")
else:
if runway >= 3.0:
runway_score = 100.0
positive_factors.append(f"Strong cash runway: {runway:.1f} months of expenses covered.")
elif runway >= 1.5:
runway_score = 75.0
positive_factors.append(f"Moderate cash runway: {runway:.1f} months of expenses covered.")
elif runway >= 0.5:
runway_score = 40.0
risk_factors.append(f"Thin cash runway: only {runway:.1f} months of expenses covered.")
else:
runway_score = 10.0
risk_factors.append(f"Critical liquidity risk: runway below 0.5 months ({runway:.2f} months).")
# 2. Debt Burden (Weight: 20%)
dti = features_dict.get("debt_to_income_ratio", 0.0)
has_debt = features_dict.get("has_debt_data", 0)
if not has_debt:
dti_score = 80.0 # Standard assumption
positive_factors.append("No active debt payments detected.")
else:
if dti <= 0.10:
dti_score = 100.0
positive_factors.append(f"Very low debt-to-income ratio ({dti*100:.1f}%).")
elif dti <= 0.30:
dti_score = 80.0
positive_factors.append(f"Manageable debt-to-income ratio ({dti*100:.1f}%).")
elif dti <= 0.50:
dti_score = 50.0
risk_factors.append(f"Elevated debt-to-income ratio ({dti*100:.1f}%).")
else:
dti_score = 10.0
risk_factors.append(f"Critical debt burden: debt-to-income ratio exceeds 50% ({dti*100:.1f}%).")
# 3. Savings Rate (Weight: 20%)
savings_rate = features_dict.get("savings_rate", 0.0)
if not has_tx:
savings_score = 50.0
else:
if savings_rate >= 0.20:
savings_score = 100.0
positive_factors.append(f"High savings rate ({savings_rate*100:.1f}% of income saved).")
elif savings_rate >= 0.05:
savings_score = 80.0
positive_factors.append(f"Positive savings rate ({savings_rate*100:.1f}% of income saved).")
elif savings_rate >= -0.05:
savings_score = 45.0
risk_factors.append("Flat cashflow: break-even savings rate.")
else:
savings_score = 10.0
risk_factors.append(f"Negative cashflow: spending exceeds income by {abs(savings_rate)*100:.1f}%.")
# 4. Behavioral Score (Weight: 20%)
behavioral_risk = features_dict.get("behavioural_risk_score", 50.0)
# Invert behavioral risk score (which is 0-100 where 100 is high risk)
# to a fitness score (100 is low risk)
beh_fit_score = 100.0 - behavioral_risk
if behavioral_risk <= 20.0:
positive_factors.append("Excellent account behavior and spending control.")
elif behavioral_risk > 60.0:
risk_factors.append(f"High-risk behaviors: gambling, failed payments, or cash advances detected (Behavioral Score: {behavioral_risk:.0f}/100).")
elif behavioral_risk > 40.0:
risk_factors.append(f"Moderate risk behaviors: occasional overdraft or impulse traits (Behavioral Score: {behavioral_risk:.0f}/100).")
# 5. Profile/Credit Score (Weight: 15%)
has_credit = features_dict.get("has_credit_score", 0)
credit_score = features_dict.get("credit_score")
if has_credit and credit_score is not None:
if credit_score >= 720:
profile_score = 100.0
positive_factors.append(f"Excellent credit bureau history (Credit Score: {credit_score}).")
elif credit_score >= 640:
profile_score = 75.0
positive_factors.append(f"Good credit bureau history (Credit Score: {credit_score}).")
elif credit_score >= 550:
profile_score = 45.0
risk_factors.append(f"Subprime credit bureau history (Credit Score: {credit_score}).")
else:
profile_score = 15.0
risk_factors.append(f"Poor credit bureau history (Credit Score: {credit_score}).")
else:
# Thin-File / Cold start profile handling using employment
employment = features_dict.get("employment_status", "UNKNOWN")
if employment == "EMPLOYED":
profile_score = 75.0
positive_factors.append("Stable W2 employment profile (no credit score).")
elif employment == "SELF_EMPLOYED":
profile_score = 55.0
risk_factors.append("Self-employed profile with unverified credit history.")
else:
profile_score = 30.0
risk_factors.append(f"Higher risk profile: status is {employment} with no credit score.")
# Calculate Weighted Points
weighted_points = (
runway_score * self.weights["runway"] +
dti_score * self.weights["debt_burden"] +
savings_score * self.weights["savings_rate"] +
beh_fit_score * self.weights["behavioral"] +
profile_score * self.weights["profile"]
)
# Scale to Credit Score Range (300 to 850)
# 10 points -> 300, 100 points -> 850
credit_like_score = 300.0 + (weighted_points - 10.0) / 90.0 * 550.0
credit_like_score = int(max(300, min(850, credit_like_score)))
# Scale to 0-100 Risk Score (where 100 is highest risk, 0 is lowest)
risk_score_100 = round(100.0 - weighted_points, 1)
risk_score_100 = max(0.0, min(100.0, risk_score_100))
# Estimate probabilities based on heuristic mapping
stress_prob = round(max(0.0, min(1.0, (100.0 - weighted_points) / 100.0)), 3)
default_prob = round(max(0.0, min(1.0, stress_prob ** 2)), 3)
liquidity_risk = round(max(0.0, min(1.0, 1.0 - (runway_score / 100.0))), 3)
# Calculate Confidence Score based on data completeness
# completeness = weighted average of presence flags
# recency / tx length is simulated as 1.0 since we have 360d of history
completeness = (
features_dict.get("has_transaction_history", 0) * 0.4 +
features_dict.get("has_questionnaire_data", 0) * 0.3 +
features_dict.get("has_credit_score", 0) * 0.2 +
features_dict.get("has_income_data", 0) * 0.1
)
confidence_score = round(max(0.1, min(1.0, completeness)), 2)
return {
"risk_score": risk_score_100,
"credit_score": credit_like_score, # 300 - 850 scale
"default_probability": float(default_prob),
"financial_stress_probability": float(stress_prob),
"liquidity_risk": float(liquidity_risk),
"confidence_score": float(confidence_score),
"top_risk_factors": risk_factors[:3],
"top_positive_factors": positive_factors[:3],
"model_type": "baseline_heuristic"
}