PROJECT 010 · PYTHON SOURCE
Ninety-day repeat purchase cohorts
Study-specific code. Shared modules, dependency versions, and reproduction instructions are included in all project files.
Download Python file ↓from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
import numpy as np
import pandas as pd
from scipy.stats import spearmanr
from sklearn.decomposition import PCA
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, precision_score, recall_score
from portfolio.data import load
from portfolio.constants import *
from portfolio.methods import result, sql, rates, associations, distribution, regression, classification, cluster
from portfolio.engine import execute
META = {'id': 10, 'dataset': 'retail', 'title': 'Ninety-day repeat purchase cohorts', 'question': 'How does repeat purchasing compare when every eligible customer receives 90 days of follow-up?', 'method': 'First-observed invoices and a fixed 90-day eligibility window.', 'action': 'Compare cohorts with equal observation time before testing acquisition or onboarding changes.', 'limitations': 'Historical invoice lines; credits are not reliably matched to original sales. Gross purchases are not profit. Unidentified customers cannot support customer-level conclusions. Exact repeated lines remain unless the study explicitly compares removal. '}
def analyze():
df = load('retail').copy()
s=df[df.is_sale & df.customerid.notna()].copy()
o=s.groupby(['customerid','invoiceno']).invoicedate.min().reset_index().sort_values('invoicedate')
first=o.groupby('customerid').invoicedate.min();cutoff=df.invoicedate.max()-pd.Timedelta(days=90)
eligible=first[first<=cutoff];o=o[o.customerid.isin(eligible.index)]
o['elapsed']=(o.invoicedate-o.customerid.map(first)).dt.total_seconds()/86400
repeat=o[(o.elapsed>0)&(o.elapsed<=90)].groupby('customerid').size()
customers=pd.DataFrame({'month':eligible.dt.strftime('%Y-%m'),'repeat_90d':eligible.index.isin(repeat.index).astype(int)})
t=rates(customers,'month','repeat_90d')
out=result(t,'month','rate','90-day repeat share','First observed is not necessarily first-ever purchase. Simultaneous invoices do not count as a later purchase. Wilson intervals assume independent customers.')
return out
if __name__ == "__main__":
execute(Path(__file__).parent, META, analyze)