import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
class CACGuardrail:
"""
A CAC (Customer Acquisition Cost) Guardrail with saturation detection and dynamic caps.
Features:
- Tracks spend and acquisitions over time.
- Computes real-time CAC (spend / acquisitions).
- Detects saturation using linear regression on cumulative spend vs. acquisitions:
- Low R² score indicates non-linear growth (saturation).
- Increasing marginal CAC (recent vs. historical).
- Applies caps: Hard daily/weekly spend caps, dynamically reduced on saturation.
- Alerts and auto-pause recommendations.
Usage:
guardrail = CACGuardrail(max_cac=50.0, saturation_r2_threshold=0.85, max_daily_spend=10000)
guardrail.update(datetime.now(), spend=5000, new_acquisitions=120)
if guardrail.should_cap_next_spend(proposed_spend=2000):
print("Spend capped!")
"""
def __init__(
self,
max_cac: float = 50.0, # Maximum acceptable CAC
saturation_r2_threshold: float = 0.85, # R² below this = saturation (diminishing returns)
saturation_marginal_multiplier: float = 1.5, # Recent CAC > historical * this = saturation
max_daily_spend: float = 10000.0, # Hard daily cap
max_weekly_spend: float = 50000.0, # Hard weekly cap
saturation_cap_reduction: float = 0.5, # Reduce cap by this factor on saturation
lookback_days: int = 30, # Days for historical avg CAC
window_size: int = 7 # Days for recent marginal CAC
):
self.max_cac = max_cac
self.saturation_r2_threshold = saturation_r2_threshold
self.saturation_marginal_multiplier = saturation_marginal_multiplier
self.max_daily_spend = max_daily_spend
self.max_weekly_spend = max_weekly_spend
self.saturation_cap_reduction = saturation_cap_reduction
self.lookback_days = lookback_days
self.window_size = window_size
self.data: List[Dict] = [] # List of {'timestamp': dt, 'spend': float, 'acquisitions': int}
self.is_saturated = False
self.current_cap_reduction = 1.0 # Starts at full cap
def update(self, timestamp: datetime, spend: float, new_acquisitions: int) -> Dict:
"""
Update with new data point (daily granularity recommended).
Returns status dict.
"""
if new_acquisitions <= 0 and spend > 0:
raise ValueError("Acquisitions must be >0 if spend >0")
self.data.append({
'timestamp': timestamp,
'spend': spend,
'acquisitions': new_acquisitions
})
# Keep only recent data
cutoff = timestamp - timedelta(days=self.lookback_days * 2)
self.data = [d for d in self.data if d['timestamp'] > cutoff]
status = self._compute_status()
self.is_saturated = status['is_saturated']
self.current_cap_reduction = saturation_cap_reduction if self.is_saturated else 1.0
return status
def _compute_status(self) -> Dict:
if len(self.data) < 3:
return {'cac': 0, 'is_saturated': False, 'r2_score': 1.0, 'recommendation': 'Insufficient data'}
df = pd.DataFrame(self.data).sort_values('timestamp')
df['cum_spend'] = df['spend'].cumsum()
df['cum_acq'] = df['acquisitions'].cumsum()
total_cac = df['cum_spend'].iloc[-1] / df['cum_acq'].iloc[-1]
# Saturation Detection 1: Linear Regression R² on cum_spend vs cum_acq
X = df['cum_spend'].values.reshape(-1, 1)
y = df['cum_acq'].values
model = LinearRegression().fit(X, y)
y_pred = model.predict(X)
r2 = r2_score(y, y_pred)
# Saturation Detection 2: Marginal CAC (recent window vs historical avg)
recent_df = df.tail(self.window_size)
historical_df = df.iloc[:-self.window_size] if len(df) > self.window_size else df
recent_cac = recent_df['spend'].sum() / recent_df['acquisitions'].sum()
hist_cac = historical_df['spend'].sum() / historical_df['acquisitions'].sum() if len(historical_df) > 0 else recent_cac
is_saturated_r2 = r2 < self.saturation_r2_threshold
is_saturated_marginal = recent_cac > (hist_cac * self.saturation_marginal_multiplier)
is_saturated = is_saturated_r2 or is_saturated_marginal
recommendation = 'OK'
if total_cac > self.max_cac:
recommendation = 'High CAC - Review'
elif is_saturated:
recommendation = 'SATURATED - Pause & Optimize'
return {
'cac': total_cac,
'is_saturated': is_saturated,
'r2_score': r2,
'recent_cac': recent_cac,
'hist_cac': hist_cac,
'recommendation': recommendation
}
def get_current_daily_cap(self, date: Optional[datetime] = None) -> float:
"""Get effective daily spend cap for a given date."""
if date is None:
date = datetime.now()
effective_max = self.max_daily_spend * self.current_cap_reduction
return min(effective_max, self._get_remaining_daily_cap(date))
def get_current_weekly_cap(self, date: Optional[datetime] = None) -> float:
"""Get effective weekly spend cap for a given date."""
if date is None:
date = datetime.now()
week_start = date - timedelta(days=date.weekday())
effective_max = self.max_weekly_spend * self.current_cap_reduction
return min(effective_max, self._get_remaining_weekly_cap(week_start))
def should_cap_next_spend(self, proposed_spend: float, date: Optional[datetime] = None) -> bool:
"""Check if proposed spend exceeds caps or saturation limits."""
if date is None:
date = datetime.now()
daily_cap = self.get_current_daily_cap(date)
weekly_cap_remaining = self._get_remaining_weekly_cap(date - timedelta(days=date.weekday()))
return proposed_spend > daily_cap or proposed_spend > weekly_cap_remaining
def _get_remaining_daily_cap(self, date: datetime) -> float:
"""Remaining spend allowed today."""
today_data = [d for d in self.data if d['timestamp'].date() == date.date()]
spent_today = sum(d['spend'] for d in today_data)
return max(0, self.max_daily_spend - spent_today)
def _get_remaining_weekly_cap(self, week_start: datetime) -> float:
"""Remaining spend allowed this week."""
week_data = [d for d in self.data if week_start <= d['timestamp'] < week_start + timedelta(days=7)]
spent_week = sum(d['spend'] for d in week_data)
return max(0, self.max_weekly_spend - spent_week)
def get_status_report(self) -> Dict:
"""Full status report."""
if not self.data:
return {'error': 'No data'}
latest_status = self._compute_status()
latest_ts = self.data[-1]['timestamp']
return {
**latest_status,
'total_spend': sum(d['spend'] for d in self.data),
'total_acquisitions': sum(d['acquisitions'] for d in self.data),
'daily_cap': self.get_current_daily_cap(latest_ts),
'weekly_cap': self.get_current_weekly_cap(latest_ts),
'is_saturated': self.is_saturated
}
# Example Usage
if __name__ == "__main__":
guardrail = CACGuardrail(max_cac=40.0, max_daily_spend=5000)
# Simulate data
dates = pd.date_range(start='2023-10-01', periods=14, freq='D')
spends = [1000, 1200, 1500, 1800, 2000, 2200, 2500, 3000, 3500, 4000, 4500, 5000, 5500, 6000]
acqs = [30, 35, 40, 45, 48, 50, 52, 53, 54, 55, 55, 56, 56, 57] # Saturation kicks in
for i, date in enumerate(dates):
status = guardrail.update(date, spends[i], acqs[i])
print(f"Day {i+1}: CAC={status['cac']:.1f}, Saturated={status['is_saturated']}, Reco={status['recommendation']}")
print("\nFinal Report:", guardrail.get_status_report())
print("Next $2000 spend approved?", not guardrail.should_cap_next_spend(2000))
Key Features Explained
- CAC Tracking: Cumulative and real-time CAC calculation.
- Saturation Detection:
- Curve Fitting: Linear regression on cumulative spend vs. acquisitions. Low R² (<0.85 default) signals non-linearity (saturation).
- Marginal CAC: Compares recent window (7 days) CAC to historical. If >1.5x, saturated.
- Caps:
- Hard daily/weekly limits.
- Dynamic reduction (50% default) when saturated.
- Remaining budget tracking.
- Guardrail Logic:
should_cap_next_spend() blocks overspend.
- Extensible: Easy to integrate with ad platforms (e.g., Google Ads API) or dashboards.
- Dependencies:
pandas, numpy, scikit-learn (pip install if needed).
This is production-ready for monitoring campaigns. Tune params based on your benchmarks! 🚀