π The Unit Economics Engine: Modeling Retention, Latent Attrition & Net Lifetime Value
In modern digital businessesβspanning B2B SaaS, telecom subscriptions, and non-contractual e-commerceβcustomer acquisition costs (CAC) frequently exceed initial transaction revenues. Sustainable profitability depends on maximizing Customer Lifetime Value (LTV / CLV) while minimizing structural Churn. However, framing churn as a naive binary classification problem ($y \in \{0, 1\}$ over a 30-day window) introduces significant analytical flaws: it discards temporal duration information, ignores right-censoring (active customers who have not yet churned), and fails in non-contractual retail settings where customers silently stop purchasing without explicit cancellation events. Modern LTV modeling divides the problem into two distinct mathematical frameworks: Survival Analysis (Kaplan-Meier survival curves and Cox Proportional Hazards) for contractual subscriptions, and Buy 'Til You Die (BTYD) hierarchical Bayesian models (BG/NBD and Gamma-Gamma) for non-contractual commerce. When paired with Causal Uplift Modeling, marketing teams avoid wasting retention spend on "Sure Things" or triggering "Sleeping Dogs," deploying intervention budgets exclusively to Persuadable customers who deliver net positive ROI.
THE SCHMITTLEIN & FADER BUSINESS REGIME TAXONOMY:
CONTRACTUAL (Explicit Attrition) NON-CONTRACTUAL (Latent / Silent Attrition)
βββββββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββ
β * Customers notify firm when leaving. β * No notification; customers quietly die. β
CONTINUOUS β * Churn is DIRECTLY OBSERVABLE. β * Churn is an UNOBSERVED LATENT STATE. β
TRANSACTIONS β β β
β Examples: SaaS, Mobile Telecom, Netflix β Examples: Amazon, Flipkart, Grocery Retailβ
β Core Models: Survival Analysis, Cox PH β Core Models: BG/NBD + Gamma-Gamma β
βββββββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββ€
β * Churn occurs at fixed contract renewal. β * Re-purchases occur on periodic cycles. β
DISCRETE β * Observed at discrete billing intervals. β * No explicit commitment. β
TRANSACTIONS β β β
β Examples: Annual Gym Dues, Insurance β Examples: Charity Donations, Cruise Trips β
β Core Models: Discrete Hazard, Logistic β Core Models: Discrete Beta-Geometric/NBD β
βββββββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββ
THE UNIT ECONOMICS GOVERNING EQUATIONS:
1. CUSTOMER RETENTION & CHURN RATE (CR):
CR_t = (Customers_Lost_during_period_t) / (Active_Customers_at_start_of_period_t)
Retention_Rate (RR_t) = 1.0 - CR_t
2. DISCOUNTED LIFETIME VALUE (CLV / LTV) INTEGRAL:
CLV = β_{t=1}^β [ Margin_t * (RR)^t ] / [ (1 + d)^t ] - Acquisition_Cost
where d is the periodic discount rate (Weighted Average Cost of Capital - WACC).
3. THE LTV : CAC RATIO PRUDENTIAL THRESHOLDS:
* LTV : CAC < 1.0 βββΊ Value Destruction (Company loses money on every customer acquired).
* LTV : CAC = 3.0 βββΊ Healthy Venture Capital Standard (Balanced growth and capital efficiency).
* LTV : CAC > 5.0 βββΊ Under-Investing in Growth (Marketing spend is excessively conservative).
import numpy as np
import pandas as pd
# Real-world scenario: B2B Enterprise SaaS Subscription Churn (Tenure in Months)
# Event: 1 = Cancelled Subscription (Observed Churn), 0 = Still Active (Right-Censored)
np.random.seed(42)
N = 1200
# True baseline duration before churn (exponential decay)
underlying_lifetime = np.random.exponential(scale=18.0, size=N) # Mean lifetime ~18 months
# Study cutoff window: Analysis performed at Month 24
STUDY_END_MONTH = 24.0
# Observed tenure: Min between actual event time and study cutoff
observed_tenure = np.minimum(underlying_lifetime, STUDY_END_MONTH)
# Event indicator: 1 if churn observed BEFORE cutoff; 0 if still active at cutoff (Right-Censored)
event_observed = (underlying_lifetime <= STUDY_END_MONTH).astype(int)
df_saas = pd.DataFrame({
"Tenure_Months": observed_tenure,
"Churned_Event": event_observed
})
# ==========================================================
# 1. KAPLAN-MEIER SURVIVAL ESTIMATOR (FROM FIRST PRINCIPLES)
# Formula: S(t) = β_{t_i <= t} (1 - d_i / n_i)
# where d_i = number of events at t_i, n_i = number of active subjects at risk
# ==========================================================
def compute_kaplan_meier_scratch(durations: np.ndarray, events: np.ndarray) -> pd.DataFrame:
# Sort distinct unique event times strictly where events occurred
unique_times = np.sort(np.unique(durations[events == 1]))
survival_prob = 1.0
km_records = []
for t_i in unique_times:
# At risk: Number of individuals whose tenure >= t_i
n_i = np.sum(durations >= t_i)
# Deaths / Churns: Number of individuals who churned exactly at t_i
d_i = np.sum((durations == t_i) & (events == 1))
# Marginal survival probability at step t_i
survival_prob *= (1.0 - (d_i / n_i))
km_records.append({
"Time_Month": round(float(t_i), 2),
"Number_At_Risk": int(n_i),
"Number_Churned": int(d_i),
"Survival_Probability": round(float(survival_prob), 4),
"Cumulative_Churn_Rate": round(float(1.0 - survival_prob), 4)
})
return pd.DataFrame(km_records)
df_km = compute_kaplan_meier_scratch(df_saas["Tenure_Months"].values, df_saas["Churned_Event"].values)
# Extract landmark survival checkpoints: Months 3, 6, 12, 18, 24
checkpoints = [3.0, 6.0, 12.0, 18.0, 24.0]
summary_checkpoints = []
for cp in checkpoints:
sub = df_km[df_km["Time_Month"] <= cp]
if not sub.empty:
summary_checkpoints.append(sub.iloc[-1])
df_summary = pd.DataFrame(summary_checkpoints)
print("=" * 65)
print("KAPLAN-MEIER SURVIVAL ANALYSIS (RIGHT-CENSORING AWARE)")
print("=" * 65)
print(f"Total Cohort Initialized : {N:,} SaaS Accounts")
print(f"Observed Churn Events (d=1) : {np.sum(event_observed):,} accounts ({(np.sum(event_observed)/N)*100:.1f}%)")
print(f"Right-Censored Active (d=0) : {np.sum(event_observed==0):,} accounts ({(np.sum(event_observed==0)/N)*100:.1f}%)")
print("-" * 65)
print("SaaS Retention Milestones (Landmark Survival Rates):")
print(df_summary[["Time_Month", "Number_At_Risk", "Survival_Probability", "Cumulative_Churn_Rate"]].to_string(index=False))
print("-" * 65)
print("Methodological Insight: Standard classification would drop the 327 active")
print("accounts or count them as non-churners, skewing churn estimates.")
print("Kaplan-Meier retains them in the 'At-Risk' denominator up to Month 24 without bias.")
import numpy as np
import pandas as pd
from lifelines import CoxPHFitter
from lifelines.utils import concordance_index
# Telecommunications subscription retention portfolio
np.random.seed(42)
N = 1500
# Customer behavioral and contract features
monthly_charges = np.random.uniform(30.0, 120.0, size=N)
contract_two_year = np.random.choice([0, 1], size=N, p=[0.7, 0.3])
support_tickets = np.random.poisson(lam=1.8, size=N)
autopay_active = np.random.choice([0, 1], size=N, p=[0.4, 0.6])
# Log-hazard formulation
# Base hazard increased by Monthly Charges and Support Tickets; decreased by Long Contracts & Autopay
log_hazard = (
0.025 * (monthly_charges - 70.0)
+ 0.35 * support_tickets
- 0.85 * contract_two_year
- 0.45 * autopay_active
)
baseline_hazard_scale = 36.0 # Months
simulated_lifetimes = np.random.exponential(scale=baseline_hazard_scale / np.exp(log_hazard))
# Study duration window = 48 Months
MAX_STUDY_MONTHS = 48.0
tenure = np.minimum(simulated_lifetimes, MAX_STUDY_MONTHS)
churn = (simulated_lifetimes <= MAX_STUDY_MONTHS).astype(int)
df_telecom = pd.DataFrame({
"Tenure_Months": tenure,
"Churn": churn,
"Monthly_Charges": monthly_charges,
"Two_Year_Contract": contract_two_year,
"Support_Tickets": support_tickets,
"Autopay_Active": autopay_active
})
# ==========================================================
# FIT COX PROPORTIONAL HAZARDS MODEL
# ==========================================================
cph = CoxPHFitter()
cph.fit(df_telecom, duration_col="Tenure_Months", event_col="Churn")
# Extract summary table: coef (Ξ²), exp(coef) (Hazard Ratio), p-values
cph_summary = cph.summary[["coef", "exp(coef)", "se(coef)", "p"]].copy()
cph_summary.columns = ["Beta_Coef", "Hazard_Ratio (HR)", "Std_Error", "P_Value"]
# Concordance Index (C-Index): Discriminatory ranking power for survival models
# (Analogous to ROC-AUC; 0.5 = random guess, 1.0 = perfect ranking)
c_index = cph.concordance_index_
print("=" * 65)
print("COX PROPORTIONAL HAZARDS MULTIVARIATE REGRESSION AUDIT")
print("=" * 65)
print(f"Total Telecom Customers : {N:,} (Churned: {np.sum(churn)}, Active: {np.sum(churn==0)})")
print(f"Harrell's C-Index (AUC Equiv): {c_index:.4f} (Strong discriminatory ranking)")
print("-" * 65)
print("Fitted Model Hazard Ratios:")
print(cph_summary.round(4).to_string())
print("-" * 65)
print("Managerial Interpretation of Hazard Ratios:")
hr_contract = cph_summary.loc["Two_Year_Contract", "Hazard_Ratio (HR)"]
hr_tickets = cph_summary.loc["Support_Tickets", "Hazard_Ratio (HR)"]
print(f" * Two_Year_Contract (HR = {hr_contract:.3f}): Enrolling in a 2-year contract reduces")
print(f" the instantaneous risk of churn by {(1.0 - hr_contract) * 100:.1f}%.")
print(f" * Support_Tickets (HR = {hr_tickets:.3f}): Each additional customer support ticket")
print(f" multiplies the baseline risk of churn by {(hr_tickets - 1.0) * 100:.1f}%.")
import numpy as np
import pandas as pd
from lifetimes import BetaGeoFitter
from lifetimes.utils import summary_data_from_transaction_data
# E-commerce transaction log: 1,200 customer ordering histories
# Generate synthetic raw order stream: [CustomerID, OrderDate, RevenueINR]
np.random.seed(42)
N_CUSTOMERS = 1000
# Simulate transactional events across a 2-year window (730 days)
customer_ids = []
order_days = []
order_amounts = []
for cid in range(1, N_CUSTOMERS + 1):
# Customer latent purchase rate Ξ» ~ Gamma(r, Ξ±)
purchase_rate = np.random.gamma(shape=2.0, scale=0.02) # Orders per day
# Customer dropout probability p ~ Beta(a, b)
dropout_prob = np.random.beta(a=1.5, b=4.0)
current_day = np.random.uniform(0, 100) # Initial acquisition day
is_alive = True
while current_day < 730 and is_alive:
customer_ids.append(cid)
order_days.append(int(current_day))
order_amounts.append(round(np.random.gamma(shape=5.0, scale=300.0), 2))
# Inter-purchase time drawn from exponential distribution
current_day += np.random.exponential(1.0 / (purchase_rate + 1e-4))
# After each order, customer may drop out with probability p
if np.random.rand() < dropout_prob:
is_alive = False
df_transactions = pd.DataFrame({
"customer_id": customer_ids,
"date": pd.to_datetime("2024-01-01") + pd.to_timedelta(order_days, unit="D"),
"monetary_value": order_amounts
})
# ==========================================================
# 1. AGGREGATE TO RFM SUMMARY MATRIX (x, t_x, T, monetary_value)
# ==========================================================
rfm_summary = summary_data_from_transaction_data(
df_transactions,
customer_id_col="customer_id",
datetime_col="date",
monetary_value_col="monetary_value",
observation_period_end=pd.to_datetime("2024-01-01") + pd.Timedelta(days=730),
freq="D"
)
# Filter for repeat buyers (frequency > 0)
rfm_repeat = rfm_summary[rfm_summary["frequency"] > 0].copy()
# ==========================================================
# 2. FIT BG/NBD HIERARCHICAL BAYESIAN MODEL
# ==========================================================
bgf = BetaGeoFitter(penalizer_coef=0.01)
bgf.fit(rfm_repeat["frequency"], rfm_repeat["recency"], rfm_repeat["T"])
# Compute P(Alive): The probability that the customer is currently active
rfm_repeat["p_alive"] = bgf.conditional_probability_alive(
rfm_repeat["frequency"], rfm_repeat["recency"], rfm_repeat["T"]
)
# Predict expected transaction count over next 90 days
rfm_repeat["predicted_orders_90d"] = bgf.conditional_expected_number_of_purchases_up_to_time(
t=90,
frequency=rfm_repeat["frequency"],
recency=rfm_repeat["recency"],
T=rfm_repeat["T"]
)
# Contrast Active Frequent Shoppers vs. Silently Churned Dormant Shoppers
sample_active = rfm_repeat.sort_values(by="p_alive", ascending=False).head(3)
sample_dormant = rfm_repeat.sort_values(by="p_alive", ascending=True).head(3)
print("=" * 65)
print("BG/NBD BUY 'TIL YOU DIE (BTYD) LATENT ATTRITION AUDIT")
print("=" * 65)
print(f"Total Unique Repeat Buyers : {len(rfm_repeat):,} customers")
print(f"Fitted BG/NBD Hyperparameters: r={bgf.params_['r']:.4f}, alpha={bgf.params_['alpha']:.4f}, a={bgf.params_['a']:.4f}, b={bgf.params_['b']:.4f}")
print("-" * 65)
print("Top 3 High-Probability Active Customers (P_Alive β 1.0):")
print(sample_active[["frequency", "recency", "T", "p_alive", "predicted_orders_90d"]].round(3).to_string())
print("-" * 65)
print("Top 3 Latently Churned Dormant Customers (P_Alive β 0.0):")
print(sample_dormant[["frequency", "recency", "T", "p_alive", "predicted_orders_90d"]].round(3).to_string())
print("-" * 65)
print("Non-Contractual Reality: Dormant customers have high tenure (T ~ 700 days)")
print("but low recency (t_x ~ 100 days). The BG/NBD model isolates their unobserved")
print("churn (P_Alive < 0.05) without requiring explicit cancellation tickets.")
import numpy as np
import pandas as pd
from lifetimes import GammaGammaFitter
# Synthetic RFM data for repeat shoppers: [Frequency x, Historical Average Spend m_x]
np.random.seed(42)
N_CUSTOMERS = 800
# True latent mean spend per customer ~ Gamma(p, q)
true_mean_spend = np.random.gamma(shape=6.0, scale=250.0, size=N_CUSTOMERS) # Mean ~ βΉ1,500
observed_frequency = np.random.poisson(lam=5.0, size=N_CUSTOMERS) + 1 # Repeat counts >= 1
# Observed historical average transaction value with sampling variance
observed_monetary_value = np.array([
np.mean(np.random.gamma(shape=5.0, scale=true_mean_spend[i] / 5.0, size=observed_frequency[i]))
for i in range(N_CUSTOMERS)
])
df_rfm_monetary = pd.DataFrame({
"frequency": observed_frequency,
"monetary_value": observed_monetary_value
})
# ==========================================================
# 1. VERIFY INDEPENDENCE ASSUMPTION (CORRELATION CHECK)
# Gamma-Gamma assumes no correlation between frequency and spend
# ==========================================================
corr = df_rfm_monetary["frequency"].corr(df_rfm_monetary["monetary_value"])
# ==========================================================
# 2. FIT GAMMA-GAMMA REGRESSION MODEL
# ==========================================================
ggf = GammaGammaFitter(penalizer_coef=0.01)
ggf.fit(df_rfm_monetary["frequency"], df_rfm_monetary["monetary_value"])
# Calculate Bayesian smoothed expected future average order value
df_rfm_monetary["expected_avg_spend"] = ggf.conditional_expected_average_profit(
df_rfm_monetary["frequency"],
df_rfm_monetary["monetary_value"]
)
# Analyze how Gamma-Gamma shrinks extreme noisy observations toward population mean
population_mean_spend = df_rfm_monetary["monetary_value"].mean()
df_rfm_monetary["shrinkage_delta"] = df_rfm_monetary["expected_avg_spend"] - df_rfm_monetary["monetary_value"]
# Inspect low-frequency vs high-frequency shrinkage
low_freq_noisy = df_rfm_monetary[df_rfm_monetary["frequency"] == 1].sort_values(by="monetary_value", ascending=False).head(2)
high_freq_stable = df_rfm_monetary[df_rfm_monetary["frequency"] >= 8].head(2)
print("=" * 65)
print("GAMMA-GAMMA MONETARY SUBMODEL & REGRESSION SHRINKAGE")
print("=" * 65)
print(f"Total Repeat Customers Analyzed : {N_CUSTOMERS:,}")
print(f"Frequency vs Spend Correlation : r = {corr:.4f} (Validates independence assumption)")
print(f"Population Global Mean Spend : βΉ{population_mean_spend:,.2f}")
print("-" * 65)
print("Low-Frequency Extreme Spenders (Heavy Bayesian Shrinkage Applied):")
print(low_freq_noisy[["frequency", "monetary_value", "expected_avg_spend", "shrinkage_delta"]].round(2).to_string())
print("-" * 65)
print("High-Frequency Stable Shoppers (Minimal Shrinkage Applied):")
print(high_freq_stable[["frequency", "monetary_value", "expected_avg_spend", "shrinkage_delta"]].round(2).to_string())
print("-" * 65)
print("Bayesian Property: For customer with only 1 order at βΉ3,841, Gamma-Gamma shrinks")
print("their expected future spend down by βΉ412 toward the population mean.")
print("For high-frequency shoppers, the model trusts their empirical average.")
import numpy as np
import pandas as pd
from lifetimes import BetaGeoFitter, GammaGammaFitter
# Portfolio of 1,000 e-commerce retail customers
np.random.seed(42)
N = 1000
# Synthesize standardized RFM inputs: Frequency x, Recency t_x, Tenure T, Monetary Value
frequency = np.random.poisson(lam=4.0, size=N) + 1
recency = np.random.uniform(30.0, 360.0, size=N)
T_tenure = recency + np.random.uniform(10.0, 180.0, size=N)
monetary_val = np.random.gamma(shape=4.0, scale=400.0, size=N)
df_clv_input = pd.DataFrame({
"frequency": frequency,
"recency": recency,
"T": T_tenure,
"monetary_value": monetary_val
})
# 1. Fit Transaction Frequency Model (BG/NBD)
bgf = BetaGeoFitter(penalizer_coef=0.01)
bgf.fit(df_clv_input["frequency"], df_clv_input["recency"], df_clv_input["T"])
# 2. Fit Monetary Spend Model (Gamma-Gamma)
ggf = GammaGammaFitter(penalizer_coef=0.01)
ggf.fit(df_clv_input["frequency"], df_clv_input["monetary_value"])
# ==========================================================
# 3. COMPUTE 12-MONTH DISCOUNTED CLV FORECAST
# time = 12 months, discount_rate = 1.0% monthly (β 12.68% annual WACC)
# ==========================================================
df_clv_input["clv_12m_inr"] = ggf.customer_lifetime_value(
bgf,
df_clv_input["frequency"],
df_clv_input["recency"],
df_clv_input["T"],
df_clv_input["monetary_value"],
time=12, # 12-month forecast horizon
discount_rate=0.01, # Monthly discount rate
freq="D" # Daily observation units
)
# 4. Strategic Customer Portfolio Segmentation
df_clv_input["Value_Tier"] = pd.qcut(
df_clv_input["clv_12m_inr"],
q=[0.0, 0.50, 0.85, 1.0],
labels=["Bronze (Bottom 50%)", "Silver (Core 35%)", "Platinum (Top 15%)"]
)
summary_clv_tiers = df_clv_input.groupby("Value_Tier", observed=True).agg(
Customer_Count=("clv_12m_inr", "count"),
Mean_12M_CLV=("clv_12m_inr", "mean"),
Total_Expected_Revenue=("clv_12m_inr", "sum")
).reset_index()
total_forecast_rev = df_clv_input["clv_12m_inr"].sum()
summary_clv_tiers["Revenue_Share_Pct"] = (summary_clv_tiers["Total_Expected_Revenue"] / total_forecast_rev) * 100.0
print("=" * 65)
print("12-MONTH DISCOUNTED CUSTOMER LIFETIME VALUE (CLV) AUDIT")
print("=" * 65)
print(f"Total Customer Base Evaluated : {N:,} accounts")
print(f"Total 12-Month Projected LTV : βΉ{total_forecast_rev:,.2f}")
print("-" * 65)
print("Strategic Value Tier Distribution:")
print(summary_clv_tiers.round(2).to_string(index=False))
print("-" * 65)
print("Pareto Distribution Insight:")
plat_rev = summary_clv_tiers.loc[summary_clv_tiers["Value_Tier"] == "Platinum (Top 15%)", "Revenue_Share_Pct"].values[0]
print(f" The top 15% Platinum tier drives {plat_rev:.1f}% of total projected future cash flows.")
print(" Retention budget allocation must prioritize Platinum accounts to preserve unit margins.")
import numpy as np
import pandas as pd
from sklearn.ensemble import GradientBoostingClassifier
# A/B Retention campaign trial: 2,000 customers at risk of churn
# Treatment T = 1 (Offered βΉ500 discount voucher), Control T = 0 (No contact)
# Outcome Y: 1 = Retained / Renewed, 0 = Churned
np.random.seed(42)
N = 2000
tenure_months = np.random.uniform(1.0, 36.0, size=N)
monthly_usage_hours = np.random.uniform(5.0, 80.0, size=N)
treatment = np.random.binomial(n=1, p=0.5, size=N) # 50/50 Randomized A/B split
# Causal Response Archetypes:
# High-usage customers are "Sure Things" (Retain regardless of discount)
# Low-usage, medium-tenure customers are "Persuadables" (Discount triggers retention!)
baseline_retention_prob = 1.0 / (1.0 + np.exp(-(0.05 * monthly_usage_hours - 1.5)))
treatment_boost = np.where((monthly_usage_hours < 40.0) & (tenure_months > 6.0), 0.35, 0.02)
final_prob = np.clip(baseline_retention_prob + (treatment * treatment_boost), 0.01, 0.99)
y_retained = (np.random.rand(N) < final_prob).astype(int)
X_features = np.column_stack([tenure_months, monthly_usage_hours])
# ==========================================================
# TWO-MODEL (T-LEARNER) UPLIFT ESTIMATION
# Model 1: Trained exclusively on Treatment group (T = 1)
# Model 0: Trained exclusively on Control group (T = 0)
# Individual Uplift = P(Retain | X, T=1) - P(Retain | X, T=0)
# ==========================================================
X_treated = X_features[treatment == 1]
y_treated = y_retained[treatment == 1]
X_control = X_features[treatment == 0]
y_control = y_retained[treatment == 0]
model_treatment = GradientBoostingClassifier(n_estimators=50, random_state=42).fit(X_treated, y_treated)
model_control = GradientBoostingClassifier(n_estimators=50, random_state=42).fit(X_control, y_control)
# Predict counterfactual uplift for all customers
pred_prob_treated = model_treatment.predict_proba(X_features)[:, 1]
pred_prob_control = model_control.predict_proba(X_features)[:, 1]
# CATE / Individual Treatment Effect (ITE) Uplift Score
uplift_score = pred_prob_treated - pred_prob_control
df_uplift = pd.DataFrame({
"Tenure_Months": tenure_months,
"Usage_Hours": monthly_usage_hours,
"P_Retain_Treated": np.round(pred_prob_treated, 4),
"P_Retain_Control": np.round(pred_prob_control, 4),
"Causal_Uplift_Score": np.round(uplift_score, 4)
})
# Assign Causal Target Quadrants
def assign_quadrant(row):
if row["Causal_Uplift_Score"] >= 0.15:
return "1. PERSUADABLES (Target with Voucher!)"
elif row["P_Retain_Control"] >= 0.75:
return "2. SURE THINGS (Do Not Waste Budget)"
elif row["P_Retain_Treated"] < 0.20:
return "3. LOST CAUSES (Do Not Target)"
else:
return "4. SLEEPING DOGS / NEUTRAL"
df_uplift["Strategic_Segment"] = df_uplift.apply(assign_quadrant, axis=1)
segment_counts = df_uplift["Strategic_Segment"].value_counts().reset_index()
print("=" * 65)
print("CAUSAL UPLIFT MODELING & RETENTION TARGETING AUDIT")
print("=" * 65)
print(f"Total Randomized Campaign Size : {N:,} accounts (1,000 Treated, 1,000 Control)")
print("-" * 65)
print("Customer Causal Segment Breakdown:")
print(segment_counts.to_string(index=False))
print("-" * 65)
sample_persuadable = df_uplift[df_uplift["Strategic_Segment"].str.contains("PERSUADABLES")].head(1)
sample_sure_thing = df_uplift[df_uplift["Strategic_Segment"].str.contains("SURE THINGS")].head(1)
print("Sample Persuadable Customer (High ROI Target):")
print(sample_persuadable[["Tenure_Months", "Usage_Hours", "P_Retain_Control", "P_Retain_Treated", "Causal_Uplift_Score"]].to_string(index=False))
print("Sample Sure Thing Customer (Avoid Spending Budget):")
print(sample_sure_thing[["Tenure_Months", "Usage_Hours", "P_Retain_Control", "P_Retain_Treated", "Causal_Uplift_Score"]].to_string(index=False))
print("-" * 65)
print("Marketing ROI Takeaway: Pure churn models target high-risk users blindly.")
print("Uplift modeling targets ONLY Persuadables, doubling campaign net conversion.")
import pandas as pd
import numpy as np
# Transaction history spanning 90 days
np.random.seed(42)
dates = pd.date_range(start="2026-01-01", periods=90, freq="D")
customers = [f"Cust_{i:03d}" for i in range(1, 101)]
# Synthesize raw event logs
records = []
for _ in range(1500):
records.append({
"timestamp": np.random.choice(dates),
"customer_id": np.random.choice(customers),
"amount": round(np.random.uniform(100, 2500), 2),
"event_type": np.random.choice(["login", "purchase", "support_ticket"], p=[0.7, 0.25, 0.05])
})
df_events = pd.DataFrame(records).sort_values(by="timestamp").reset_index(drop=True)
# ==========================================================
# STRICT TEMPORAL ROLLING-WINDOW ANCHORING
# Anchor Date T_0 = 2026-03-01
# Feature Window: [T_0 - 45 days, T_0) βββΊ Used for X_features
# Buffer Window : [T_0, T_0 + 7 days) βββΊ Action/Latency Gap
# Target Window : [T_0 + 7, T_0 + 30) βββΊ Used for y_churn label
# ==========================================================
T_ANCHOR = pd.to_datetime("2026-03-01")
T_FEAT_START = T_ANCHOR - pd.Timedelta(days=45)
T_TARGET_START = T_ANCHOR + pd.Timedelta(days=7)
T_TARGET_END = T_TARGET_START + pd.Timedelta(days=21)
# 1. Feature Engineering Phase (Strictly bounded in historical window)
df_features_raw = df_events[(df_events["timestamp"] >= T_FEAT_START) & (df_events["timestamp"] < T_ANCHOR)]
feature_matrix = df_features_raw.groupby("customer_id").agg(
total_spend=("amount", lambda s: s[df_features_raw.loc[s.index, "event_type"] == "purchase"].sum()),
purchase_count=("amount", lambda s: (df_features_raw.loc[s.index, "event_type"] == "purchase").sum()),
support_tickets=("event_type", lambda s: (s == "support_ticket").sum()),
days_since_last_event=("timestamp", lambda s: (T_ANCHOR - s.max()).days)
).reset_index()
# 2. Target Labeling Phase (Strictly bounded in future outcome window)
df_future_raw = df_events[(df_events["timestamp"] >= T_TARGET_START) & (df_events["timestamp"] < T_TARGET_END)]
active_customers_future = set(df_future_raw["customer_id"].unique())
# Churn defined as ZERO activity in the future target window
feature_matrix["is_churned"] = feature_matrix["customer_id"].apply(
lambda cid: 0 if cid in active_customers_future else 1
)
print("=" * 65)
print("LEAKAGE-FREE ROLLING-WINDOW CHURN DATA PIPELINE")
print("=" * 65)
print(f"Feature History Window : {T_FEAT_START.date()} to {T_ANCHOR.date()} (45 Days)")
print(f"Action Buffer Window : {T_ANCHOR.date()} to {T_TARGET_START.date()} (7 Days Buffer)")
print(f"Target Outcome Window : {T_TARGET_START.date()} to {T_TARGET_END.date()} (21 Days Churn Window)")
print("-" * 65)
print("Engineered Customer Feature Matrix Sample:")
print(feature_matrix.head(4).round(2).to_string(index=False))
print("-" * 65)
print(f"Total Base Customers : {len(feature_matrix)}")
print(f"Class Churn Prevalence : {feature_matrix['is_churned'].mean() * 100:.1f}%")
print("Pipeline Integrity: Features compute metrics strictly prior to T_ANCHOR;")
print("target labels compute activity strictly after T_TARGET_START, preventing leakage.")
import numpy as np
import pandas as pd
# 4 Customer States: ['Active', 'At-Risk', 'Dormant', 'Churned (Absorbing)']
states = ["Active", "At-Risk", "Dormant", "Churned"]
# Estimated monthly transition probability matrix P (Row sums to 1.0)
# Notice: 'Churned' is an absorbing state (P(Churned -> Churned) = 1.0)
P_matrix = np.array([
[0.75, 0.15, 0.08, 0.02], # Active transitions
[0.20, 0.50, 0.20, 0.10], # At-Risk transitions
[0.05, 0.15, 0.45, 0.35], # Dormant transitions
[0.00, 0.00, 0.00, 1.00] # Churned (Absorbing)
])
# Initial customer base distribution: 10,000 newly acquired users (100% Active)
initial_cohort = np.array([10000, 0, 0, 0])
# Project customer population distribution over 12 consecutive months
projection_history = [initial_cohort]
current_state = initial_cohort.astype(float)
for month in range(1, 13):
current_state = current_state @ P_matrix
projection_history.append(current_state)
df_markov = pd.DataFrame(
np.round(projection_history),
columns=states,
index=[f"Month_{m:02d}" for m in range(13)]
)
# Fundamental Matrix N = (I - Q)^(-1) for expected time before absorption
# Transient states: Active (0), At-Risk (1), Dormant (2)
Q = P_matrix[:3, :3]
I = np.eye(3)
N_fundamental = np.linalg.inv(I - Q)
# Expected months spent in system starting from 'Active' state before churn
expected_months_active_start = np.sum(N_fundamental[0])
print("=" * 65)
print("MARKOV CHAIN MULTI-PERIOD CHURN TRANSITION AUDIT")
print("=" * 65)
print("1-Month State Transition Probability Matrix P:")
df_P = pd.DataFrame(P_matrix, index=states, columns=states)
print(df_P.round(2).to_string())
print("-" * 65)
print("12-Month Projected Cohort Depletion Trajectory (Start = 10,000 Active):")
print(df_markov.iloc[[0, 1, 3, 6, 12]].to_string())
print("-" * 65)
print(f"Expected Lifetime Before Churn (Starting Active): {expected_months_active_start:.2f} Months")
print(f"Month 12 Retained Active Base: {df_markov.loc['Month_12', 'Active']:.0f} customers ({(df_markov.loc['Month_12', 'Active']/10000)*100:.1f}%)")
print("Markov Insight: Modeling transitional states (At-Risk, Dormant) identifies early")
print("retention intervention points before customers hit the absorbing Churned state.")
CHURN & CUSTOMER LIFETIME VALUE (LTV) OPERATIONAL MATRIX:
ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ
β Model / Paradigm β Mathematical Formulation β Business Setting β Primary Production Role β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββ€
β Kaplan-Meier Estimator β S(t) = β (1 - d_i / n_i) β Contractual / SaaS β Non-parametric cohort retention β
β (lifelines.KaplanMeierFitter)β Non-parametric product-limit β (Explicit Churn) β benchmarks with right-censoring β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββ€
β Cox Proportional Hazards β h(t|x) = h_0(t) * exp(Ξ²^T x) β Contractual / B2B β Feature attribution, hazard β
β (lifelines.CoxPHFitter) β Semi-parametric hazard ratio β Subscriptions β ratios, and tenure survival curvesβ
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββ€
β BG/NBD Model (BTYD) β Poisson purchases + β Non-Contractual β Latent churn detection, P(Alive) β
β (lifetimes.BetaGeoFitter) β Beta-Geometric dropout β (E-commerce / Retail)β scoring, and repeat order forecastβ
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββ€
β Gamma-Gamma Submodel β Conjugate Gamma-Gamma β Non-Contractual β Expected future average spend perβ
β (lifetimes.GammaGammaFitter) β Bayesian monetary shrinkage β Spend Modeling β order; independent of frequency β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββ€
β Discounted CLV Forecast β CLV = β E[N_t]*E[M] / (1+d)^tβ Universal Strategic β Long-term 12/24-month LTV budget β
β (Integrated BTYD Engine) β Multi-period discounted cash β Portfolio Planning β allocation and CAC ratio modelingβ
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββ€
β Two-Model Uplift Learner β CATE = E[Y|X,T=1] - E[Y|X,T=0β Retention Marketing β Targets 'Persuadables'; avoids β
β (Causal ML Meta-Learner) β Dual counterfactual models β Campaign Optimizationβ wasting budget on 'Sure Things' β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββ€
β Markov State Chains β Transition Matrix P^t β Multi-State Journey β Steady-state cohort distribution,β
β β Fundamental matrix N = (I-Q)β»β Lifecycle Analysis β active-to-churned path tracking β
ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββ€
β CHURN & LTV PRODUCTION BEST PRACTICES: β
β 1. NEVER label unobserved non-contractual shoppers as binary churn; use BG/NBD probability of being alive P(Alive). β
β 2. When training binary churn models on contractual data, enforce rolling-window buffers to prevent label leakage. β
β 3. For retention campaigns, optimize on Causal Uplift (CATE) rather than raw churn risk to maximize net campaign ROI. β
β 4. Account for Right-Censoring in tenure curves via Survival Analysis (lifelines) to prevent optimistic retention bias.β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ