survival-analysis-marketing
Skill1 starsChanged 7 months agoMITView on GitHub
Models time-to-event in marketing: next purchase, churn, subscription renewal, promotion redemption. Handles censored observations correctly. Use when asked to: predict when a customer will next purchase, identify churn risk and timing, measure how discounts or email frequency accelerate or delay events, build replenishment campaign triggers, or estimate time-to-first-purchase for acquisition targeting. Also trigger when someone says "time to event", "survival curve", "kaplan meier", "cox model", "hazard ratio", "churn timing", "time to churn", "time to next purchase", "censored data", "censored records", "replenishment timing", "when will they buy", "how long until", or pastes data with event times and censoring indicators. Always renders inline HTML dashboard as primary output — never just text tables.
In this repository35 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- agency-request-intake-routerSkill
- analyzing-marketing-campaignSkill
- audience-segmentation-briefSkill
- campaign-launch-qaSkill
- change-order-generatorSkill
- client-memory-synthesizerSkill
- creative-supply-plannerSkill
- crm-journey-architectSkill
- customer-lifetime-valueSkill
- customer-segmentation-clusteringSkill
- data-intake-normalizerSkill
- executive-growth-memoSkill
- fte-capacity-sizingSkill
- margin-simulationSkill
- market-basket-analysisSkill
- measurement-incrementalitySkill
- media-procurement-benchmarkSkill
- media-routing-plannerSkill
- mmm-modelingSkill
- performance-diagnosisSkill
- ppa-assortment-diagnosisSkill
- ppa-continuous-optimizationSkill
- ppa-financial-modelSkill
- ppa-pack-size-leverageSkill
- ppa-value-perceptionSkill
- price-demand-optimizationSkill
- price-elasticity-modelingSkill
- price-threshold-detectionSkill
- qbr-generatorSkill
- recommender-systemsSkill
- response-uplift-modelingSkill
- rfp-submissionSkill
- scope-auditSkill
- weekly-control-towerSkill
The file
We split this skill into the rules it gives an agent
1 rule. About 0 are common, 1 is distinctive, and 0 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 80
Never drop censored records — they carry information (§2.6.2, p.
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Survival Analysis for Marketing
Time-to-event modeling with proper censored data handling. Three-tier approach: Kaplan–Meier (nonparametric) → Cox PH (semiparametric) → Time-to-Event prediction.
Core Equations (Katsov §2.6.2)
Survival Function (eq. 2.107–2.109)
S(t) = Pr(T > t) = 1 − F(t) # probability of surviving past t
# Kaplan-Meier estimator (eq. 2.109):
Ŝ(t) = ∏_{i ≤ t} (1 − d_i / n_i) # product over observed event timesHazard Function (eq. 2.112–2.116)
h(t) = lim_{dt→0} Pr(t < T ≤ t+dt | T > t) / dt
= f(t) / S(t) = −d/dt [log S(t)]
H(t) = ∫₀ᵗ h(τ)dτ [cumulative hazard]
S(t) = exp(−H(t))Cox Proportional Hazards (eq. 2.119–2.133)
h(t | x) = h₀(t) · exp(wᵀx) # baseline × risk ratio
# Partial likelihood (eq. 2.127–2.128):
L_i(w) = exp(wᵀx_i) / Σ_{j ∈ R(t_i)} exp(wᵀx_j)
# Personalized survival function (eq. 2.133):
S(t | x) = S₀(t)^{exp(wᵀx)}
# Breslow baseline cumulative hazard (eq. 2.131):
Ĥ₀(t) = Σ_{t_i ≤ t} d̂_i / Σ_{j ∈ R(t_i)} exp(wᵀx_j)Key marketing interpretations:
exp(w_k)= hazard ratio for feature k → how much it accelerates/decelerates the eventHR > 1→ accelerates event (e.g., discount → faster purchase)HR < 1→ decelerates event (e.g., retention offer → slower churn)
Input Data Format (eq. 2.104, 2.118)
Each row: (customer_id, t_i, δ_i, x_i...)
| Column | Description |
t | Survival/censoring time (days, weeks, months from treatment) |
delta | 1 = event observed; 0 = censored (customer still active at analysis date) |
x_1..N | Feature vector: recency, frequency, discount_depth, n_emails, etc. |
Censoring rule: Customer is censored if event not observed by analysis date. Never drop censored records — they carry information (§2.6.2, p. 58–59).
Workflow
Step 1 — Prepare Data
python scripts/censored_data_prep.py \
--transactions data/txns.csv \
--analysis-date 2024-12-31 \
--event purchase \
--output data/survival_ready.csvStep 2 — Kaplan-Meier (nonparametric baseline)
python scripts/kaplan_meier.py \
--data data/survival_ready.csv \
--group-col treatment \
--output results/km_output.jsonOutput: survival curve per group + log-rank test p-value.
Step 3 — Cox PH Model (covariate effects)
python scripts/cox_model.py \
--data data/survival_ready.csv \
--features recency frequency discount_depth n_emails \
--output results/cox_output.jsonOutput: hazard ratios, 95% CI, p-values, concordance index.
Step 4 — Predict Time-to-Event per Customer
python scripts/time_to_event_pred.py \
--data data/survival_ready.csv \
--cox-model results/cox_output.json \
--output results/tte_predictions.csvOutput: median survival time, p25/p75 per customer → use as campaign trigger.
Step 5 — Visualize Hazard Ratios
python scripts/hazard_ratio_viz.py \
--cox-results results/cox_output.json \
--output results/hr_forest_data.jsonStep 6 — Export Dashboard JSON + Render
python scripts/export_survival_dashboard_json.py \
--km results/km_output.json \
--cox results/cox_output.json \
--tte results/tte_predictions.csv \
--output dashboard_data.jsonThen call show_widget with references/survival_dashboard_template.html.
Output sequence:
1. [bash_tool] censored_data_prep.py
2. [bash_tool] kaplan_meier.py + cox_model.py + time_to_event_pred.py
3. [bash_tool] export_survival_dashboard_json.py → JSON
4. [show_widget] Render dashboard
5. [text] Exec recommendation: HR interpretation + campaign trigger timing
6. [text] PH assumption caveat if relevantScripts Reference
| Script | Key Inputs | Key Outputs |
censored_data_prep.py | raw txns CSV, analysis date, event type | survival-ready CSV with (t, delta, features) |
kaplan_meier.py | survival CSV, optional group col | KM curve JSON + log-rank p-value |
cox_model.py | survival CSV + feature cols | HR table, concordance, baseline cumhaz |
time_to_event_pred.py | survival CSV + cox JSON | per-customer median TTE + p25/p75 |
hazard_ratio_viz.py | cox JSON | forest plot data JSON |
export_survival_dashboard_json.py | km + cox + tte JSONs | unified dashboard JSON |
Output Format — Visualization First
Primary output: inline HTML dashboard. Always render before text.
Dashboard panels (see references/survival_dashboard_template.html):
- KPI bar — median survival time, concordance index, n events, n censored, % censored
- Survival curve(s) — KM estimator, one line per group, with 95% CI band
- Hazard ratio forest plot — one row per feature, dot + CI bar, HR=1 reference line
- Cumulative hazard H(t) — log scale, shows proportional hazard structure
- TTE distribution — histogram of predicted median time-to-event across customers
- Log-rank test summary — p-value and interpretation per group comparison
Fallback: Katsov Example 2.1 format — t | n_at_risk | events | S(t) | CI_lower | CI_upper
Marketing Applications (§3.5.6)
| Application | Event | Censoring rule | Campaign action |
| Replenishment | Next purchase | Analysis date | Send notification N days before predicted purchase |
| Churn detection | Subscription cancel | Still active | Retention offer at t = median × 0.7 |
| Acquisition | First purchase | Analysis date | Retarget users nearing median TTE |
| Promotion redemption | Coupon use | Expiry date | Adjust offer timing to HR of discount_depth |
| Reactivation | Return after lapse | End of observation | Winback trigger at predicted re-engagement |
Key Caveats
- Proportional hazards assumption. Cox model requires
h_i(t)/h_j(t) = constantacross time. Validate with Schoenfeld residuals or log-log plot. Violation → use time-varying coefficients or stratified Cox. - Censoring must be non-informative. Censored customers must not differ systematically from uncensored ones (e.g., don't censor high-value customers selectively).
- Event definition determines the model. Purchase ≠ redemption ≠ churn. Build separate models per event type.
- Repeated events. KM/Cox assume single event per customer. For repeat purchases, model each purchase interval separately (gap time model).
- Marketing interpretation of HR. HR = exp(w_k): a 1-unit increase in feature k multiplies the event rate by HR. For binary features (treatment=1/0), HR is the treatment effect directly.
Integration with Agency Growth OS
| Skill | Handoff |
customer-lifetime-value | S_u(t) feeds LTV survival model (eq. 3.31) |
response-uplift-modeling | Survival curves compare treated vs control groups |
crm-journey-architect | Median TTE → message timing in replenishment journeys |
audience-segmentation-brief | TTE segments → urgency tiers for targeting |
measurement-incrementality | KM group comparison = A/B test measurement |
Reference Files
references/katsov_survival_excerpts.md— Equations 2.104–2.133, Example 2.1, §3.5.6references/model_selection_survival.md— KM vs Cox vs parametric decision guidereferences/survival_dashboard_template.html— Reusable HTML dashboard; injectSKILL_DATA_JSON
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

