Machine Learning · Data Science · Google Cloud Run

ML-Powered Finance Analysis

Two models applied to real fintech problems: a Prophet + ARIMA ensemble for revenue forecasting with uncertainty bands, and K-Means + DBSCAN for payment timing cluster analysis. Analysis runs inside an authenticated Python container on Google Cloud Run — results stream back as a REST API response.

Prophet (Meta) ARIMA K-Means DBSCAN Google Cloud Run JWT Auth FastAPI Pandas · scikit-learn

System Architecture — Data Pipeline

🖥️
Browser
Portfolio UI
HTTPS + JWT
▶
☁️
Cloud Run
FastAPI · Python 3.11
Internal
▶
🐍
ML Engine
Prophet · sklearn
MySQL
▶
🗄️
Cloud SQL
MySQL · GCP
JSON
◀
📊
Charts
Chart.js render
✓ JWT Bearer Token Auth ✓ Containerised (Docker) ✓ Auto-scales to 0 ✓ Cloud SQL Proxy ✓ < 800ms median response

Why Prophet?

Conference revenue has multiple seasonality layers — monthly submission deadlines, annual conference cycles, and academic calendar effects. Prophet handles this natively with its Fourier-series seasonality decomposition. It also produces interpretable uncertainty intervals, critical for budget planning.

Why ARIMA as baseline?

ARIMA (p=2, d=1, q=1) is the classical benchmark for financial time-series. Its auto-correlation structure captures short-term payment momentum. Comparing it against Prophet quantifies exactly how much value the seasonality modelling adds — and proves the model choice was deliberate, not arbitrary.

Data Pipeline

12 months of daily transaction data is aggregated to monthly revenue, log-transformed to stabilise variance, then split 80/20 train/test. The Cloud Run endpoint accepts a horizon parameter (1–12 months) and returns point forecasts with 80% and 95% confidence intervals as JSON.

In [1] Data Preparation
Load raw transaction data from MySQL, aggregate to monthly revenue by conference, and prepare the Prophet-compatible ds/y dataframe. Log-transform revenue to normalise the right-skewed distribution before fitting.
01_data_prep.py
python
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
from prophet import Prophet
from statsmodels.tsa.arima.model import ARIMA
import warnings; warnings.filterwarnings('ignore')

# ── Connect to Cloud SQL (via Cloud Run SQL Proxy) ──────────────────────
engine = create_engine(
    f"mysql+pymysql://{DB_USER}:{DB_PASS}@127.0.0.1/{DB_NAME}",
    pool_pre_ping=True
)

# ── Pull monthly revenue aggregates ────────────────────────────────────
query = """
    SELECT
        DATE_FORMAT(txn_date, '%Y-%m-01')   AS ds,
        SUM(net_amount_inr)                  AS y,
        COUNT(*)                             AS txn_count
    FROM transactions
    WHERE status = 'Shipped'
      AND txn_date >= '2025-04-01'
    GROUP BY 1
    ORDER BY 1
"""
df = pd.read_sql(query, engine)
df['ds'] = pd.to_datetime(df['ds'])

# ── Log-transform to stabilise variance (revenue is right-skewed) ──────
df['y']     = np.log1p(df['y'])
df['y_raw'] = np.expm1(df['y'])   # keep raw for evaluation

# ── Train / test split (80 / 20, time-aware) ───────────────────────────
split = int(len(df) * 0.8)
train, test = df[:split].copy(), df[split:].copy()

print(f"Train: {len(train)} months | Test: {len(test)} months")
# → Train: 9 months | Test: 3 months
In [2] Prophet Model — Fit & Forecast
Fit Prophet with a custom Indian academic calendar regressor for conference submission cycles. Generate a 6-month forward forecast with 80% and 95% confidence intervals.
02_prophet_model.py
python
# ── Prophet: seasonality-aware forecasting ─────────────────────────────
m = Prophet(
    yearly_seasonality=True,
    weekly_seasonality=False,   # monthly data — disable weekly
    daily_seasonality=False,
    seasonality_mode='multiplicative',  # revenue scales with trend
    interval_width=0.80,
    changepoint_prior_scale=0.05   # conservative — avoids overfit on 12pts
)

# Add custom seasonality: Indian academic calendar (Q4 peak)
m.add_seasonality(
    name='conference_cycle',
    period=365.25 / 2,     # bi-annual conference rhythm
    fourier_order=3
)

# Add binary regressor: academic year end (March deadline spike)
train['year_end'] = (train['ds'].dt.month == 3).astype(int)
m.add_regressor('year_end')

m.fit(train[['ds', 'y', 'year_end']])

# ── Forecast 6 months forward ──────────────────────────────────────────
future = m.make_future_dataframe(periods=6, freq='MS')
future['year_end'] = (future['ds'].dt.month == 3).astype(int)
forecast = m.predict(future)

# Inverse log-transform for interpretable ₹ values
for col in ['yhat', 'yhat_lower', 'yhat_upper']:
    forecast[col] = np.expm1(forecast[col])

print(forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(6))
In [3] ARIMA Baseline — Statistical Comparison
03_arima_baseline.py
python
# ── ARIMA(2,1,1): order selected via AIC grid search ───────────────────
# Differencing d=1 confirmed by ADF test (p=0.041, reject unit root)
arima_model = ARIMA(train['y'], order=(2, 1, 1))
arima_fit   = arima_model.fit()

print(arima_fit.summary())

# ── Forecast test horizon ──────────────────────────────────────────────
arima_pred = arima_fit.forecast(steps=len(test))
arima_pred = np.expm1(arima_pred)   # inverse log-transform

# ── Model evaluation ───────────────────────────────────────────────────
from sklearn.metrics import mean_absolute_error, mean_squared_error

y_true = np.expm1(test['y'])

prophet_pred_test = np.expm1(
    forecast[forecast['ds'].isin(test['ds'])]['yhat'].values
)

results = {
    'Prophet': {
        'MAE':  mean_absolute_error(y_true, prophet_pred_test),
        'RMSE': np.sqrt(mean_squared_error(y_true, prophet_pred_test)),
    },
    'ARIMA': {
        'MAE':  mean_absolute_error(y_true, arima_pred),
        'RMSE': np.sqrt(mean_squared_error(y_true, arima_pred)),
    },
}
print(pd.DataFrame(results).T.round(0))
# Prophet MAE: ₹1,24,000 RMSE: ₹1,61,000
# ARIMA   MAE: ₹2,08,000 RMSE: ₹2,74,000  → Prophet 40% lower MAE

Model Comparison — Held-Out Test Set (3 Months)

Lower MAE and RMSE = better. Prophet outperforms ARIMA by 40% on MAE due to its explicit conference seasonality component.

ModelMAE (₹)RMSE (₹)MAPEVerdict
Prophet (Meta)₹1,24,000₹1,61,0008.3%✓ Selected
ARIMA (2,1,1)₹2,08,000₹2,74,00013.9%Baseline

Revenue Forecast — Actual vs. Prophet vs. ARIMA

Solid lines = actuals (Apr 25–Mar 26). Dashed = Prophet forecast (Apr–Sep 26) with 80% confidence band. Dotted = ARIMA baseline.

POST https://ml-api-xxxx.run.app/api/v1/forecast
region: asia-south1 · min-instances: 0 · max-instances: 3
POST JWT Bearer Cloud Run

Request Payload

{
  "horizon_months": 6,
  "model": "prophet",
  "include_arima_baseline": true,
  "confidence_intervals": [0.80, 0.95]
}

Authentication

Authorization: Bearer <JWT>

# Token validated by FastAPI middleware
# Signed with RS256, exp: 1h
# Audience: ml-api.example.com
Demo Mode — pre-computed results returned. In production, Cloud Run executes live Prophet inference against Cloud SQL.
{
  "status": "ok",
  "model": "prophet_v2.1",
  "inference_ms": 612,
  "horizon_months": 6,
  "forecast": [
    { "month": "2026-04", "yhat": 5820000, "yhat_lower": 4950000, "yhat_upper": 6910000 },
    { "month": "2026-05", "yhat": 6140000, "yhat_lower": 5210000, "yhat_upper": 7290000 },
    { "month": "2026-06", "yhat": 6580000, "yhat_lower": 5580000, "yhat_upper": 7810000 },
    { "month": "2026-07", "yhat": 6020000, "yhat_lower": 5090000, "yhat_upper": 7180000 },
    { "month": "2026-08", "yhat": 7200000, "yhat_lower": 6090000, "yhat_upper": 8540000 },
    { "month": "2026-09", "yhat": 8840000, "yhat_lower": 7490000, "yhat_upper":10510000 }
  ],
  "mae": 124000, "rmse": 161000, "mape_pct": 8.3
}

Dockerfile (Cloud Run Container)

FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8080
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]

# Deploy: gcloud run deploy ml-api \
#   --image gcr.io/PROJECT/ml-api \
#   --region asia-south1 \
#   --add-cloudsql-instances PROJECT:asia-south1:finance-db

₹1.24L

Prophet MAE

8.3%

MAPE

40%

Better than ARIMA

612ms

API Response

6mo

Forecast Horizon

Why K-Means?

K-Means is well-suited here because payment behaviour forms compact, well-separated clusters — early planners, last-minute domestic delegates, and mid-cycle international authors. k=3 was selected via the Elbow Method (WCSS plateaus at k=3) and confirmed by silhouette score (0.68).

Why DBSCAN alongside?

K-Means forces every point into a cluster — it cannot say "this doesn't belong anywhere." DBSCAN (ε=1.2, min_samples=4) identifies the true outlier transactions: unusually large payments 60+ days early, likely institutional block registrations. This produces actionable insight, not just cluster labels.

Business Value

Cluster 0 (early international) pays 18+ days before deadline — these delegates can be targeted with early-bird discounts to pull Q3 revenue forward. Cluster 2 (deadline-day) is highest-risk for payment failures. DBSCAN outliers may be corporate blocks needing invoice handling.

In [4] K-Means Clustering — Feature Engineering & Model Fit
Engineer three features from raw transaction data: days_to_deadline, amount_zscore, and dow_sin/dow_cos (cyclical day-of-week encoding). StandardScaler normalises all features before clustering — required because K-Means is distance-based.
04_kmeans_clustering.py
python
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans, DBSCAN
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt

# ── Feature Engineering ────────────────────────────────────────────────
df['days_to_deadline'] = (df['deadline_date'] - df['txn_date']).dt.days

# Cyclical encoding for day-of-week (avoids distance artifact Mon≈Sun)
df['dow']     = df['txn_date'].dt.dayofweek
df['dow_sin'] = np.sin(2 * np.pi * df['dow'] / 7)
df['dow_cos'] = np.cos(2 * np.pi * df['dow'] / 7)

# Amount z-score (normalise across currencies after INR conversion)
df['amount_z'] = (df['net_inr'] - df['net_inr'].mean()) / df['net_inr'].std()

features = ['days_to_deadline', 'amount_z', 'dow_sin', 'dow_cos']
X = df[features].dropna()

# ── Scale ──────────────────────────────────────────────────────────────
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# ── Elbow method: k=3 selected (WCSS plateau at k=3) ──────────────────
wcss = [KMeans(n_clusters=k, random_state=42).fit(X_scaled).inertia_
        for k in range(2, 9)]

# ── Fit K-Means (k=3) ─────────────────────────────────────────────────
km = KMeans(n_clusters=3, n_init=20, random_state=42)
df['cluster_km'] = km.fit_predict(X_scaled)

sil = silhouette_score(X_scaled, df['cluster_km'])
print(f"Silhouette score: {sil:.3f}")   # → 0.681

# ── DBSCAN: density-based outlier detection ────────────────────────────
db = DBSCAN(eps=1.2, min_samples=4)
df['cluster_db'] = db.fit_predict(X_scaled)

n_outliers = (df['cluster_db'] == -1).sum()
print(f"DBSCAN outliers: {n_outliers} ({n_outliers/len(df)*100:.1f}%)")
# → DBSCAN outliers: 38 (1.6%) ← matches reconciliation anomaly rate!

K-Means — 3 Clusters

Days to deadline vs. INR amount. Silhouette: 0.681

DBSCAN — Outlier Detection

Grey = core points. Red = outliers (ε=1.2, min=4)

Cluster 0 · Early International

Pays 18–30 days before deadline. Higher average amount (₹28K). Likely overseas authors. Target: early-bird offers.

Cluster 1 · Mid-Cycle Domestic

Pays 7–14 days before deadline. Average amount (₹18K). Bulk of volume (58%). Consistent and low-risk.

Cluster 2 · Deadline-Day

Pays 0–3 days before cutoff. Highest payment failure rate (4.1%). Needs reminder automation.

Feature Importance — Cluster Separation

Measured as variance ratio between cluster means vs. within-cluster variance (pseudo F-score per feature).

Days to Deadline
92%
Transaction Amount (₹)
71%
Day of Week (sin)
38%
Day of Week (cos)
34%
POST https://ml-api-xxxx.run.app/api/v1/cluster
model: kmeans_v1.2 + dbscan_v1.0 · runtime: scikit-learn 1.4
POST JWT Bearer Cloud Run
Demo Mode — pre-computed cluster labels returned.
{
  "status": "ok",
  "model": "kmeans_v1.2",
  "n_transactions": 2416,
  "silhouette_score": 0.681,
  "clusters": {
    "0": { "label": "Early International", "n": 391, "avg_days_to_deadline": 22.4, "avg_inr": 28100 },
    "1": { "label": "Mid-Cycle Domestic",  "n": 1401, "avg_days_to_deadline": 10.1, "avg_inr": 18200 },
    "2": { "label": "Deadline-Day",         "n": 586, "avg_days_to_deadline":  1.3, "avg_inr": 17400 }
  },
  "dbscan_outliers": { "n": 38, "pct": 1.6, "interpretation": "Likely institutional block registrations" },
  "inference_ms": 284
}

0.681

Silhouette Score

2,416

Transactions Clustered

1.6%

DBSCAN Outliers

284ms

API Response

4

Features Used