# Time to next order (design, declared before any model is fitted)

Part five of the online retail study. Question: on the same public orders, when customers still quiet at the end of the data
are treated as censored and not as gone, does a survival model trained on one year say who will order next, and when, better
than days since the last order on later dates it never saw? Is the churn score it gives calibrated by band, does the same
score hold across the study's December and June dates, and what contact rule follows from a stated contact cost and order
value, against contacting everyone quiet?

The takeaway this round is built to test or refute in numbers: a churn score tells you who is likely to leave. It does not
tell you who a contact would keep. The score and the holdout have to run together.

This file and `protocol-survival.json` (the same settings in machine form, with the predictions) are committed before any
model is fitted. `survival_pipeline.py` refuses to run unless the protocol matches its pinned SHA-256 and, inside a git
checkout, is committed unmodified. The scoring stage then refuses unless the fitted model is committed.

## Why this is a part of this study and not a new one

Overlap test (improve an existing study when the question family or the data matches; a new study only when both differ).
Data: the same Online Retail II orders. Question family: which quiet customers get a contact. Both match, so this is part
five. What no published page answers:

- Part one counts who ordered again within 180 days at two dates and sizes a holdout. It has no time to the next order, no
  score per customer, no calibration and no contact rule from a cost. Its "most an offer can cost" caps an offer at an assumed
  lift on one fixed list.
- Part two counts monthly flows and three-month come-backs per event, with no model.
- Part three uses Kaplan-Meier and a discrete-time hazard model on synthetic subscription accounts, to show what a naive
  retention curve misses. It scores no customer and uses no real orders.
- Part four fits clusterings and, as one reference line, a logistic regression out of fold at the same date as its outcome. It
  has no censoring, no model frozen before later dates, no calibration and no drift.

## What was already known before this design

The published parts at the same dates: the quiet flag, the 330-customer list and its 67% and 43% return rates; the share of
active customers who ordered again within 180 days (57% on 1 June 2011, 48% on 1 December 2010); recency alone at an AUC of
0.73 and 0.70, and among quiet customers 0.62 and 0.60; the logistic regression at 0.78 on both dates; the holdout sizes (a
rise of about 6 points on all 2,358 quiet customers). Part one's monthly revenue shows the autumn peak. The predictions below
were written from those figures and general experience with these methods. Before this file was written, the only look at the
months used for training was their line count, the number of active customers per landmark date and the median order value
(£303.79, which sets the stated order value). No model had been fitted and no line after the cutoff had been read.

## 1. Data, cutoff and the dates

- Lines: the study's own cleaning, unchanged (`pipeline.read_sheets` and `retail/clean.py`), keeping quantity as well.
- Training cutoff: 1 December 2010. `prepare` writes lines before it and lines from it to two separate files. `fit` opens only
  the first. `score`, `boot` and `collect` open the second only after `require_fit_committed()` passes: the fitted model must
  be committed unmodified. This is why the training year is short: it is the only split that leaves both the December and the
  June date unseen.
- Scored dates, never seen in training: 1 December 2010 and 1 June 2011 (the first part's two dates, at 180 days), 1 March 2011
  (180 days) and 1 September 2011 (90 days, because the data ends 100 days later). Each date is reported on its own and never
  pooled.
- Population at a date: the first part's active customers (positive net revenue and at least one sale in the 365 days before
  it). The December and June populations must rebuild the first part's exactly.

## 2. Time to next order, and censoring

From a date, time to next order is the days until the customer's first sale line on or after the date. Follow-up stops at 180
days or at the end of the visible data, whichever comes first. A customer with no order by then is censored at that point. It
is not a churn event: nothing says the customer has left.

Time runs in 10-day steps, so 180 days is exactly 18 steps. A step counts only when it is wholly inside the follow-up. An order
in a partly seen last step is not used. In the training year the follow-up ends at the cutoff, so landmarks from July 2010
onward are censored before 180 days. That is where the handling matters.

"Churn" throughout means one thing: no order in the 180 days after the date (90 for September 2011). Churn score: the model's
probability of that.

## 3. Training landmarks and features

- Landmarks: the first of each month from 1 March to 1 November 2010: nine landmarks, each at least 90 days after the start of
  the data. A customer appears once per landmark at which it is active; resampling is by customer, so repeats are handled.
- Features, from lines before the landmark only, in the 365 days before it or since the start of the data if that is shorter:
  - log(1 + days since the last order);
  - log(1 + distinct orders per year), scaled up when fewer than 365 days are visible;
  - log(1 + net revenue per year), scaled the same way;
  - log(1 + rhythm), where rhythm is days since the last order over the customer's own mean gap between order days; this is the
    "own ordering rhythm" the first part says a real program should use;
  - a flag for customers with one order day, whose rhythm is set to 0;
  - log(1 + mean units per sale line), which marks bulk buyers.
- Features are standardized on the training rows, and the same scaling is applied at every later date. At the December and
  June dates a full 365 days is visible; in training the visible window is 90 to 335 days. This difference is a known limit.

## 4. Arms

All arms are fitted once on the training file and frozen, except arm 6.

1. **Survival model (primary).** Discrete-time hazard: a logistic regression on customer-steps with a piecewise baseline by days
   since the date (0 to 30, 30 to 60, 60 to 90, 90 to 120, 120 to 180), the six features, and one season term, the share of the
   step's days in September to November. The churn score is the product of (1 minus the hazard) over the steps, using the season
   term of the calendar dates ahead.
2. **Survival model without the season term.** The same without that term.
3. **Recency.** The plain rule, nothing fitted, ranks customers by days since the last order (used for AUC). For calibration it
   needs a probability, so it uses a table: Kaplan-Meier from the training landmarks in five recency bands (0 to 30, 31 to 60, 61
   to 90, 91 to 180, 181 to 365 days).
4. **Censored counted as churn.** One row per customer and landmark, all nine landmarks, a logistic regression on the six features
   with "no order seen" as churn, so a customer followed for 30 days counts the same as one followed for 180. This is the error
   the round exists to measure.
5. **Complete follow-up only.** The same logistic regression, using only the landmarks with 180 days of follow-up (March to June
   2010). The usual analyst's fix: right about censoring, but it discards the later months.
6. **Refit at June.** Arm 1's specification fitted on lines before 1 June 2011, landmarks from 1 March 2010 to 1 May 2011, censored
   at 1 June 2011. Scored only at 1 June 2011. It asks what a refit buys over the frozen score. It has no bearing on the frozen arms.

## 5. Measures, per date and per arm

- AUC for churn within the horizon, on all active customers and on quiet customers only. Recency's AUC must match part four's
  stored reference.
- Calibration by score band, with fixed bands on the predicted churn: under 20%, 20% to 40%, 40% to 60%, 60% to 80%, 80% or more.
  Each band: customers, mean predicted, observed. The mean band error is the customer-weighted mean of the absolute gap. The
  overall gap is mean predicted minus observed. Also the calibration slope and the Brier score. Any band under 11 customers is
  withheld in public tables.
- Time: predicted against observed share still quiet at 30, 60, 90, 120, 150 and 180 days, by score band, at the December and June
  dates.
- Drift: the population stability index (PSI) of the score bands between December and June for arms 1 and 2, the same for each
  feature (on December's deciles), the change in AUC and the change in the overall gap. Usual reading: under 0.10 stable, above
  0.25 a large shift.
- Proportional hazards check, on the training rows only: the improvement in log-likelihood from adding recency times time, and how
  far it moves the scores of the 1 June 2010 landmark. Reported, with no pass mark.

## 6. Intervals

95% percentile intervals from 500 joint resamples of customers. Each draw resamples customer keys over the union of the training
rows and the later dates, refits every arm with those weights on the fixed scaling, rescores, and recomputes every measure on the
same draw. So intervals show both which customers trained the model and which were scored. The fitted arms keep the frozen point
estimates; only intervals come from the draws.

## 7. The contact rule

Stated inputs, set here, none measured except where said:

- Contact cost: £5 (an email plus a small voucher).
- Order value: £300, the training year's median order (£303.79) rounded.
- Margin: 40%, the first part's assumption. So one extra order is worth £120.
- Persuaded share: the share of customers who would otherwise place no order and who place one because of the contact. It is not
  in the data; the base case assumes 10%.

Rule: contact when churn score x persuaded share x order value x margin is at least the cost, which gives a score threshold of
5 / (0.10 x 300 x 0.40) = 41.7%. Break-even lift: 5 / 120 = 4.2 extra orders per 100 contacts. Lists at each of the December and
June dates: everyone quiet (the comparison); the first part's high-value list; the rule (every active customer above the
threshold); the rule among quiet customers only.

Value: each observed non-returner on a list is won with the assumed persuaded share, for one order's margin, minus the cost of every
contact. Returners are assumed not to change. So who stays away is measured and what a contact does is assumed: the net figures are
scenarios, never findings. Response patterns, persuaded share by score band from low to high:

- `flat`: 10%, 10%, 10%, 10%, 10%. Under this pattern the better list is simply the one with more non-returners per contact, so the
  score wins almost by construction; the page must say so.
- `middle`: 5%, 10%, 20%, 10%, 2%. Those near the line can be moved; those gone cannot.
- `near`: 20%, 20%, 10%, 5%, 2%. The further gone, the less a contact does.

Also reported for each pattern: the list a team would pick if it knew the pattern (contact a band when its mean score x its persuaded
share x £120 is at least the cost), which is the gain a holdout could reveal. Sweep, one input at a time around the base case and in a
full grid in the results: cost £1, £5, £20; persuaded share 5%, 10%, 20%; order value £150, £300, £600; margin 30%, 40%, 50%.

Holdout, from the first part's formula (`measures.minimum_detectable_lift`, 80% power, two-sided 5%, 50/50 arms): the smallest lift
detectable on all quiet customers and within each score band, at the June and December dates, and the customers per arm needed to
detect the break-even lift. No contact is simulated or estimated: the data has none.

## 8. Predictions (written before any fit; scored on the point estimates)

Held when the estimate falls inside the band, missed otherwise. Listed in machine form in `protocol-survival.json`:

1. June: survival model's AUC is at least 0.03 above recency's.
2. December: the same.
3. June: survival model's AUC lands within 0.03 of part four's out-of-fold logistic regression (0.784), though frozen six months
   before the date.
4. June, quiet customers only: survival model's AUC is at least 0.02 above recency's.
5. June: survival model's mean band error is at most 5 points.
6. December: the same.
7. Recency's table has a larger mean band error than the survival model at both dates.
8. Without the season term, the overall gap at June minus the gap at December is at least +5 points: the score reads too high in
   June against December.
9. The season term at least halves that difference.
10. Censored counted as churn overstates churn by at least 10 points at both dates.
11. Complete follow-up only has a larger absolute gap than the survival model at June.
12. PSI of the no-season score bands between December and June is under 0.10: the customers move little, and the drift is in what
    they do next.
13. The survival model's AUC at June and December differ by at most 0.02.
14. Base case at June: at least 10% of quiet customers fall below the threshold, and at least 100 customers not yet quiet are above it.
15. Under `flat`, the rule nets more than everyone quiet at both dates. Close to a safe bet, as section 7 says.
16. Everyone quiet nets above zero under `flat` at both dates and below zero under `near` at June. Arithmetic on an assumption, scored
    only to show the sign flips.
17. The break-even lift is below the smallest detectable lift of the all-quiet test and of every score band at June: one date's test
    cannot confirm a contact pays at these stated inputs.
18. Refit at June has a smaller absolute gap than the frozen survival model, with an AUC within 0.01.

No prediction may be edited, dropped or added after the first fit; any later idea is labelled as added after the results and is not
scored. A change before the results is a numbered "Change N to the protocol", committed before use.

## 9. Worked example (chosen by a declared rule)

At 1 June 2011, among quiet customers below the base-case threshold, the customer nearest that group's median score, ties by hashed
key; if the group is empty, the quiet customer nearest the threshold. The page shows counts in bands, money to the nearest £100, days
to the nearest 10 and never the key.

## 10. Public files

Aggregates, plus one derived table, `data/derived/survival-scored.csv`: per customer and scored date, the hashed key, days since the
last order, the quiet flag, the first part's tier, the arms' scores, the days to the next order and whether it was seen. It carries
no more about a customer than the first part's customer tables plus the time to the next order, and it lets every measure replay with
no download. No account, name or product.

## 11. Outputs

`results-survival-fit.json` (the frozen model; no order after the cutoff), committed before scoring; `results-survival.json`; the page
`time-to-next-order.html` from `render_survival.py`, linked from the main page with one sentence; `README-survival.md`; tests in
`tests/test_survival.py` and `tests/test_render_survival.py`.

## 12. Limits known before the results

One wholesaler-heavy UK gift-ware seller. Orders only: no contact is recorded, so nothing here estimates what a contact adds. One
training year, so the season term rests on one autumn, and landmarks start in March, so January and February are not in the training
hazards. Time to the next order is one event per landmark; it is not a model of repeat purchasing.
