import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.figure_factory as ff
from scipy import stats
import warnings
warnings.filterwarnings('ignore')
st.set_page_config(page_title="Sherlock's Cohort Retention Dashboard", layout="wide", page_icon="🔍")
@st.cache_data
def generate_sample_data():
"""
Generate realistic sample user event data for cohort analysis.
Events: signup, activation, purchase (first), repeat_purchase.
Cohorts based on signup month.
"""
np.random.seed(42)
n_users = 15000
cohort_starts = pd.date_range('2023-01-01', '2024-06-01', freq='MS')
data = []
for user_id in range(n_users):
# Cohort assignment: signup date
cohort_date = np.random.choice(cohort_starts)
signup_date = cohort_date + pd.Timedelta(days=np.random.randint(0, 28))
if signup_date > pd.Timestamp('2024-06-01'):
continue
data.append({'user_id': user_id, 'event_date': signup_date, 'event': 'signup'})
# Activation (80% rate, 1-7 days after signup)
if np.random.rand() < 0.8:
act_date = signup_date + pd.Timedelta(days=np.random.randint(1, 7))
data.append({'user_id': user_id, 'event_date': act_date, 'event': 'activation'})
# First purchase (50% of activated, 1-60 days after)
if np.random.rand() < 0.5:
first_pur_date = signup_date + pd.Timedelta(days=np.random.randint(1, 60))
data.append({'user_id': user_id, 'event_date': first_pur_date, 'event': 'purchase'})
# Repeat purchases (Poisson, 30% of first purchasers)
if np.random.rand() < 0.3:
n_repeats = np.random.poisson(1, 1)[0]
for _ in range(n_repeats):
repeat_date = first_pur_date + pd.Timedelta(days=np.random.randint(7, 180))
if repeat_date < pd.Timestamp('2024-07-01'):
data.append({'user_id': user_id, 'event_date': repeat_date, 'event': 'repeat_purchase'})
df = pd.DataFrame(data)
df['event_date'] = pd.to_datetime(df['event_date'])
df['cohort_month'] = df.groupby('user_id')['event_date'].transform('min').dt.to_period('M')
df['period'] = ((df['event_date'].dt.to_period('M') - df['cohort_month']).dt.n).astype(int)
df['period'] = df['period'].clip(0, 12) # Cap at 12 months for viz
return df
@st.cache_data
def preprocess_data(df):
"""
Precompute cohort metrics for efficiency.
"""
# Cohort sizes (unique signups per cohort)
cohort_sizes = df[df['event'] == 'signup'].groupby('cohort_month')['user_id'].nunique().rename('cohort_size')
# Active users per cohort-period (any event)
active_by_period = df.groupby(['cohort_month', 'period'])['user_id'].nunique().reset_index(name='active_users')
retention_df = active_by_period.merge(cohort_sizes, left_on='cohort_month', right_index=True)
retention_df['retention_%'] = (retention_df['active_users'] / retention_df['cohort_size']) * 100
# Funnel metrics per cohort
funnel_data = []
for cohort in retention_df['cohort_month'].unique():
cohort_users = df[df['cohort_month'] == cohort]['user_id'].unique()
n_signup = len(cohort_users)
n_act = len(df[(df['user_id'].isin(cohort_users)) & (df['event'] == 'activation')]['user_id'].unique())
n_first = len(df[(df['user_id'].isin(cohort_users)) & (df['event'] == 'purchase')]['user_id'].unique())
n_repeat = len(df[(df['user_id'].isin(cohort_users)) & (df['event'] == 'repeat_purchase')]['user_id'].unique())
funnel_data.append({
'cohort_month': cohort,
'Signup': n_signup,
'Activated': n_act,
'First Purchase': n_first,
'Repeat': n_repeat
})
funnel_df = pd.DataFrame(funnel_data)
funnel_df['Signup %'] = 100.0
funnel_df['Activated %'] = (funnel_df['Activated'] / funnel_df['Signup']) * 100
funnel_df['First Purchase %'] = (funnel_df['First Purchase'] / funnel_df['Signup']) * 100
funnel_df['Repeat %'] = (funnel_df['Repeat'] / funnel_df['Signup']) * 100
# Repeat rates per cohort
repeat_counts = df[df['event'] == 'repeat_purchase'].groupby('cohort_month')['user_id'].nunique().rename('repeat_users')
repeat_df = cohort_sizes.to_frame().join(repeat_counts).fillna(0)
repeat_df['repeat_rate_%'] = (repeat_df['repeat_users'] / repeat_df['cohort_size']) * 100
return retention_df, funnel_df, repeat_df, cohort_sizes
# Load and preprocess data
df = generate_sample_data()
retention_df, funnel_df, repeat_df, cohort_sizes = preprocess_data(df)
st.title("🔍 Sherlock's Cohort-Based Retention Dashboard")
st.markdown("**Unravel the mystery of user retention: Funnels, repeat rates, and cohort tests at your fingertips.**")
st.markdown("*(Powered by simulated data from 15K users across 18 months. Run locally with `streamlit run this_script.py`.)*")
# Sidebar for global filters
st.sidebar.header("Filters")
max_cohorts = st.sidebar.slider("Max Cohorts to Show", 6, 18, 12)
cohort_list = sorted(retention_df['cohort_month'].unique())[-max_cohorts:]
selected_cohorts = st.sidebar.multiselect("Select Cohorts", cohort_list, default=cohort_list[-6:])
max_period = st.sidebar.slider("Max Retention Period (Months)", 3, 12, 6)
# Filter data
retention_filtered = retention_df[retention_df['cohort_month'].isin(selected_cohorts)].copy()
funnel_filtered = funnel_df[funnel_df['cohort_month'].isin(selected_cohorts)].copy()
repeat_filtered = repeat_df.loc[repeat_df.index.isin(selected_cohorts)].copy()
# Tabs
tab1, tab2, tab3, tab4 = st.tabs(["📊 Retention Cohorts", "🚀 Funnels", "🔄 Repeat Rates", "🧪 Cohort Tests"])
with tab1:
st.header("Retention Cohorts")
col1, col2 = st.columns([1, 1])
with col1:
# Heatmap
pivot_ret = retention_filtered.pivot(index='cohort_month', columns='period', values='retention_%').fillna(0)
fig_heatmap = px.imshow(
pivot_ret,
labels=dict(x="Period (Months)", y="Cohort Month", color="Retention %"),
title="Cohort Retention Heatmap",
color_continuous_scale="RdYlGn"
)
fig_heatmap.update_layout(height=400)
st.plotly_chart(fig_heatmap, use_container_width=True)
with col2:
# Line chart
avg_retention = retention_filtered.groupby('period')['retention_%'].mean().reset_index(name='Average')
fig_line = px.line(retention_filtered, x='period', y='retention_%', color='cohort_month',
title="Retention Curves by Cohort",
labels={'retention_%': 'Retention %', 'period': 'Months After Cohort'})
fig_line.add_scatter(x=avg_retention['period'], y=avg_retention['Average'], name='Average', line=dict(dash='dash'))
fig_line.update_layout(height=400)
st.plotly_chart(fig_line, use_container_width=True)
with tab2:
st.header("Conversion Funnels by Cohort")
selected_funnel_cohort = st.selectbox("Select Cohort for Detailed Funnel", funnel_filtered['cohort_month'])
funnel_selected = funnel_filtered[funnel_filtered['cohort_month'] == selected_funnel_cohort].iloc[0]
# Funnel chart
funnel_stages = pd.DataFrame({
'stage': ['Signup', 'Activated', 'First Purchase', 'Repeat'],
'users': [funnel_selected['Signup'], funnel_selected['Activated'],
funnel_selected['First Purchase'], funnel_selected['Repeat']]
})
fig_funnel = px.funnel(funnel_stages, x='users', y='stage', title=f"Funnel for {selected_funnel_cohort}")
st.plotly_chart(fig_funnel, use_container_width=True)
# Rates bar
rates_melt = funnel_selected[['Signup %', 'Activated %', 'First Purchase %', 'Repeat %']].rename('rate').reset_index()
fig_rates = px.bar(rates_melt, x='index', y='rate', title="Funnel Drop-off Rates (%)")
st.plotly_chart(fig_rates, use_container_width=True)
# All cohorts funnel comparison
funnel_melt = funnel_filtered.melt(id_vars='cohort_month', value_vars=['Signup %', 'Activated %', 'First Purchase %', 'Repeat %'],
var_name='stage', value_name='conversion_%')
fig_all_funnels = px.line(funnel_melt, x='cohort_month', y='conversion_%', color='stage',
title="Funnel Stages Across Cohorts")
st.plotly_chart(fig_all_funnels, use_container_width=True)
with tab3:
st.header("Repeat Rates by Cohort")
fig_repeat = px.bar(repeat_filtered.reset_index(), x=repeat_filtered.index.astype(str), y='repeat_rate_%',
title="Repeat Rate % (Users with ≥1 Repeat Purchase)",
labels={'index': 'Cohort Month'})
fig_repeat.update_xaxis(tickangle=45)
st.plotly_chart(fig_repeat, use_container_width=True)
col1, col2 = st.columns(2)
with col1:
st.metric("Overall Repeat Rate", f"{repeat_filtered['repeat_rate_%'].mean():.1f}%")
with col2:
best_cohort = repeat_filtered['repeat_rate_%'].idxmax()
st.metric("Best Cohort Repeat", f"{repeat_filtered.loc[best_cohort, 'repeat_rate_%']:.1f}%", f"{best_cohort}")
with tab4:
st.header("Cohort Tests (Statistical Comparisons)")
col1, col2 = st.columns(2)
with col1:
test_cohort1 = st.selectbox("Cohort 1", cohort_list)
with col2:
test_cohort2 = st.selectbox("Cohort 2", cohort_list, index=1)
test_period = st.slider("Test Retention at Period (Months)", 1, max_period, 3)
if test_cohort1 != test_cohort2:
# Retention curves for selected
test_df = retention_filtered[retention_filtered['cohort_month'].isin([test_cohort1, test_cohort2])]
fig_test_lines = px.line(test_df, x='period', y='retention_%', color='cohort_month',
title=f"Retention Curves: {test_cohort1} vs {test_cohort2}")
st.plotly_chart(fig_test_lines, use_container_width=True)
# Chi-square test on active/inactive at test_period
def get_active_size(cohort, period):
row = retention_df[(retention_df['cohort_month'] == cohort) & (retention_df['period'] == period)]
if not row.empty:
active = row['active_users'].iloc[0]
size = row['cohort_size'].iloc[0]
else:
active = 0
size = cohort_sizes[cohort]
return active, size - active
act1, inact1 = get_active_size(test_cohort1, test_period)
act2, inact2 = get_active_size(test_cohort2, test_period)
contingency = [[act1, inact1], [act2, inact2]]
chi2, p_value, dof, expected = stats.chi2_contingency(contingency)
st.subheader("Chi-Square Test Results (Retention at Period {test_period})")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Retention Cohort 1", f"{(act1 / (act1 + inact1) * 100):.1f}%")
with col2:
st.metric("Retention Cohort 2", f"{(act2 / (act2 + inact2) * 100):.1f}%")
with col3:
color = "🟢" if p_value < 0.05 else "🔴"
st.metric(f"p-value {color}", f"{p_value:.4f}")
st.write("**Contingency Table:**")
st.dataframe(pd.DataFrame(contingency, columns=['Active', 'Inactive'], index=[test_cohort1, test_cohort2]))
st.caption("*p < 0.05 indicates significant difference.*")
else:
st.warning("Select two different cohorts to run a test.")
st.sidebar.markdown("---")
st.sidebar.markdown("**Built by Sherlock (Trailblazer Labs)**")
st.sidebar.markdown("*To use your own data: Replace `generate_sample_data()` with `pd.read_csv('your_data.csv')`.*")