python
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from scipy import stats
import warnings
warnings.filterwarnings('ignore')
# ============================================================================
# Sherlock's Paid Social MMM Sanity Overlay
# ============================================================================
# This overlay provides:
# 1. PRIORS: Bayesian-inspired priors for key Paid Social MMM parameters
# (ROAS, adstock decay, saturation alpha, hill exponent).
# 2. CONSTRAINTS: Hard/soft bounds to enforce economic sanity.
# 3. DRIFT CHECKS: Monitoring for model degradation (MAPE, param stability,
# contribution drift, holdout perf).
#
# Usage:
# overlay = PaidSocialMMMSanityOverlay(data_df, model_params_df)
# priors = overlay.apply_priors()
# constraints_passed = overlay.enforce_constraints(model_params_df)
# drift_report = overlay.check_drift(historical_models_df)
# overlay.build_dashboard()
#
# Assumes input data:
# - data_df: pd.DataFrame with cols ['date', 'spend_social', 'sales', 'imps_social']
# - model_params_df: pd.DataFrame with MMM posterior params (e.g., from PyMC/LightweightMMM)
# cols: ['roas_mean', 'roas_lower', 'roas_upper', 'decay_mean', ...]
# - historical_models_df: For drift, stacked params over time windows.
# ============================================================================
class PaidSocialMMMSanityOverlay:
def __init__(self, data_df, geo_mean_roas=1.5):
"""
Initialize with data and optional geo_mean_roas (industry prior).
"""
self.data = data_df.copy()
self.geo_mean_roas = geo_mean_roas # Global prior mean ROAS for paid social
self.priors = self._define_priors()
self.drift_thresholds = {
'mape': 0.15, # MAPE >15% flags drift
'roas_drift': 0.3, # |ΔROAS| >30% flags
'param_cv': 0.25, # CoV >25% flags instability
}
def _define_priors(self):
"""Sherlock's Deductive Priors for Paid Social MMM."""
# Informed by benchmarks: Meta/TT ads ROAS 1-3x, decay 3-7 days, sat alpha 1e-6 to 1e-4
return {
'roas': stats.lognorm(s=0.4, scale=self.geo_mean_roas), # Lognormal ~1.5 mean, skewed right
'decay': stats.beta(3, 2), # Beta prior: mean ~0.6 (half-life ~3 days for daily data)
'sat_alpha': stats.gamma(2, scale=1e-5), # Gamma for saturation threshold
'hill_k': stats.gamma(2, scale=2), # Hill exponent ~2-5 for diminishing returns
'base_sales': stats.norm(loc=np.mean(self.data['sales']) * 0.7, scale=np.std(self.data['sales']) * 0.1),
}
def apply_priors(self, posterior_samples_df):
"""
Shrink posterior towards priors using empirical Bayes.
Returns adjusted params DataFrame.
"""
adjusted = posterior_samples_df.copy()
for param, prior_dist in self.priors.items():
if param in adjusted.columns:
prior_mean = prior_dist.mean()
prior_std = prior_dist.std()
post_mean = adjusted[f'{param}_mean'].iloc[0]
post_std = (adjusted[f'{param}_upper'].iloc[0] - adjusted[f'{param}_lower'].iloc[0]) / (2 * 1.96)
# Shrinkage: weighted average (precision-weighted)
shrinkage = prior_std**2 / (prior_std**2 + post_std**2)
adjusted[f'{param}_prior_adj'] = shrinkage * prior_mean + (1 - shrinkage) * post_mean
print("🕵️♂️ Priors applied: Shrunk ROAS by {:.1%} towards {:.2f}x benchmark.".format(
1 - (adjusted['roas_prior_adj'].iloc[0] / posterior_samples_df['roas_mean'].iloc[0]),
self.geo_mean_roas
))
return adjusted
def enforce_constraints(self, params_df, hard=True):
"""
Apply constraints:
- Hard: Clip to bounds (economic sanity).
- Soft: Flag warnings.
Returns (constrained_df, flags_df).
"""
constraints = {
'roas_mean': (0.5, 5.0), # ROAS 0.5-5x realistic for social
'decay_mean': (0.1, 0.9), # Decay 0.1-0.9 (half-life 1-30 days)
'sat_alpha_mean': (1e-7, 1e-3), # Saturation starts reasonable
'hill_k_mean': (1.0, 10.0), # Diminishing returns
}
flags = pd.DataFrame(index=params_df.index, columns=list(constraints.keys()))
constrained = params_df.copy()
for param, (low, high) in constraints.items():
if param in params_df.columns:
orig = constrained[param]
constrained[param] = np.clip(orig, low, high)
flags[param] = (orig < low) | (orig > high)
passed = flags.sum().sum() == 0
status = "✅ ALL CONSTRAINTS PASSED" if passed else "⚠️ CONSTRAINT VIOLATIONS"
if hard:
print(f"🛡️ {status} | Clipped {flags.sum().sum()} params.")
else:
print(f"🛡️ {status} | {flags.sum().sum()} soft flags.")
return constrained, flags
def check_drift(self, historical_models_df, current_params_df, holdout_df=None):
"""
Drift checks across time windows.
- Param stability: CoV of means.
- ROAS drift: % change from median historical.
- Predictive: MAPE on rolling holdout.
Returns drift_report dict with flags.
"""
report = {'flags': {}, 'summary': {}}
# 1. Param stability (CoV)
param_cols = [col for col in historical_models_df.columns if col.endswith('_mean')]
cov = historical_models_df[param_cols].std() / historical_models_df[param_cols].mean()
unstable = cov > self.drift_thresholds['param_cv']
report['flags']['param_cv'] = unstable.to_dict()
report['summary']['param_cov'] = cov.to_dict()
# 2. ROAS drift
hist_roas_median = historical_models_df['roas_mean'].median()
current_roas = current_params_df['roas_mean'].iloc[0]
roas_drift_pct = abs((current_roas - hist_roas_median) / hist_roas_median)
report['flags']['roas_drift'] = roas_drift_pct > self.drift_thresholds['roas_drift']
report['summary']['roas_drift_pct'] = roas_drift_pct
# 3. Holdout MAPE (if provided)
if holdout_df is not None:
# Assume holdout_df has 'actual_sales', 'predicted_sales'
mape = np.mean(np.abs(holdout_df['actual_sales'] - holdout_df['predicted_sales']) / holdout_df['actual_sales'])
report['flags']['mape'] = mape > self.drift_thresholds['mape']
report['summary']['mape'] = mape
drift_count = sum(report['flags'].values())
status = "🟢 NO DRIFT" if drift_count == 0 else f"🔴 {drift_count} DRIFT FLAGS"
print(f"📈 DRIFT CHECK: {status}")
return report
def build_dashboard(self, params_df, drift_report=None, priors_df=None):
"""Interactive Plotly dashboard for sanity viz."""
fig = make_subplots(
rows=2, cols=2,
subplot_titles=('ROAS Prior & Constraints', 'Decay & Saturation Priors',
'Historical Param Drift', 'Drift Metrics'),
specs=[[{"secondary_y": False}, {"secondary_y": False}],
[{"secondary_y": False}, {"secondary_y": False}]]
)
# 1. ROAS
fig.add_trace(go.Histogram(x=params_df['roas_mean'], name='Posterior', opacity=0.7), row=1, col=1)
fig.add_hline(y=self.priors['roas'].mean(), line_dash="dash", annotation_text="Prior Mean", row=1, col=1)
fig.add_vrect(x0=0.5, x1=5.0, fillcolor="green", opacity=0.2, line_width=0, row=1, col=1)
# 2. Decay/Sat
fig.add_trace(go.Scatter(x=params_df['decay_mean'], y=params_df['sat_alpha_mean'],
mode='markers', name='Posteriors'), row=1, col=2)
fig.add_hline(y=self.priors['decay'].mean(), line_dash="dash", row=1, col=2)
fig.add_vline(x=self.priors['sat_alpha'].mean(), line_dash="dash", row=1, col=2)
# 3. Historical Drift (dummy if no drift_report)
if drift_report:
params_hist = pd.DataFrame(drift_report['summary']['param_cov'], index=['CoV']).T
fig.add_trace(go.Bar(x=params_hist.index, y=params_hist['CoV'], name='Param CoV'), row=2, col=1)
fig.add_hline(y=self.drift_thresholds['param_cv'], line_dash="dash", row=2, col=1)
# 4. Drift Metrics
if drift_report:
metrics = pd.Series(drift_report['summary']).drop('param_cov')
colors = ['green' if not flag else 'red' for flag in drift_report['flags'].values()]
fig.add_trace(go.Bar(x=metrics.index, y=metrics.values, marker_color=colors), row=2, col=2)
fig.update_layout(height=800, title_text="🕵️♂️ Sherlock's Paid Social MMM Sanity Dashboard")
fig.show()
def run_full_suite(self, posterior_df, historical_df, holdout_df=None):
"""One-click full sanity check."""
print("🔍 Running Sherlock's Full MMM Sanity Suite...")
priors_adj = self.apply_priors(posterior_df)
constrained, flags = self.enforce_constraints(priors_adj)
drift = self.check_drift(historical_df, constrained, holdout_df)
self.build_dashboard(constrained, drift, priors_adj)
return {
'priors': priors_adj,
'constrained': constrained,
'flags': flags,
'drift': drift
}
# ============================================================================
# Example Usage (Synthetic Data)
# ============================================================================
if __name__ == "__main__":
# Synthetic data
np.random.seed(42)
dates = pd.date_range('2023-01-01', periods=365)
data = pd.DataFrame({
'date': dates,
'spend_social': np.random.poisson(1000, 365).cumsum() / 10,
'sales': 10000 + np.random.normal(0, 2000, 365),
'imps_social': np.random.poisson(1e6, 365)
})
# Mock posterior params
posterior = pd.DataFrame({
'roas_mean': [2.1], 'roas_lower': [1.5], 'roas_upper': [2.8],
'decay_mean': [0.65], 'sat_alpha_mean': [2e-5], 'hill_k_mean': [2.8]
})
# Mock historical
historical = pd.DataFrame({
'roas_mean': np.random.normal(1.8, 0.3, 12),
'decay_mean': np.random.normal(0.6, 0.1, 12),
})
# Run suite
overlay = PaidSocialMMMSanityOverlay(data)
results = overlay.run_full_suite(posterior, historical)
print("💼 Sanity suite complete. Model is ready for optimization.")