Great — since you're experienced in Python and time-series forecasting, I’ll walk you through a scalable, modular, quant-oriented forecasting framework tailored for unsecured credit origination, from data ingestion and processing, to model benchmarks, forecasting methods, diagnostics, and evaluation. You can scale this for live systems later.
🔧 Step 1: Framework Overview
We'll model Origination as the composite of 3 main drivers:
[
\textbf{Origination}_t = \text{Applications}_t \times \text{Net Take Rate}_t \times \text{Avg Credit Amount}_t
]
You’ll forecast each component individually to make it interpretable, modular, and to allow independent dynamics (e.g., seasonality in applications, regime shifts in take rate). Then, combine forecasts multiplicatively.
You'll also:
- Preprocess and analyze each component (seasonality, stationarity).
- Fit and compare multiple models (statistical + ML).
- Test backtest errors using classic metrics.
- Combine models only if it adds information (e.g., weighted ensembles).
🧱 Step 2: Data Prep
Assumptions:
You have a DataFrame with time granularity = daily, with columns like:
df = pd.DataFrame({
'date': pd.date_range(start='2022-01-01', end='2024-06-18', freq='D'),
'applications': ..., # observed daily applications
'net_take_rate': ..., # pct [0-1]
'avg_credit_amount': ..., # in currency units
})
Add:
df['origination'] = (
df['applications'] * df['net_take_rate'] * df['avg_credit_amount']
)
🔬 Step 3: Diagnostics
📊 A. Statistical Analysis:
Run decomposition on each driver:
from statsmodels.tsa.seasonal import STL
for var in ['applications', 'net_take_rate', 'avg_credit_amount']:
result = STL(df[var], period=7).fit()
result.plot()
plt.title(var.title())
plt.show()
🔍 B. Stationarity Check:
Differencing for ARIMA-type models.
from statsmodels.tsa.stattools import adfuller
for var in ['applications', 'net_take_rate', 'avg_credit_amount']:
pval = adfuller(df[var].dropna())[1]
print(f"{var}: {'Stationary' if pval < 0.05 else 'Not Stationary'} (p={pval:.4f})")
Use log transforms or seasonal differencing where appropriate.
📈 Step 4: Modeling Approaches
We'll fit at least 3 models per time series:
- Naïve/Seasonal Naïve: baseline, useful for benchmarking.
- SARIMA: effective for autocorrelated, seasonal data.
- Prophet (or NeuralProphet): interpretable, handles holiday effects.
- XGBoost / ML: for multivariate/context-aware modeling.
- (Optional): LSTM/DeepAR — if your data’s volume and complexity warrants it.
Let’s write a generic modeling pipeline for 1 time series.
You can use a high-level pipeline like darts, sktime, or go raw [statsmodels + custom framework].
🧪 Step 5: Backtest Engine and Error Evaluation
Essential to evaluate each driver, then compute backtest error for the combined Origination forecast.
from sklearn.metrics import mean_absolute_error, mean_absolute_percentage_error
import numpy as np
def get_origination(apps, rate, amt):
return apps * rate * amt
def evaluate_forecast(y_true, y_pred, name="Model"):
print(f"📈 Evaluation for {name}")
print(f"MAE: {mean_absolute_error(y_true, y_pred):,.2f}")
print(f"MAPE: {mean_absolute_percentage_error(y_true, y_pred)*100:.2f}%")
print()
You’ll want to:
- Backtest each component forecast separately using expanding or rolling window.
- Then multiply predicted series.
- Compute total origination errors.
⚙️ Step 6: Forecast Execution Plan
Here’s a full processing plan.
A. Forecasting Each Component
For example, SARIMA + Prophet:
from statsmodels.tsa.statespace.sarimax import SARIMAX
from prophet import Prophet
def forecast_sarima(ts, steps=365, order=(1, 1, 1), seasonal_order=(1, 1, 1, 7)):
model = SARIMAX(ts, order=order, seasonal_order=seasonal_order)
res = model.fit(disp=False)
pred = res.get_forecast(steps).predicted_mean
return pred
def forecast_prophet(ts, steps=365):
df = ts.reset_index()
df.columns = ['ds', 'y']
m = Prophet()
m.fit(df)
future = m.make_future_dataframe(periods=steps)
forecast = m.predict(future)
return forecast.set_index('ds')['yhat'].iloc[-steps:]
Repeat for applications, take rate, and credit amount.
You can also try benchmark_dummy (seasonal naive):
# Seasonal Naive for baseline
def forecast_seasonal_naive(ts, horizon=365, seasonality=365):
return ts[-seasonality:].values[:horizon]
B. Combine the Models
apps_pred = forecast_sarima(df['applications']) # or Prophet etc.
take_pred = forecast_prophet(df['net_take_rate'])
amt_pred = forecast_sarima(df['avg_credit_amount'])
orig_pred = get_origination(apps_pred, take_pred, amt_pred)
C. Backtest Framework
For each method combo, implement:
from tqdm import tqdm
def backtest_origination(df, start_day, horizon=30):
results = []
for t in tqdm(range(start_day, len(df) - horizon)):
train = df.iloc[:t]
test = df.iloc[t:t+horizon]
apps_pred = forecast_sarima(train['applications'], steps=horizon)
take_pred = forecast_sarima(train['net_take_rate'], steps=horizon)
amt_pred = forecast_sarima(train['avg_credit_amount'], steps=horizon)
pred = get_origination(apps_pred, take_pred, amt_pred)
true = get_origination(test['applications'], test['net_take_rate'], test['avg_credit_amount'])
mae = mean_absolute_error(true, pred)
mape = mean_absolute_percentage_error(true, pred)
results.append({'t': test.index[0], 'mae': mae, 'mape': mape})
return pd.DataFrame(results)
🔬 Step 7: Model Selection / Ranking
Use cross-validation scores across drivers and origination. Criteria:
- Mean error
- Error variance
- Last-period fit — check recency effects
- Sensitivity to anomalies
You can also define a loss function combining this, e.g.:
score = 0.5 * MAPE_app + 0.3 * MAPE_take + 0.2 * MAPE_amt
⚗️ Step 8: Handle Anomalies and Exogenous Shocks
For each series, detect anomalies using Isolation Forest / statistical thresholds:
from sklearn.ensemble import IsolationForest
def detect_anomalies(ts, contamination=0.01):
clf = IsolationForest(contamination=contamination)
preds = clf.fit_predict(ts.values.reshape(-1, 1))
return pd.Series(preds == -1, index=ts.index)
Flag or remove outliers. Also consider:
- Holiday effects
- Promotions / marketing
- Central bank rate changes — Use exogenous variables (X)
You can expand SARIMAX or use
Prophet with regressors.
📤 Step 9: 365-Day Forecast Deployment
Once model is finalized:
final_apps = forecast_sarima(df['applications'], 365)
final_take = forecast_sarima(df['net_take_rate'], 365)
final_amt = forecast_sarima(df['avg_credit_amount'], 365)
forecast_final = get_origination(final_apps, final_take, final_amt)
forecast_final.plot(title='365-Day Unsecured Credit Origination Forecast')
Keep track of forecast intervals if using Prophet.
📋 Output Example
| Date | Forecast_Origination |
|---|
| 2024-06-20 | 2,430,512 |
| 2024-06-21 | 2,470,828 |
| ... | ... |
| 2025-06-19 | 2,891,123 |
🧠 Optional: Add Interpretability
Use SHAP on ML models to explain which features (e.g., day-of-week, holidays, recent take rate trend) drive forecasts.
🧩 Final Notes
- Treat each component separately if diversifying modeling (stat vs ML).
- You may ensemble components: e.g., SARIMA and Prophet avg.
- Adjust horizon depending on business cycle sensitivity.
- Keep updating model monthly post-live with sliding retrain window.
Would you like a complete Python skeleton of this pipeline as .py or notebook version with DASH dashboard support?
Let me know — I can generate the full script ready for production/deployment.