Design a Baseline Credit Offer Engine
Machine LearningModel answerLast updated
Design an ML recommendation engine for financial credit offers that balances default risk prediction, user acceptance propensity, risk calibration, fair lending compliance, and feedback loop mitigation.
Design an ML-driven baseline system to recommend financial credit offers (such as business cash advances or term loans).
Your design must resolve the dual objective inherent in credit recommendation: maximizing product engagement and transaction volume while strictly managing financial risk exposure.
Please address the following components:
- System Goals and Hard Constraints: Formulate the primary optimization function and state hard operational, regulatory (e.g., fair lending and adverse action notice rules), and financial safety boundaries.
- Feature Engineering & Data Pipeline Strategy: Outline core user and product features, point-in-time snapshot processing, missing data policies, and cold-start strategies for new entities or new credit products.
- Scoring Architecture & Model Formulations: Detail the modeling pipeline for Probability of Default ($PD$) and Probability of Acceptance ($P_{\text{accept}}$), calibration procedures, and the decision layer used to score and rank offers.
- Validation Metrics & Selective Labeling Strategy: Define offline validation strategies, temporal dataset splits, and approaches to handle the selective label problem (censored repayment labels).
- Fairness, Bias Loops, and Operational Monitoring: Explain techniques to prevent feedback loops, monitor model drift via Population Stability Index (PSI), and safely deploy the pipeline.
Hints
Hint 1
Decouple credit default risk (a survival/binary classification task on historic loans) from application propensity (an offer acceptance task on impressions). Risk is a hard constraint; value is an optimization goal.
Hint 2
Consider the selective label problem: you only observe default labels for candidates who were historically approved and accepted the offer. How will you collect unbiased ground truth or perform counterfactual evaluation?
Hint 3
Calibration is essential. Raw GBDT or SVM outputs cannot be directly plugged into expected monetary value calculations without risk-calibrated probabilities.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and System Objectives
A capital offer system differs from conventional content or e-commerce recommendation engines: recommending an offer to a user who accepts but defaults causes direct financial loss. We must separate credit risk assessment from product demand estimation.
Optimization Objective
For a user $u$ and credit offer $o = (\text{product_type}, \text{principal } A, \text{term } T, \text{fee } F)$, we rank eligible offers by maximizing Expected Monetary Value ($\text{EV}$):
$$\text{EV}(u, o) = P_{\text{accept}}(u, o) \times \Big[ \text{Revenue}(o) - P_{\text{default}}(u, o) \times \text{LGD} \times A - \text{Cost}_{\text{capital}} \Big]$$
Where:
- $P_{\text{accept}}(u, o)$ is the predicted probability the user accepts offer $o$.
- $P_{\text{default}}(u, o)$ is the probability of default over term $T$.
- $\text{LGD}$ is Loss Given Default (unrecoverable fraction of principal, e.g., $0.70$).
- $\text{Revenue}(o)$ includes total origination fees and expected interest payments.
- $\text{Cost}_{\text{capital}}$ is the cost to fund the offer.
Operational & Regulatory Constraints
- Risk Threshold (Hard Safety Filter): $P_{\text{default}}(u, o) \le \tau_{\text{risk}}$, configured by credit policy.
- Affordability Cap: Monthly repayment $\le \alpha \times \text{Average Monthly Cashflow}$.
- Regulatory Directives:
- Equal Credit Opportunity Act (ECOA) / Reg B: Exclude protected attributes (gender, age, ethnicity) and obvious proxies.
- Adverse Action Disclosures: For denied or downscoped offers, generate top $K$ reason codes derived from model feature contributions (e.g., SHAP values or monotonic gain attributions).
- Serving SLA: Batch pre-computation or real-time scoring within $< 100\text{ ms}$ p99.
2. System Architecture & Scoring Flow
[ Financial Records / Telemetry ] ---> [ Feature Store (Point-in-Time) ]
|
v
[ Offline / Daily Batch Pipeline ] ---> [ Candidate Generation ]
|
v
[ Hard Policy & Eligibility Gate ]
|
v
[ Parallel Scoring Architecture ]
/ \
[ Risk Engine: PD Model ] [ Propensity Engine: P_accept ]
\ /
v v
[ Value Optimization & Ranking ]
|
v
[ Post-Processing & Reason Codes ]
|
v
[ Cased Offer Cache (Redis/DynamoDB) ]
3. Feature Engineering & Cold-Start Strategy
Feature Catalog
| Category | Features | Snapshot / Window |
|---|---|---|
| Cashflow & Volume | Revenue mean/std, sales growth velocity, minimum cash balances | 30d, 90d, 365d point-in-time windows |
| Operational Health | Operating history length, transaction activity, chargeback/dispute rate | Lifetime / 90d windows |
| Credit History | Historical repayment velocity, active liabilities, external score | Latest verified snapshot |
| Offer Parameters | Principal $A$, term $T$, principal-to-monthly-revenue ratio | Static candidate parameters |
Missing Data Protocols
- Gradient Boosted Trees: Leverage native split handling for missing fields.
- Linear Baselines: Impute missing metrics using cohort medians while creating explicit binary indicator flags (
is_field_missing). - Constraint: Imputation logic must default toward conservative risk estimates rather than assuming high creditworthiness.
Cold-Start Handling
- New Entities: Entities with $< 90$ days of transactional history bypass ML scoring and are routed to a conservative rule-based policy tier with low limits and short durations.
- New Products: Estimate $P_{\text{default}}$ using existing user-level risk models. Estimate $P_{\text{accept}}$ by borrowing propensity data from similar products, allocating $10%$ of impression traffic via Thompson Sampling for dynamic exploration.
4. Modeling Pipeline Implementation
The core scoring pipeline trains two decoupled models and combines their calibrated probabilities into an expected value calculation.
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.isotonic import IsotonicRegression
class CreditOfferScoringPipeline:
def __init__(self, risk_threshold: float, lgd: float = 0.70):
self.risk_threshold = risk_threshold
self.lgd = lgd
self.pd_model = LogisticRegression(penalty='l2', C=1.0)
self.p_accept_model = LogisticRegression(penalty='l2', C=1.0)
self.pd_calibrator = IsotonicRegression(out_of_bounds='clip')
def fit_risk_model(self, X_train, y_default_train, X_val, y_default_val):
"""Fits the PD model and calibrates predicted risks using validation data."""
self.pd_model.fit(X_train, y_default_train)
raw_val_preds = self.pd_model.predict_proba(X_val)[:, 1]
self.pd_calibrator.fit(raw_val_preds, y_default_val)
def predict_calibrated_pd(self, X):
raw_preds = self.pd_model.predict_proba(X)[:, 1]
return self.pd_calibrator.transform(raw_preds)
def rank_candidate_offers(self, X_features, candidate_offers):
"""
X_features: matrix combining user and offer features
candidate_offers: list of dicts containing offer metadata
"""
raw_pd = self.pd_model.predict_proba(X_features)[:, 1]
pd_scores = self.pd_calibrator.transform(raw_pd)
p_accept_scores = self.p_accept_model.predict_proba(X_features)[:, 1]
ranked_results = []
for idx, offer in enumerate(candidate_offers):
pd = pd_scores[idx]
p_accept = p_accept_scores[idx]
# Risk Constraint Gate
if pd > self.risk_threshold:
continue
# Expected Value Scoring
revenue = offer['fee_amount']
expected_loss = pd * self.lgd * offer['principal']
net_value = revenue - expected_loss - offer['cost_of_capital']
ev = p_accept * net_value
ranked_results.append({
'offer_id': offer['offer_id'],
'expected_value': ev,
'calibrated_pd': pd,
'p_accept': p_accept
})
return sorted(ranked_results, key=lambda item: item['expected_value'], reverse=True)
Monotonicity Enforcement
To maintain defensibility under audit, enforce monotonic constraints when using GBDTs (e.g., XGBoost, LightGBM):
- Higher sales volume $\rightarrow$ Non-increasing $PD$.
- Higher chargeback rate $\rightarrow$ Non-decreasing $PD$.
5. Offline Evaluation & Selective Labeling
Data Splitting & Metrics
- Out-of-Time (OOT) Splits: Train on historical months $T_0 \dots T_{12}$, validate on $T_{13} \dots T_{15}$, and evaluate on $T_{16} \dots T_{18}$. Avoid random K-fold splits to prevent temporal leakage across credit cycles.
- Risk Model Evaluation: ROC-AUC, Kolmogorov-Smirnov ($KS > 0.40$ target), and Expected Calibration Error (ECE).
- Propensity Model Evaluation: Log-loss and Precision@K for accepted offers.
- Portfolio Level Validation: Replay historical offers to check net default rate and predicted versus realized total value.
Mitigating Selective Label Bias
Default labels ($y_{\text{default}}$) are only observed for users who were approved and accepted the offer, creating a sample selection bias.
- Randomized Exploration Band: Route $2-5%$ of applicants near the margin of eligibility to receive low-cap offers under random approval rules. This constructs an unbiased ground-truth dataset over time.
- Propensity Weighting: Weight observed training instances by inverse propensity scores $1 / P(\text{Approved} \mid X)$ during PD model fitting.
Production Monitoring
- Population Stability Index (PSI): Measure feature distribution shifts between baseline training sets and live inference datasets:
$$\text{PSI} = \sum \left( \text{Actual}% - \text{Expected}% \right) \times \ln\left( \frac{\text{Actual}%}{\text{Expected}%} \right)$$
- $\text{PSI} < 0.1$: Stable.
- $0.1 \le \text{PSI} \le 0.25$: Marginal shift; flag for review.
- $\text{PSI} > 0.25$: Significant distribution shift; trigger retraining or fall back to conservative rules.