financial-risk-api / src /archetypes.py
octavioloffaro's picture
Deploy financial risk API to Hugging Face
bc308f6
Raw History Blame Contribute Delete
3.61 kB
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
class BehaviouralArchetypeDiscoverer:
"""Clusters user trajectories into distinct behavioural archetypes dynamically based on centroids."""
def __init__(self, n_clusters=6, random_state=42):
self.n_clusters = n_clusters
self.random_state = random_state
self.scaler = StandardScaler()
self.kmeans = KMeans(n_clusters=n_clusters, random_state=random_state, n_init=5)
self.is_fitted = False
self.archetype_mapping = {}
def fit(self, df_features, feature_cols):
"""Fits KMeans on user temporal features and names the archetypes based on centroid parameters."""
X = df_features[feature_cols].fillna(0.0).values
X_scaled = self.scaler.fit_transform(X)
self.kmeans.fit(X_scaled)
self.is_fitted = True
# Name centroids dynamically
centroids = self.kmeans.cluster_centers_
# Invert scaling to read real values
centroids_real = self.scaler.inverse_transform(centroids)
# We assign labels based on feature priorities:
# We find indices of runway_months, debt_to_income_ratio, savings_rate, behavioural_risk_score
runway_idx = feature_cols.index("runway_months") if "runway_months" in feature_cols else 0
dti_idx = feature_cols.index("debt_to_income_ratio") if "debt_to_income_ratio" in feature_cols else 0
savings_idx = feature_cols.index("savings_rate") if "savings_rate" in feature_cols else 0
risk_idx = feature_cols.index("behavioural_risk_score") if "behavioural_risk_score" in feature_cols else 0
scores = []
for k in range(self.n_clusters):
cent = centroids_real[k]
runway = cent[runway_idx]
dti = cent[dti_idx]
savings = cent[savings_idx]
risk = cent[risk_idx]
# Simple sorting score: high score is healthy, low score is distress
score = runway + 2.0 * savings - 2.0 * dti - 0.05 * risk
scores.append((k, score, runway, dti, risk))
# Sort clusters from healthiest to most distressed
scores.sort(key=lambda x: x[1], reverse=True)
# Archetype labeling:
# Index 0: Stable Savers
# Index 1: Liquidity Oscillators (high volatility/savings mix)
# Index 2: Paycheck-to-Paycheck
# Index 3: Resilient Recoverers (high recovery indicators)
# Index 4: Chronic Overdrafters
# Index 5: Debt Spiral Users
labels = [
"Stable Savers",
"Liquidity Oscillators",
"Paycheck-to-Paycheck",
"Resilient Recoverers",
"Chronic Overdrafters",
"Debt Spiral Users"
]
for idx, (k, *_) in enumerate(scores):
label = labels[min(idx, len(labels) - 1)]
self.archetype_mapping[k] = label
print("Mapped behavioral archetypes dynamically to cluster centroids.")
def predict_archetype(self, df_features, feature_cols):
"""Predicts descriptive archetype labels for a dataframe of features."""
if not self.is_fitted:
return ["Stable Savers"] * len(df_features)
X = df_features[feature_cols].fillna(0.0).values
X_scaled = self.scaler.transform(X)
clusters = self.kmeans.predict(X_scaled)
return [self.archetype_mapping.get(c, "Stable Savers") for c in clusters]