import pandas as pd
import numpy as np
class CACGuardrail:
def __init__(self, hard_cap=50.0, saturation_threshold=0.15, lookback_window=7):
"""
Initializes the guardrail system.
:param hard_cap (float): The absolute max CAC allowed (e.g., $50).
:param saturation_threshold (float): The % increase in Marginal CAC vs Blended CAC that triggers a warning.
(e.g., 0.15 means if Marginal CAC is 15% higher than Blended, we are saturating).
:param lookback_window (int): Days to look back for calculating trends.
"""
self.hard_cap = hard_cap
self.saturation_threshold = saturation_threshold
self.lookback_window = lookback_window
# Storage for campaign data
self.data = []
def ingest_data(self, date, spend, new_customers):
"""Simulates ingesting daily marketing data."""
self.data.append({
'date': date,
'spend': spend,
'customers': new_customers
})
def _calculate_metrics(self):
"""Calculates Blended CAC and Marginal CAC."""
df = pd.DataFrame(self.data)
# 1. Blended CAC (Cumulative Spend / Cumulative Customers)
df['cum_spend'] = df['spend'].cumsum()
df['cum_customers'] = df['customers'].cumsum()
df['blended_cac'] = df['cum_spend'] / df['cum_customers']
# 2. Marginal CAC (Rolling Spend / Rolling Customers)
# This tells us how expensive the "latest" customers were to acquire.
df['rolling_spend'] = df['spend'].rolling(window=self.lookback_window, min_periods=1).sum()
df['rolling_customers'] = df['customers'].rolling(window=self.lookback_window, min_periods=1).sum()
df['marginal_cac'] = df['rolling_spend'] / df['rolling_customers']
# Handle infinite/NaN values
df = df.replace([np.inf, -np.inf], np.nan).fillna(0)
return df
def check_guardrails(self):
"""Runs the guardrail logic against the latest data."""
df = self._calculate_metrics()
if df.empty:
return "NO_DATA"
# Get the most recent record
current_state = df.iloc[-1]
status = {
"status": "HEALTHY",
"blended_cac": current_state['blended_cac'],
"marginal_cac": current_state['marginal_cac'],
"message": "Within limits."
}
# --- CHECK 1: Hard Cap Breach ---
if current_state['blended_cac'] > self.hard_cap:
status['status'] = "CAP_BREACH"
status['message'] = f"CRITICAL: Blended CAC (${current_state['blended_cac']:.2f}) exceeded Hard Cap (${self.hard_cap})."
return status
# --- CHECK 2: Saturation Detection ---
# Saturation occurs when the cost to acquire the RECENT user (Marginal)
# is significantly higher than the AVERAGE user (Blended).
cac_ratio = 0
if current_state['blended_cac'] > 0:
cac_ratio = (current_state['marginal_cac'] - current_state['blended_cac']) / current_state['blended_cac']
if cac_ratio > self.saturation_threshold:
status['status'] = "SATURATION_WARNING"
status['message'] = (f"WARNING: Market Saturation detected. Marginal CAC (${current_state['marginal_cac']:.2f}) "
f"is {cac_ratio:.1%} higher than Blended CAC.")
return status
# ==========================================
# Example Usage Simulation
# ==========================================
guardrail = CACGuardrail(hard_cap=50.0, saturation_threshold=0.20)
# Data: Day, Spend, Customers
# Scenario: Early days are efficient. Later days, we spend more but get fewer customers (Saturation).
campaign_data = [
("2023-10-01", 100, 10), # CAC 10
("2023-10-02", 100, 12), # CAC 8.3
("2023-10-03", 100, 11), # CAC 9.1
("2023-10-04", 150, 10), # Spending more, getting fewer (Marginal CAC rising)
("2023-10-05", 200, 9), # Spending double, getting even fewer
("2023-10-06", 300, 6), # Saturation point
]
print(f"{'DATE':<15} | {'BLENDED_CAC':<15} | {'MARGINAL_CAC':<15} | {'STATUS':<20}")
print("-" * 75)
for day, spend, cust in campaign_data:
guardrail.ingest_data(day, spend, cust)
result = guardrail.check_guardrails()
print(f"{day:<15} | {result['blended_cac']:<15.2f} | {result['marginal_cac']:<15.2f} | {result['status']:<20}")
if result['status'] != "HEALTHY":
print(f" -> {result['message']}")