Appendix E — Statistics for Motorsport Analytics

Every chapter of this book ends a calculation the same way: with a number, an interval and an n. This appendix collects the statistical machinery behind those three things in one place. It covers the methods the chapters actually used, when each one is the right tool, the formula in a form you can check by hand, and a worked example on the book's own data. Just as important, it covers the places where the obvious method gave the wrong answer, because in F1 data the traps are specific and they repeat.

All of the examples live in one script, appendices/code/appendix_e_examples.py. It prints a header (== E.3.2 and so on) for each section below, and every output block in this appendix is pasted from a real run of it. Run it from the book root:

python appendices/code/appendix_e_examples.py            # everything, about 70 seconds
python appendices/code/appendix_e_examples.py E.3.3 E.12 # just those sections

It makes no network calls, and every random step has a seed, so you will get the same numbers. Where this appendix quotes a result that a chapter computed and this script does not rerun, it says which chapter the number comes from.

Two companions sit beside this appendix. The definitions of the quantities being estimated (clean lap, pit loss, degradation, race pace) live in Appendix B and the metric encyclopedia, Appendix D. The Python idioms are in Appendix A. This appendix is about the step after the definition: how sure can you be?


E.1 The map: which method, which chapter

F1 data has a shape that decides most statistical choices before you open a notebook:

  • Laps are not independent. Laps of one driver in one stint share a car, a set of tyres, a fuel load and a strategy. Laps of one race share a track, a temperature and a safety car.
  • The sample of races is small. 2023–2026 gives 91 Grands Prix in the OpenF1 era, about 76 of them dry. A season is 21–24 rounds. Many interesting questions come down to n = 4 or n = 11.
  • Car and driver are tangled. A driver is only ever observed in one car per race, and the best drivers tend to sit in the best cars.
  • Several things trend together over a race. Fuel burns off, the track rubbers in, and tyres wear, all at once and all roughly in step with the lap number.

Each method below answers one of those problems.

Method Use it when Where the book uses it Section
Wilson interval quoting any rate from counts everywhere; Ch 12, 13, 14, 15, 16, 28 E.2
Percentile bootstrap interval for a median or any awkward statistic Ch 3, 10, 20, 21, 22, 25 E.3
Race-level (cluster) bootstrap observations are grouped in races Ch 20, 21, 26 E.3.2–E.3.3
Permutation / sign-flip test comparing groups with few units and no trusted distribution Ch 15, 17, 24 E.4
OLS with cluster-robust errors a slope from laps that come in drivers or races Ch 4, 16, 20, 22 E.5
Weighted least squares units carry different amounts of information Ch 15, 21 E.5
Fixed effects removing everything constant about a driver, stint, race or car Ch 16, 20, 21 E.6
Mixed (random-effects) models many small groups, each a noisy version of a common value Ch 22 E.6
Ridge regression many overlapping effects, some poorly identified Ch 21, 26 E.6
Logistic regression probability of a yes/no outcome Ch 5, 13, 26 E.7
Ordinal regression an ordered outcome (bands, positions) Ch 26 E.7
Poisson model counts of events per race Ch 14, 29 E.8
Hazard rates events per lap at risk Ch 14, 18, 27, 37 E.8
Kaplan–Meier time to an event when some units never have it Ch 37 E.9
Change-point detection did a team's level shift during a season? Ch 24 E.10
Benjamini–Hochberg many tests at once Ch 24 E.10
Spearman correlation monotone association, robust to outliers Ch 8, 10, 20, 23 E.11
Split-half reliability is a driver or team metric a trait or noise? Ch 8, 9, 17, 21, 23 E.11
Shrinkage / empirical Bayes ranking many units each measured with noise Ch 17, 20, 26, 34, 37 E.12
Brier score, log loss, calibration scoring probability forecasts Ch 13, 21, 26, 27 E.13
Walk-forward validation any model that will predict the future Ch 11, 16, 22, 26 E.14
Monte Carlo, common random numbers comparing strategies under randomness Ch 14, 27, 33, 36 E.15
Identification analysis before trusting any coefficient Ch 3, 20, 22 E.16

E.2 Proportions: the Wilson interval

When. Any time you quote a rate from counts: win rates, safety-car rates, undercut success, the share of stops that are slow. The book's rule (see Chapter 14) is that every such rate carries a Wilson interval and its n.

📐 Definition: Wilson score interval. For k successes in n trials, with p̂ = k/n and z = 1.96,

$$\text{centre} = \frac{\hat p + z^2/(2n)}{1 + z^2/n}, \qquad \text{half-width} = \frac{z}{1+z^2/n}\sqrt{\frac{\hat p(1-\hat p)}{n} + \frac{z^2}{4n^2}}.$$

In words: it pulls the estimate a little towards one half and widens the interval when n is small, so that it never runs below 0 or above 1. The toolkit's metrics.wilson_ci(k, n) returns (p, low, high).

The textbook alternative, the Wald interval p̂ ± 1.96 √(p̂(1 − p̂)/n), is fine when n is large and p is not near 0 or 1. F1 rarely gives you that.

r = history.results(list(range(2023, 2027)))
g1 = r[r.grid == 1]                                   # actual starting grid, not qualifying order
k, n = int((g1.position == 1).sum()), len(g1)
p, lo, hi = metrics.wilson_ci(k, n)
== E.2 Proportions: Wilson intervals
Started from grid slot 1 and won, 2023-2026 R21: 56/91 = 0.615  Wilson [0.513, 0.709]  Wald [0.515, 0.715]
2026 only: 15/21 = 0.714  Wilson [0.500, 0.862]  Wald [0.521, 0.908]

Small and extreme counts (Wilson vs Wald):
  Singapore races with a full SC, 2023-26         1/4    p 0.250  Wilson [0.046, 0.699]  Wald [-0.174, +0.674]
  Singapore races with SC or VSC, 2023-26         2/4    p 0.500  Wilson [0.150, 0.850]  Wald [+0.010, +0.990]
  big stops (>=320 km/h) shorter than 100 m       0/230  p 0.000  Wilson [0.000, 0.016]  Wald [+0.000, +0.000]
  2023-26 GPs with >=1 SC                        44/91   p 0.484  Wilson [0.384, 0.585]  Wald [+0.381, +0.586]

Coverage of nominal 95 % intervals (20,000 simulated samples each):
  p = 0.25, n =   4: Wilson 0.949   Wald 0.631
  p = 0.25, n =  21: Wilson 0.960   Wald 0.906
  p = 0.50, n =  21: Wilson 0.921   Wald 0.921
  p = 0.05, n =  91: Wilson 0.951   Wald 0.942

Read the middle block first. With 1 safety car in 4 Singapore races, Wald says the true rate could be −17 %, which is nonsense. Wilson says 5 % to 70 %, which is the honest answer: four races tell you almost nothing. With 0 of 230 braking stops under 100 m (the Chapter 7 result), Wald collapses to a zero-width interval and claims certainty. Wilson says the true share is below 1.6 %, which is what you can actually defend. The coverage simulation makes the same point: at n = 4, a "95 %" Wald interval contains the truth only 63 % of the time.

Note the definitional detail in the first line. The book's pole-to-win rate for 2023–26 is 62.6 % (57/91), counted from qualifying. This script counts the car that started from grid slot 1, after penalties, and gets 56/91. Both are correct for their definitions, and the intervals overlap almost entirely. Say which one you mean.

⚠️ Common pitfall: a rate with no n. "Singapore has a 65 % safety-car probability" is a claim you can't check. "1 of 4 races, 95 % interval 5–70 %" is evidence, and it shows at a glance that the claim isn't supported. Chapter 14 pools Singapore with the per-lap hazard across all circuits for exactly this reason.


E.3 The bootstrap

The bootstrap estimates the uncertainty of a statistic by recomputing it on many resamples of the data, drawn with replacement, and reading the spread. It needs no formula for the statistic's standard error, which is why the book uses it for medians, slopes of medians, network ratings and simulation outputs.

📐 Definition: percentile bootstrap. Draw B resamples of the n independent units, compute the statistic θ̂_b on each, and report the 2.5 % and 97.5 % quantiles of the θ̂_b as the 95 % interval. metrics.bootstrap_ci(x, stat=np.median) does this with B = 10,000 and seed 42, and returns (estimate, low, high). That is three values, not two, a detail that tripped up two chapters.

E.3.1 An interval for a median

The pit loss at one race is a small, skewed sample with a long right tail (traffic, a slow stop). The book reports its median, so the interval should be for the median.

ps = metrics.pit_loss(f1data.session(2025, "rodriguez", "R"), per_stop=True)
u = ps[ps.used].pit_loss_s.to_numpy()
est, lo, hi = metrics.bootstrap_ci(u, np.median)
== E.3.1 Bootstrap: the percentile interval for a median
2025 Mexico City GP green-flag pit loss: n = 26 stops, median 22.475 s, 95 % bootstrap [21.787, 23.226] (10,000 resamples, seed 42)
  mean 23.572 s, min 18.776, max 34.603
  bootstrap of the MEAN instead: 23.572 [22.357, 24.999]

The mean is pulled up by one 34.6 s stop and its interval is twice as wide. That is the reason the book's pit loss is a median (Chapter 12).

E.3.2 Resample the unit that is independent

The bootstrap assumes the resampled units are independent. If they are not, it underestimates the uncertainty, sometimes badly. In F1 the units that are close to independent are usually races (or race weekends), not laps or stints.

Here is the median degradation rate across every 2025 dry-race stint, bootstrapped two ways: treating each stint as independent, and resampling whole races so that all of a race's stints travel together.

keys = x.session_key.unique()
byrace = {k: x.loc[x.session_key == k, "slope_s_per_lap"].to_numpy() for k in keys}
for _ in range(5000):
    pick = rng.choice(keys, len(keys), replace=True)          # whole races, with replacement
    bs.append(np.median(np.concatenate([byrace[k] for k in pick])))
== E.3.2 Bootstrap: resample the unit that is independent (stints vs races)
2025 dry races: 20, MEDIUM/HARD stints with >= 6 usable laps: 736
  MEDIUM median +0.0488 s/lap (n = 403 stints, 20 races) | stint bootstrap [+0.0437, +0.0560] width 0.0123 | race bootstrap [+0.0296, +0.0660] width 0.0364
  HARD   median +0.0335 s/lap (n = 333 stints, 20 races) | stint bootstrap [+0.0278, +0.0390] width 0.0113 | race bootstrap [+0.0197, +0.0468] width 0.0271
  spread of race medians (SD): MEDIUM 0.0406, HARD 0.0355 s/lap

The race bootstrap is three times wider. The stint bootstrap pretends 403 MEDIUM stints are 403 independent pieces of evidence. In fact they come from 20 races, and the race-to-race spread (circuit, asphalt, temperature, the allocation Pirelli chose) is far larger than the stint-to-stint spread within a race. The honest n is closer to 20 than to 403. (Degradation here is fuel-corrected with the toolkit's assumed 100 kg start fuel and 0.03 s/kg; see E.16 and pitfall P1.)

🔍 Why this works. A bootstrap mimics the process that generated the data. If the next season would bring new races, and each race brings its own conditions, then a resample must draw new races, not new stints from the same races. The rule of thumb: resample at the level where you'd get fresh, independent draws if you collected more data. That is the race for pace and degradation questions, the race weekend for practice-to-race questions, and the season for championship questions.

The same logic drives every race-level bootstrap in the book: the fuel-effect median over 76 dry races in Chapter 20 (−0.0563 s/lap [−0.0609, −0.0499]), the paired model comparisons in Chapter 26, and the teammate chain.

E.3.3 The pinning bug: when the resample changes the model

The teammate chain in Chapter 21 links every driver to every other through shared teammates. Each teammate-season gives one equation, y_ab = θ_a − θ_b, where y is the median qualifying gap, and θ is solved by least squares with Hamilton fixed at 0. The interval comes from resampling races (year-round pairs) and refitting.

Resampling can change the network. A driver who stood in for two rounds is normally dropped (a teammate-season needs at least 3 rounds). In a resample where one of those rounds is drawn twice, he suddenly has 3 rounds and a link. An early implementation built each replicate's design matrix with columns fixed to the drivers of the full-data fit. The newcomer had no column, so his row kept only his teammate's +1, and the least-squares fit treated the newcomer as if his θ were exactly 0, Hamilton's level. Nothing raised an error. The script reproduces both versions on the same resamples:

def buggy_fit(ps, ref="hamilton", drivers=DRV):          # columns fixed to the full-data driver list
    drv = [d for d in drivers if d != ref]
    idx = {d: i for i, d in enumerate(drv)}
    X = np.zeros((len(ps), len(drv)))
    for k, (a, b) in enumerate(zip(ps.a, ps.b)):
        if a in idx: X[k, idx[a]] += 1                     # a driver not in idx simply has no column:
        if b in idx: X[k, idx[b]] -= 1                     # his theta is silently 0
    ...
good.append(ratings.chain_fit(psb).get("max_verstappen"))  # fixed: fit each replicate on its own network
== E.3.3 Bootstrap: the pinning bug in a network fit
Teammate network: 386 teammate-seasons, 140 drivers in Hamilton's component
Point estimate Verstappen - Hamilton: -0.230 % of lap time
1000 race-level bootstrap replicates (seed 42), both fits on the SAME resamples:
  replicates whose Hamilton component contains a driver missing from the full-data fit: 100% (median 7 such drivers)
  fixed (own component)  median -0.235  95 % [-0.408, -0.069]  width 0.338  P(< 0) 1.000
  buggy (pinned)         median -0.324  95 % [-0.528, -0.019]  width 0.509  P(< 0) 0.981
  replicates where the two fits differ by > 0.01 pp: 99%

The point estimate (−0.230 %) is the same either way, because the full data contain no newcomers. Only the interval is wrong: the pinned version is 50 % wider, skewed (its median, −0.324, sits far from the point estimate) and nearly touches zero. The fixed run reproduces Chapter 21's published interval, −0.408 to −0.069; the pinned run reproduces the wider interval from the book's earlier reference calculation, −0.528 to −0.019.

⚠️ Common pitfall: a bootstrap whose replicates fit a different model. Whenever the structure of the problem depends on the data (which drivers are connected, which compounds have enough stints, which circuits appear), let each replicate rebuild that structure, then report the quantities you care about. A symptom worth checking every time: the bootstrap median should sit close to the point estimate. When it doesn't, the resampling is doing something your model isn't.


E.4 Permutation tests

When. You want to know if a difference between two groups could be chance, the groups are small, and you don't trust a normal approximation. A permutation test builds the null distribution directly: if the label (2026 vs earlier, wet vs dry) didn't matter, shuffling it shouldn't change the statistic.

📐 Definition: permutation p-value. Compute the observed statistic T. Shuffle the group labels across units B times, computing T_b each time. The two-sided p-value is (1 + #{|T_b| ≥ |T|}) / (B + 1). The +1s count the observed arrangement as one of the possibilities and keep p above zero.

Chapter 17 asked whether 2026's new cars made lap 1 more chaotic. The unit is the race, and the statistic is the race's mean absolute lap-1 position change among grid slots 1–20.

churn = d.assign(a=d.places_gained.abs()).groupby(["year", "round"]).a.mean()   # one value per race
perm = [x[m].mean() - x[~m].mean() for m in (rng.permutation(is26) for _ in range(9999))]
== E.4 Permutation test: was 2026 lap 1 really more chaotic?
Race-level churn = mean |places gained on lap 1|, grid slots 1-20: 2026 1.998 (n = 21 races) vs 2022-25 1.518 (n = 92); diff +0.479
Permutation test (9999 shuffles of the season label, seed 42): one-sided p = 0.0118, two-sided p = 0.0190
Welch t-test for comparison: t = 2.18, two-sided p = 0.0375
Shuffling individual starts instead (n = 2185): diff +0.463, two-sided p = 0.0001  <- too small: starts in one race are not independent

The race-level test gives p = 0.019 (Chapter 17's run, with its own shuffles, gave 0.0179). The last line is the warning. Shuffle individual starts and the p-value drops a hundredfold, because the test now believes it has 2,185 independent observations. One lap-1 pile-up moves five cars at once; those five moves are one event. The unit you permute must be the unit that is exchangeable under the null, the same rule as E.3.2.

Two variants appear in the book:

  • Sign-flip tests for paired data. When each unit gives a difference (driver vs teammate, wet minus dry), flip the signs at random under the null "no consistent direction". Chapter 15 used it for wet-weather skill: driver effects explained more of the wet-dry shift than random sign patterns did (p = 0.011, 2,000 flips, seed 42).
  • Permutation tests inside change-point detection (E.10), where the shuffle destroys the order of a season's races.

⚠️ Common pitfall: exchangeability with autocorrelation. Shuffling races within a season assumes race 5 and race 15 are interchangeable under "no change". Real team-performance series drift, so treat p-values near 0.05 from order-destroying shuffles as weak evidence. Chapter 24 says this in its function docstring, and it matters in E.10.


E.5 OLS, cluster-robust errors and weighted least squares

OLS on one stint

Ordinary least squares fits y = Xβ + ε by minimising the sum of squared residuals: β̂ = (XᵀX)⁻¹Xᵀy. The book's degradation rate is OLS of lap time on tyre age within one stint (metrics.degradation), with a t-interval from the usual standard error.

nor = lp[lp.acronym == "NOR"]; soft = nor[nor.compound == "SOFT"]
raw = metrics.degradation(soft)                              # y = raw lap_duration
fc  = metrics.degradation(metrics.fuel_corrected(soft))      # y = lap_time_fc
2025 Mexico City GP, Norris SOFT stint (OLS of lap time on tyre age, clean laps, stint lap > 1):
  raw lap time      slope +0.0214 s/lap  95 % t-CI [+0.0076, +0.0353]  n = 28
  fuel-corrected    slope +0.0637 s/lap  95 % t-CI [+0.0499, +0.0775]  n = 28  (toolkit ASSUMPTION: 100 kg start fuel, 0.03 s/kg)

Same laps, same model, a threefold difference in the answer. The difference is the fuel correction, and it is an assumption, not a measurement. Pitfall P1 and section E.16 come back to this.

The t-interval assumes the residuals are independent with constant variance. Within one stint that is roughly tenable. As soon as you pool laps across drivers, it is not.

Cluster-robust standard errors

metrics.estimate_fuel_effect pools a whole race: lap time on lap number, with a fixed effect per driver and a compound-specific tyre-age slope. A driver's laps share residual structure (traffic phases, tyre-management phases), so the toolkit clusters the standard errors by driver.

📐 Definition: cluster-robust (sandwich) variance. With clusters g,

$$\widehat{\mathrm{Var}}(\hat\beta) = (X^\top X)^{-1}\Big(\sum_g X_g^\top \hat e_g \hat e_g^\top X_g\Big)(X^\top X)^{-1}.$$

It lets residuals within a cluster correlate in any way while assuming clusters are independent. It needs a reasonable number of clusters; with fewer than about 15–20, treat it as approximate.

Fuel + track-evolution slope, same race (OLS, driver-session FE, compound x tyre age; SE clustered by driver):
  -0.0450 s/lap  95 % [-0.0485, -0.0416]  n = 1061 laps, 18 drivers
  SE of the lap_number slope: iid 0.0010  vs  clustered by driver 0.0018  (ratio 1.77)
  median within-driver lag-1 autocorrelation of residuals: 0.295

The naive standard error is 1.8 times too small, and the reason is visible: consecutive residuals of one driver correlate at about 0.3. Chapter 9 found the same structure across 79 dry races (lag-1 ρ 0.460 around stint lines), and Chapter 20 clusters its traffic regressions by race for the same reason. With 18 clusters, this is near the lower limit where the sandwich estimator is trustworthy.

Weighted least squares

When units carry different amounts of information, weight them. WLS minimises Σ wᵢ(yᵢ − xᵢβ)². For a mean of n noisy observations with variance σ², the variance is σ²/n, so the efficient weight is n. The teammate chain uses the gentler √n: a 24-round teammate-season counts more than a 3-round one, but not 8 times more, because pairs also differ for reasons that more rounds don't average away.

Teammate chain (y_ab = theta_a - theta_b per teammate-season, median gap, n >= 3 rounds):
  WLS, weights sqrt(n):  Verstappen - Hamilton -0.230 %   Norris -0.195   Alonso +0.075
  OLS, equal weights:    Verstappen - Hamilton -0.181 %   Norris -0.120   Alonso +0.091
  teammate-season rounds n: median 16, min 3, max 24

The weighting moves Verstappen–Hamilton by 0.05 percentage points. That is a quarter of the estimate, and it is why Chapter 21 reports a range across seven specifications (−0.292 to −0.127 %) and the verdict "leans Verstappen by about 0.1–0.3 % of a qualifying lap; the direction is robust, the size depends on the method." Weights fix unequal precision, not bias: in Chapter 15 a pooled WLS slope of the slick-versus-intermediate penalty came out physically backwards (0.435), because no weighting can undo selection in which laps exist.


E.6 Fixed effects, mixed effects and ridge

All three answer the same question: how do you compare units that are each observed under different conditions? They differ in how much they trust the groups.

Fixed effects

A fixed effect is a separate intercept for every group: every driver-stint, every driver-session, every car-season. It absorbs everything constant within the group, measured or not. The cost: a fixed effect can only learn from variation within its group.

  • Chapter 16 estimates track evolution in qualifying with driver fixed effects: each driver's later laps compared with his own earlier laps (median −0.0190 s per minute, negative in 81 of 81 sessions).
  • Chapter 20 estimates the dirty-air penalty within driver-stint: a car running 0–1 s behind another is +0.495 s/lap [0.386, 0.604] slower than the same car on the same tyres in clean air.
  • Chapter 21 separates driver from car with a driver effect plus a car-season effect. A driver effect is identified only through drivers who change teams, and a car-season effect only through drivers who share it.

Ridge: fixed effects with a leash

Driver + car-season with plain fixed effects is badly conditioned: a driver with five rounds in one car is almost perfectly confounded with that car. Ridge regression adds a penalty α Σβ² that shrinks every effect towards zero, more strongly for effects the data support weakly.

$$\hat\beta_{\text{ridge}} = \arg\min_\beta \;\|y - X\beta\|^2 + \alpha\|\beta\|^2 = (X^\top X + \alpha I)^{-1}X^\top y.$$

for alpha in (0.1, 1.0, 10.0):
    reg = ratings.driver_car_regression(alpha=alpha)        # Q1 gap to fastest, 2014-2026, drop > 5 %
    vs = ratings.variance_shares(reg)                       # var(car) / var(car + driver) per season
== E.6 Fixed effects, mixed effects and ridge: driver + car-season
ridge alpha  0.1: n = 5375, R2 0.565, resid SD 0.608 %, Verstappen - Hamilton -0.222 %, median car share 0.718, driver share 0.100
ridge alpha  1.0: n = 5375, R2 0.564, resid SD 0.609 %, Verstappen - Hamilton -0.166 %, median car share 0.572, driver share 0.153
ridge alpha 10.0: n = 5375, R2 0.544, resid SD 0.623 %, Verstappen - Hamilton -0.054 %, median car share 0.381, driver share 0.291
car share of explained variance by season (alpha 1):
  2014 0.62, 2015 0.57, 2016 0.48, 2017 0.63, 2018 0.70, 2019 0.70, 2020 0.67, 2021 0.33, 2022 0.49, 2023 0.33, 2024 0.33, 2025 0.28, 2026 0.80
drivers with < 10 Q1 rounds: 10; their mean |effect| at alpha 0.1 vs 10: 0.606 vs 0.377 %

This is the most important table in the appendix for anyone who wants to say "the car is X % of performance". The fit barely changes (R² 0.565 → 0.544), yet the car share swings from 72 % to 38 % with the penalty. The penalty decides how much of the overlap between "good driver" and "good car" goes to each side, and the data can't overrule it. Chapter 21's reading, which every later chapter follows: the car's share is a model output with a wide range (28–80 % by season, 25–72 % by penalty), never a constant.

Mixed (random-effects) models

A mixed model treats the groups as draws from a population: each stint's degradation slope is the field's slope plus a random deviation with variance τ². The fitted stint slopes (BLUPs) are then shrunk towards the field value, more so for short, noisy stints. This is the regression version of E.12.

m = D.mixed_deg(lpd, "SOFT")   # statsmodels MixedLM: yy ~ age, groups = driver-stint, re_formula="~age", REML
Mixed model, 2025 Mexico City SOFT (random intercept + slope per driver-stint, REML, default fuel):
  fixed (field) slope +0.0627 [+0.0540, +0.0715] s/lap; SD of stint slopes 0.0152; 27 stints, 593 laps; median of 27 stint OLS slopes +0.0565
  shrinkage of the extremes (OLS -> mixed-model slope):
    ALO-1  n = 15  +0.015 -> +0.047
    STR-1  n = 21  +0.031 -> +0.048
    RUS-3  n = 19  +0.119 -> +0.080
    SAI-3  n =  8  +0.125 -> +0.069

Sainz's 8-lap stint at +0.125 s/lap is pulled almost halfway back; the model judges most of that slope to be noise. Chapter 22 ran this on 161 race-compound cells: the mixed fixed slope and the simple median of stint slopes correlate at 0.925, and the single-stint spread is 40 % narrower after shrinkage. The median is a good, cheap estimator of the field rate; the mixed model earns its keep when you need individual stints.

🔍 Why this works. Fixed effects say "every group is its own thing; tell me only about within-group changes". Random effects say "groups are similar; borrow strength across them". Ridge sits between, with the penalty playing the part of 1/τ². Use fixed effects when the group-level confounding is the threat (driver quality correlated with car quality); use random effects or ridge when the threat is noise in many small groups.


E.7 Logistic and ordinal regression

Logistic regression

For a yes/no outcome, model the log-odds as linear: log(p/(1 − p)) = β₀ + β₁x. Coefficients are changes in log-odds; exp(β₁) is an odds ratio. Predictions stay between 0 and 1.

r["win"] = (r.position == 1).astype(int); r["lg"] = np.log(r.grid)
fit = smf.logit("win ~ lg", data=r).fit(disp=0)
== E.7 Logistic and ordinal regression: what a grid slot is worth
Logistic P(win) ~ log(grid), Jolpica 2014-2026 R21, grid slots 1-20: n = 5401 starts
  intercept +0.289 (SE 0.108), slope -2.412 (SE 0.105)
  grid  1: model 0.572   observed 0.549 [0.490, 0.607] (n = 273)
  grid  2: model 0.201   observed 0.232 [0.185, 0.285] (n = 272)
  grid  3: model 0.086   observed 0.099 [0.069, 0.140] (n = 273)
  grid  5: model 0.027   observed 0.018 [0.008, 0.042] (n = 273)
  grid 10: model 0.005   observed 0.015 [0.006, 0.037] (n = 271)
  odds ratio for doubling the grid slot: 0.188

Two habits are on display. First, choose the scale of the predictor: log(grid) says that the step from P1 to P2 matters as much as the step from P5 to P10, which is what racing intuition says. Second, check the model against the observed rates with their Wilson intervals. The fit is inside the intervals at grid 1–5 and too pessimistic at grid 10, where wins come from safety cars and rain that a one-variable model can't see.

The book's richest logistic model is the undercut curve in Chapter 13: logit P = 2.171 − 1.597 × gap, so a 50 % chance at a 1.36 s gap and 80 % at 0.5 s. Scored leave-one-race-out, it beat the base rate (log loss 0.5348 vs 0.6350), and extra predictors added nothing out of sample. Chapter 5 shows the main failure mode: with circuit fixed effects, the logit for an extra preparation lap separated (some circuits had zero such runs, so their coefficients ran to infinity), and the chapter switched to a linear probability model.

Ordinal regression

When the outcome is ordered (podium / points / no points), a proportional-odds model fits one slope and several thresholds: P(Y ≤ j) = logistic(θⱼ − βx).

f["band"] = pd.cut(f.position, [0, 3, 10, 30], labels=["podium", "P4-P10", "P11+"])
om = OrderedModel(f["band"], f[["grid"]], distr="logit").fit(method="bfgs", disp=0)
Ordinal (proportional-odds) logit of finish band on grid slot, finishers 2014-2026: n = 4495
  grid coefficient +0.3754 (SE 0.0087) on the log-odds of a WORSE band
         podium  P4-P10   P11+
grid 1    0.682   0.303  0.014
grid 5    0.323   0.615  0.062
grid 10   0.068   0.630  0.301
grid 15   0.011   0.251  0.738
  observed shares by grid group (1 | 2-5 | 6-10 | 11-15):
band      podium  P4-P10   P11+
grid                           
(0, 1]     0.884   0.104  0.012
(1, 5]     0.502   0.464  0.034
(5, 10]    0.068   0.710  0.223
(10, 15]   0.015   0.388  0.597
  same model on log(grid): coefficient +2.933 (SE 0.069); P(podium) grid 1 0.968, grid 5 0.210, grid 10 0.034, grid 15 0.010
  log-likelihood: linear grid -3116.9, log grid -3010.7

On linear grid, the model gives the pole-sitter a 68 % podium chance against an observed 88 %. Log(grid) fits much better (log-likelihood up by 106) but now overshoots at pole (97 %). Neither form is right at the extreme, because the proportional-odds assumption forces one slope to serve both thresholds. In Chapter 26 an ordinal model of finishing position scored worse than a plain logit for the winner (log loss 1.436 vs 1.292, walk-forward 2014–26): pick the model for the question you're scoring, not for the most complete description of the outcome.


E.8 Counts and hazards

Poisson counts

The number of events in a race (safety cars, passes, retirements) is a count. The Poisson model has one parameter: mean = variance = λ, and P(k events) = e^(−λ)λᵏ/k!. Its first check is the dispersion, variance divided by mean.

== E.8 Counts and hazards: Poisson incidents, per-lap DNF hazard
SC/VSC/red incidents per GP, OpenF1 race control 2023-2026 R21: n = 91 races, total 118
  mean 1.297, variance 1.278, dispersion (var/mean) 0.99
  incidents:       0     1     2     3     4     5     6
  observed:       25    32    20    11     2     1     0
  Poisson exp:  24.9  32.3  20.9   9.0   2.9   0.8   0.2
  P(>= 1 incident): Poisson 1 - exp(-1.30) = 0.727; observed 0.725 (66/91)

Neutralisation incidents are almost perfectly Poisson. That is useful: 1 − e^(−λ) turns a rate into "the chance of at least one", and it is the bridge from Chapter 14's rates to the simulator in Chapter 27.

Green-flag passes are the opposite case. In Chapter 29, passes per race had dispersion about 8: some circuits produce ten times the passes of others. A Poisson regression with circuit fixed effects still estimates the rate ratio consistently (2026 vs 2025: 1.76 [1.36, 2.28]), but only with robust (HC1) standard errors; naive Poisson errors would be about √8 ≈ 2.8 times too narrow.

Hazards: events per unit of exposure

A rate per race hides when the risk occurs. A hazard divides events by exposure: incidents per lap at risk, retirements per car-lap. Chapter 14 found an incident-start hazard of 0.1758 on lap 1 (16/91), 0.0323 on laps 2–10, 0.0186 in the middle of the race and 0.0149 over the final 10 laps, so lap 1 is 8.8 times riskier than the rest. The same structure, for retirements:

h = rel.dnf_hazard([2022, 2023, 2024, 2025])     # events / car-laps at risk, by race phase
rel.hazard_to_p(h, 57)                           # 1 - prod(1 - h_L) over a 57-lap race
DNF hazard per car-lap, Jolpica 2022-25: lap 1 0.02080, laps 2-10 0.00219, middle 0.00180, final 10 0.00234, all 0.00229
  events {'lap 1': 38, 'laps 2-10': 35, 'middle': 122, 'final 10': 38}; starters 1827; observed DNF share 0.128; implied P(DNF) over 57 laps 0.123

DNF hazard per car-lap, Jolpica 2026: lap 1 0.00662, laps 2-10 0.00401, middle 0.00313, final 10 0.00318, all 0.00335
  events {'lap 1': 3, 'laps 2-10': 16, 'middle': 52, 'final 10': 12}; starters 453; observed DNF share 0.183; implied P(DNF) over 57 laps 0.174

The hazard view tells a story the season totals hide. In 2026 lap 1 became safer (0.0066 against 0.0208 per car) while every later phase became riskier: the rise from 12.8 % to 18.3 % DNFs is a reliability story, not a first-corner story. The conversion back to a race probability (0.174 against the observed 0.183) is a useful self-check on any hazard table.

📐 Definition: hazard to probability. With per-lap hazards h₁ … h_N, the chance of at least one event is 1 − Π(1 − h_L). For a constant small h this is ≈ 1 − e^(−hN), the Poisson link above.

Chapter 36 used the ratio of two hazards: incidents on wet laps against dry laps, 2.38 (1.30–4.34). With 12 wet-lap incidents the interval is wide, which is pitfall P4 in miniature.


E.9 Survival analysis: Kaplan–Meier

When. You care about when an event happens and some units never experience it during observation. A car that finishes was not "immune to failure": it survived this race distance. That is a censored observation, and simply dropping it or counting it as a non-event over-simplifies.

📐 Definition: Kaplan–Meier estimator. At each distinct event time tᵢ, with dᵢ events and nᵢ units still at risk just before tᵢ,

$$\hat S(t) = \prod_{t_i \le t}\Big(1 - \frac{d_i}{n_i}\Big).$$

Censored units leave the risk set at their censoring time without counting as events.

reliability.survival_curve measures time as the fraction of race distance completed. A retirement is an event at (laps completed + 0.5)/winner's laps; finishers and lapped cars are censored at full distance.

== E.9 Survival: Kaplan-Meier curves for reaching the flag
2022-25: starters 1827, DNFs 233 (0.128); S(25 %) 0.955  S(50 %) 0.929  S(75 %) 0.901  S(100 %) 0.872
  median retirement point 0.45 of race distance; share of DNFs before half distance 0.55
2026: starters 453, DNFs 83 (0.183); S(25 %) 0.945  S(50 %) 0.907  S(75 %) 0.859  S(100 %) 0.817
  median retirement point 0.50 of race distance; share of DNFs before half distance 0.49

Here every car is observed for the whole race, so S(100 %) equals one minus the DNF share. Kaplan–Meier earns its place when exposure differs: comparing races of different lengths, a car that was disqualified or withdrawn, or a season still in progress (2026 is "after 21 of 23 rounds"). The curves make the hazard story visible: the 2026 curve separates from the 2022–25 curve gradually through the race, not at the start. The DNF definition matters here: it uses Jolpica's status-derived finished flag, never is_classified, which is True for cars that retired after completing 90 % of the distance (see Chapter 26).


E.10 Change points and multiple testing

Binary segmentation with a permutation test

"When did McLaren's 2023 car get faster?" is a change-point question. Chapter 24's development.change_points scans every split k of a season's gap series and picks the one that maximises the between-segment sum of squares,

$$S(k) = \frac{k(n-k)}{n}\big(\bar y_{1..k} - \bar y_{k+1..n}\big)^2,$$

then compares the maximum against the maxima of 999 shuffled series. Taking the maximum over all splits is what makes the permutation essential: even pure noise has a best split, and a t-test on it would be badly over-confident.

Many seasons, many tests

Run that test on 41 team-seasons and some will fire by chance. The family-wise view (Bonferroni: test each at α/m) protects against any false alarm, and is very strict. The Benjamini–Hochberg procedure controls the false discovery rate instead: the expected share of false alarms among the results you keep.

📐 Definition: Benjamini–Hochberg at FDR q. Sort the m p-values p₍₁₎ ≤ … ≤ p₍ₘ₎. Find the largest k with p₍ₖ₎ ≤ (k/m) q, and keep the k smallest. In words: the bar rises with rank, so a cluster of small p-values can survive together where Bonferroni would reject each one alone.

p = dev._perm_p(yv, 4, s_, 999, np.random.default_rng(42))     # first-split p for every team-season
fs["bh_crit"] = 0.05 * np.arange(1, m + 1) / m                 # after sorting p ascending
== E.10 Change points and multiple testing (Benjamini-Hochberg)
Team-seasons 2023-2026 (dry rounds, circuit-adjusted gap to fastest team): 41
First-split permutation p < 0.05: 10  (expected by chance: 2.1)
Bonferroni (p < 0.00122): 0   Benjamini-Hochberg at FDR 5 %: 0
Smallest attainable permutation p with 999 shuffles: 0.0010; BH bar for the smallest p: 0.00122
 year     team_ref  n  round     p  shift  bh_crit
 2025       sauber 22     13 0.002 -0.804   0.0012
 2026 aston_martin 20     16 0.004 -1.219   0.0024
 2023      mclaren 19      7 0.013 -0.962   0.0037
 2024       alpine 20     19 0.021 -0.783   0.0049
 2025         haas 22     12 0.030 -0.770   0.0061
 2024 aston_martin 20      6 0.033  0.711   0.0073
 2026       alpine 20     13 0.036 -0.761   0.0085
 2023   alphatauri 19     14 0.036 -0.681   0.0098
P(>= 10 of 41 below 0.05 if no team ever changed) = 0.0000 (binomial; assumes independence)

This output holds two lessons that pull in opposite directions, and Chapter 24 reported both:

  1. No single change point survives correction. McLaren 2023 (p = 0.013), the most famous mid-season turnaround of the era, would need p ≤ 0.0037 at its rank. The individual timings are not established.
  2. The family as a whole is far from null. Ten of 41 below 0.05 where 2.1 are expected is very unlikely under "nobody ever changed". Teams do develop; the noise (median residual SD 0.458 percentage points per race in Chapter 24) is too large to pin down when for any one of them.

Note the mechanical detail in the fourth line. With 999 shuffles, the smallest p-value a permutation test can return is 0.001, and the BH bar for the top-ranked test is 0.05/41 = 0.00122. Sauber 2025 at 0.002 misses by one shuffle's worth. If you plan to correct for m tests, run enough permutations that 1/(B + 1) sits well below q/m.

Chapter 24 also computed the power of the test: with 20 races and a mid-season step, a shift of 0.5 percentage points is detected only 49.7 % of the time, and a 1.0-point shift 95 %. Many real upgrades are smaller than the detection limit. "No change point found" is not "no upgrade".


E.11 Rank correlation and split-half reliability

Spearman correlation

Spearman's ρ is the Pearson correlation of the ranks. It measures monotone association, ignores the spacing of values, and can't be hijacked by one extreme point. It is the natural statistic for orders: grid against finish, one weekend's pace order against the next.

== E.11 Rank correlation and split-half reliability
Grid vs finish Spearman per race (finishers who started from the grid), 2023-2026 R21: n = 91 races
  median 0.811, IQR 0.681-0.885; by season 2023 0.71, 2024 0.86, 2025 0.82, 2026 0.81
  Pearson on the same races: median 0.808

On positions, Spearman and Pearson agree because positions are ranks. Chapter 10 used this per-race ρ as a circuit "order-keeping" measure (Suzuka 0.93 to Las Vegas 0.45). They diverge on raw times, where one car that spins or one corrupt timing value moves Pearson and barely touches Spearman.

Split-half reliability: is it a trait?

Before ranking drivers on any metric (start gains, consistency, braking style), ask whether the metric measures something stable. Split each driver's data in two independent halves (odd and even rounds), compute the metric on each, and correlate the halves across drivers. Then correct for the halving with the Spearman–Brown formula: reliability of the full data = 2r/(1 + r).

sh = d.assign(half=np.where(d["round"] % 2 == 1, "odd", "even")).groupby(["driver_ref", "half"]).above.mean().unstack()
r_sh = sh["odd"].corr(sh["even"]); sb = 2 * r_sh / (1 + r_sh)
Start rating split-half (odd vs even rounds, 2014-2026, drivers with >= 60 starts): 27 drivers
  r = 0.598 -> Spearman-Brown full-length reliability 2r/(1+r) = 0.748; Spearman of halves 0.567

Over a career, start ability is a real trait (reliability 0.75). Over a single season it is mostly noise, which is the subject of E.12. The book's split-half results are a ladder from trait to noise:

Metric Split-half r Chapter
Brake-on share of lap time (teammates) 0.77 23
Lap-time gap itself (teammates) 0.72 23
Partial-throttle share 0.64 23
Start rating, career (Spearman–Brown 0.75) 0.60 17
Brake point before the apex 0.27 23
Wet qualifying gap (Spearman) 0.27 21
Tyre management (teammate slope difference) 0.16 9

A "tyre whisperer" ranking built on a metric with split-half 0.16 is a ranking of luck.


E.12 Shrinkage and empirical Bayes

When. You have many units (drivers, teams, circuits), each measured with noise of known size, and you want each unit's best estimate. The raw estimate for a unit with few observations is too extreme in both directions, because the noise adds spread. Shrinkage pulls each estimate towards the group mean, by an amount that depends on how noisy it is.

📐 Definition: normal–normal empirical Bayes. Unit i has raw estimate xᵢ with sampling variance sᵢ² = σ²/nᵢ. Estimate the mean μ and the true between-unit variance τ² = var(x) − mean(sᵢ²). Then

$$\hat\theta_i = \mu + w_i(x_i - \mu), \qquad w_i = \frac{\tau^2}{\tau^2 + s_i^2}.$$

In words: trust a unit's own data in proportion to the share of its spread that is real.

Chapter 17 applied this to season start ratings: lap-1 places gained minus the average for that grid slot and era.

sigma2 = d.groupby(["driver_ref", "year"]).above.var().mean()   # variance of a single start
S["s2"] = sigma2 / S.n
tau2 = max(S.x.var() - S.s2.mean(), 0.0)
S["w"] = tau2 / (tau2 + S.s2); S["shrunk"] = mu + S.w * (S.x - mu)
== E.12 Shrinkage (empirical Bayes) and the regression-to-the-mean trap
Driver-season start ratings 2014-2026 (>= 10 starts): 266; single-start variance 6.84
  mu -0.010; observed var 0.657 = true var tau^2 0.309 + mean sampling var 0.348
  weight on a 21-start season w = 0.49
  predict season t+1 with zero            : RMSE 0.769  (n = 198 pairs)
  predict season t+1 with raw season t    : RMSE 0.909  (n = 198 pairs)
  predict season t+1 with shrunk season t : RMSE 0.751  (n = 198 pairs)
  slope of next season on this season 0.27 (1 = perfectly persistent, 0 = pure noise)
  top-20 raw seasons: mean +1.289 -> next season +0.201 (shrunk forecast +0.590)
  bottom-20 raw seasons: mean -1.240 -> next season -0.264 (shrunk forecast -0.592)
  2026, top three raw -> shrunk: leclerc +1.176 -> +0.568; sainz +1.140 -> +0.550; arvid_lindblad +1.105 -> +0.520

More than half the spread of season start ratings is sampling noise (0.348 of 0.657), so a full season earns a weight of only 0.49. The raw rating is a worse predictor of next season than predicting zero for everyone (RMSE 0.909 against 0.769); the shrunk rating is the best of the three. Leclerc's 2026 rating of +1.18 places per start becomes +0.57 after shrinkage.

The top-20 line is the warning behind pitfall P5: even the shrunk forecast (+0.59) overestimates what the best seasons did next (+0.20). The normal–normal model assumes a driver's true ability is fixed across seasons; the fitted slope of 0.27 says it isn't (cars, team-mates and grid positions change), so a second layer of shrinkage across seasons is justified. Shrinkage is a floor on caution, not a ceiling.

The same idea in other forms:

2026 team DNF rates, beta-binomial shrinkage (prior a 1.78, b 7.94):
    team_ref  starts  dnfs   raw  ci_low  ci_high  shrunk
          rb      41     3 0.073   0.025    0.194   0.094
    mercedes      42     4 0.095   0.038    0.221   0.112
     ferrari      42     4 0.095   0.038    0.221   0.112
        audi      40     4 0.100   0.040    0.231   0.116
     mclaren      39     4 0.103   0.041    0.236   0.119
      alpine      42     5 0.119   0.052    0.250   0.131
    red_bull      42     6 0.143   0.067    0.278   0.150
        haas      42     7 0.167   0.083    0.306   0.170
    williams      40     9 0.225   0.123    0.375   0.217
    cadillac      41    16 0.390   0.257    0.543   0.351
aston_martin      42    21 0.500   0.355    0.645   0.440

For rates, the conjugate prior is a beta distribution: shrunk = (k + a)/(n + a + b), here a prior worth about 9.7 starts. Aston Martin's 50 % remains the worst after shrinkage, but at 44 %. Chapter 34 shrinks slow-stop rates the same way (prior worth 40 stops: Cadillac's 38.5 % → 21.7 %), and Chapter 20 shrinks the dirty-air penalty of circuits seen only once (Madring, 1 race: 1.359 → 1.135 s/lap).


E.13 Scoring probability forecasts: Brier, log loss and calibration

A forecast of "Norris 40 %" can't be right or wrong on one race. It can only be scored over many races.

📐 Definitions. For a binary outcome y ∈ {0, 1} and forecast p: - Brier score = mean of (p − y)². 0 is perfect; always saying 0.5 scores 0.25. - Log loss = −mean of [y log p + (1 − y) log(1 − p)]. Always saying 0.5 scores log 2 = 0.693. It punishes confident mistakes without limit: one p = 0.001 on an event that happens costs 6.9. - Calibration (reliability): among forecasts near p, the event should happen about p of the time.

For a race with 20 runners, the book's version of log loss is −log p(winner), with probabilities normalised to sum to one within the race.

Both scores are proper: you minimise them only by reporting your true belief. Accuracy ("did the favourite win?") is not, and it ignores everything a probability says except its argmax.

The teammate Elo of Chapter 21 is a clean example because every duel is predicted before the result is used to update the ratings:

== E.13 Calibration, Brier score and log loss
Elo from teammate qualifying duels, scored on duels from 2006 (each duel predicted BEFORE it is used):
  K =  8: n = 4310, log loss 0.6371, Brier 0.2232
  K = 16: n = 4310, log loss 0.6239, Brier 0.2173
  K = 32: n = 4310, log loss 0.6176, Brier 0.2144
  K = 64: n = 4310, log loss 0.6261, Brier 0.2172
  coin flip: log loss 0.6931, Brier 0.2500
  K = 32 reliability (favourite's probability):
                 n  mean_pred  observed
bin                                    
(0.499, 0.6]  1313      0.550     0.542
(0.6, 0.7]    1204      0.651     0.646
(0.7, 0.8]    1126      0.747     0.718
(0.8, 1.0]     667      0.857     0.826
  favourite won 0.661 of duels
  Brier of always saying 'favourite wins with p = 0.661': 0.2241

Three readings. K = 32 is best on both scores, so it is the K the book uses. The reliability table shows slight overconfidence at the top: favourites given 86 % won 83 %. And the improvement over a constant forecast (0.2144 against 0.2241) looks small in absolute terms; that is normal. Most F1 outcomes are close to unpredictable, and real skill shows up in the third decimal.

Chapter 26 reports the same pattern for race winners: gradient boosting improves log loss over the grid-slot baseline (1.304 vs 1.439, walk-forward over 273 GPs), yet it doesn't pick the winner more often than "pole wins" (54.9 % vs 55.7 %). A model can be better calibrated without being more accurate, and for betting (Chapter 38) calibration is what pays. Always pair a score with a paired bootstrap over races of the score difference: Chapter 26's GBM-minus-grid log loss was −0.135 [−0.251, −0.025].


E.14 Time-respecting validation and leakage

A model that will predict next Sunday must be tested the way it will be used: trained on the past, scored on the future. Walk-forward validation trains on seasons before Y, predicts season Y, and moves on. Random cross-validation over rows lets the model train on 2025 to predict 2023.

Leakage is any feature that carries information from after the moment of prediction. The classic F1 leaks are the end-of-season championship position, a centred rolling average (which reaches two races into the future), a "team pace this season" computed over the whole season, and anything using the race result to define the race's own feature.

ds = history.driver_standings(list(range(2006, 2027)), final=True)   # final rank: known only in December
r["lfr"] = np.log(r.final_rank)
walk(["lg"]); random_cv(["lg"]); walk(["lg", "lfr"]); random_cv(["lg", "lfr"])
== E.14 Time-respecting validation and leakage
Winner log loss per race, test seasons 2014-2026 (273 GPs; lower is better). Uniform pick: 3.004
  walk-forward, grid only:                 1.429
  random 5-fold over rows, grid only:      1.434
  walk-forward, grid + FINAL season rank:  1.175   <- leak: the rank is known only in December
  random 5-fold, grid + final season rank: 1.168

Two findings, both matching Chapter 26:

  1. Random CV is almost harmless here (1.434 vs 1.429). With a simple model and a stable relationship (grid predicts wins in every era), there's little for the future to teach the past.
  2. A leaky feature is devastating, and walk-forward does not protect you from it. The final season rank cuts log loss by 0.25, nearly twice the honest gain of Chapter 26's gradient-boosting model over the grid baseline (0.135). Chapter 26 measured the same effect on its gradient-boosting model: leaky features faked about 46 % of the model's honest gain over the grid baseline.

Walk-forward protects against training on future rows. It cannot protect against future information smuggled into the features of past rows. The defence is a rule for every feature: could I have computed this value before the session in question started? Chapter 24's centred smoother is fine for describing a season and a leak as a predictor, and Chapter 26 flags exactly that.

Other places the book applies the principle: Chapter 11 calibrates the lap simulator on alternate rounds and scores it on the others (median |error| 1.66 s out of sample vs 1.16 s in sample); Chapter 16 validates its cut-line forecast leave-one-season-out; Chapter 22 fits its degradation model on earlier races only, and found that hindsight doesn't rescue the pit-stop call (median error 5 laps with hindsight vs 4 pre-race).


E.15 Monte Carlo with common random numbers

A strategy simulator draws random safety cars, retirements, lap-time noise and lap-1 shuffles, then compares strategies by their average outcome. The precision of that average is ordinary statistics: the standard error of a mean of N runs is SD/√N. For a difference between strategies A and B,

$$\mathrm{Var}(\bar A - \bar B) = \frac{\mathrm{Var}(A) + \mathrm{Var}(B) - 2\,\mathrm{Cov}(A,B)}{N}.$$

With independent random streams, the covariance is zero. With common random numbers (CRN), both strategies face the same safety-car timeline and the same lap noise in each run, so the covariance is large and positive and most of the noise cancels.

🧪 Illustrative model: a deliberately simple single-car race (57 laps; degradation 0.051 s/lap; green pit loss 22.512 s; SC pit loss 12.722 s; full-SC hazard 0.0115 per lap lasting 4 laps; lap noise SD 0.288 s). The inputs are the book's measured base rates, but the model leaves out traffic, compounds and fresh-tyre steps. It exists to show the variance arithmetic, not to call a strategy.

rng = np.random.default_rng(42); m1, e1 = draw(rng, n); m2, e2 = draw(rng, n)
ind = race_times(two, m2, e2) - race_times(one, m1, e1)      # independent streams
rng = np.random.default_rng(42); m, e = draw(rng, n)
crn = race_times(two, m, e) - race_times(one, m, e)          # same SC timeline, same noise
== E.15 Monte Carlo with common random numbers
Clean-race difference two-stop minus one-stop: +8.691 s
  n =  1000: independent mean +8.435 s, SE 0.147 | CRN mean +8.221 s, SE 0.117 | variance ratio 1.6x | P(two-stop faster) CRN 0.091
  n = 10000: independent mean +8.334 s, SE 0.046 | CRN mean +8.202 s, SE 0.036 | variance ratio 1.7x | P(two-stop faster) CRN 0.088
  similar plans (stop lap 31 vs lap 28), n = 10000: independent mean +0.286 s, SE 0.042 | CRN mean +0.327 s, SE 0.0246 | variance ratio 3x
  runs needed for SE 0.1 s on the difference: CRN 1262, independent 2089

In this toy, CRN cuts the variance of the difference by 1.6–3×. The gain is modest because most of the remaining variance comes from whether a planned stop happens to fall under a safety car, which differs between plans even with shared timelines; the lap noise, by contrast, cancels completely. How much CRN buys depends on how much of the randomness the plans share. In the engine of Chapter 27, CRN reduced the variance of a strategy comparison 1,572-fold (paired SE 0.084 against 3.314 independent).

Four habits from Chapter 27 are worth copying:

  • Report the Monte Carlo SE with every simulated number, and choose N to make it small relative to the differences you care about. Chapter 27 needed about 10,406 runs to pin a two-stop/one-stop difference to ±0.25 s.
  • Compare plans on CRN, always. It's free.
  • Separate the two kinds of uncertainty. The SE says how well N runs estimate the model's average. It says nothing about whether the model's inputs (hazard, degradation, pit loss) are right. For those, run a sensitivity sweep or a tornado chart; in Chapter 27 the degradation multiplier moved the answer more than anything else.
  • Validate the engine against outcomes with the scores of E.13 before trusting its probabilities.

E.16 Identification limits: fuel burn vs track evolution

Some questions can't be answered by any amount of the data you have, because two causes move together perfectly. That is an identification problem, and it should be checked before estimating anything.

Over a race, three things change lap time: the fuel load falls (the car gets faster), the track rubbers in (faster) and the tyres wear (slower). Within one stint, tyre age and lap number rise together one-for-one. Fuel load is a linear function of lap number, and track evolution is roughly linear in lap number too.

== E.16 Identification limits: fuel burn vs track evolution
2025 Mexico City GP clean laps: corr(lap number, tyre age) within a stint, median 1.0000; within a driver's whole race, median 0.311
design [1, lap_number, fuel_kg, tyre_age]: rank 3 of 4 columns -> fuel load (linear in lap) and track evolution (linear in lap) cannot both be estimated
corr(lap_number, fuel_kg) = -1.000000
what the data CAN estimate: fuel + evolution slope -0.0450 s/lap [-0.0485, -0.0416] -> 0.0320 s/kg at an ASSUMED 100 kg over 71 laps (upper bound on the pure fuel effect)
drivers with >= 2 stints (the ones that identify the lap slope): 18 of 19

Read it as a chain of what is and isn't knowable:

  1. Tyre wear vs the lap trend: identified, but only across stints. Within a stint the correlation is exactly 1, so a single stint can't separate them. A pit stop resets tyre age while the lap number keeps rising; that break is what identifies the lap slope. Only drivers with two or more stints contribute.
  2. Fuel vs track evolution: not identified. Both are linear in lap number; the design matrix loses a rank. The data give their sum, −0.045 s/lap at Mexico City. Turning that into "seconds per kg" needs an assumed start fuel (no FIA limit is sourced for 2022–25), and the result is an upper bound, since part of the slope is the track.

Chapter 20 proved the point by simulation: on synthetic races with known fuel and evolution effects, the estimator recovered their sum almost exactly (−0.0677 vs −0.0676 true), and its interval covered the pure fuel effect in 0 % of runs. A second, independent estimator (matched tyre ages across consecutive stints, −0.0558) agreed with the regression, which is evidence about the sum, not about the split. Other identification limits in the book: Chapter 3's attempt to fit power and drag area together from straight-line acceleration gave nonsense (1,556 kW, a negative CdA) because 1/v and v² were correlated at −0.990 over the available speeds; Chapter 5 found the sign of a load-sensitivity term flipped with an assumed reference speed.

⚠️ Common pitfall: a precise estimate of an unidentified quantity. The interval on the fuel slope is narrow ([−0.0485, −0.0416]). Narrow is not the same as meaningful. The interval describes the sum of two effects; no amount of precision says how to split it. When you see a narrow interval, ask what variation in the data is producing it.


E.17 Pitfalls from the book's own analyses

Each of these cost a chapter time or nearly put a wrong number in print. They are specific to F1 data, and each one will happen to you.

P1. Raw lap times hide degradation

The car gets lighter every lap. On raw lap times, that improvement cancels most of the tyre wear, and the slope of lap time on tyre age looks flat.

== E.P1 Pitfall: raw lap times hide degradation
2025 dry races, stints with >= 8 usable laps: median slope raw vs fuel-corrected (100 kg x 0.03 s/kg ASSUMED)
            n  raw_median  fc_median  raw_pos  fc_pos
compound                                             
HARD      329     -0.0174     0.0335   0.3708  0.8237
MEDIUM    390      0.0015     0.0487   0.5231  0.8231
SOFT      138      0.0266     0.0715   0.6957  0.8841

On raw times, the median HARD stint gets faster with age, and only half of MEDIUM stints show any wear. After the assumed correction, 82–88 % of stints degrade. Over all 76 dry races 2023–26, Chapter 22 found raw medians of 0.018 / 0.003 / −0.002 s/lap (SOFT / MEDIUM / HARD) against 0.064 / 0.051 / 0.048 corrected. The correction is 77–109 % of the corrected value: the degradation number is mostly the fuel assumption. Every degradation figure must say which correction it uses (E.5, E.16).

P2. The overtakes table is not a list of overtakes

OpenF1's overtakes records every change of position the timing system logs, including pit-stop cycles, safety-car reshuffles, cars slowing to retire and loop-to-loop flicker.

== E.P2 Pitfall: the overtakes table is not a list of overtakes
2026 Las Vegas Grand Prix: raw records 361, green on-track 180 (49.9%); green on-track 180, lap 1 58, under SC/VSC/red 46, flicker (reversed <=10 s) 31, mass change (>=4 for one car in a lap) 22, pit in/out lap 20, retiring car 4
2025 Mexico City Grand Prix: raw records 320, green on-track 54 (16.9%); pit in/out lap 120, lap 1 103, green on-track 54, flicker (reversed <=10 s) 36, retiring car 7
2024 Italian Grand Prix: raw records 225, green on-track 42 (18.7%); pit in/out lap 149, green on-track 42, lap 1 21, flicker (reversed <=10 s) 12, retiring car 1

Across 2023–26, about 16 % of records are green-flag on-track passes (an average of about 40 per race), so the raw table overstates passing about six-fold. Worse, the share varies by race, from 17 % at Mexico City to 50 % at the 2026 Las Vegas GP, so the raw count isn't even a consistent proxy for comparing races or seasons. Use the book's filter (overtaking.classify_passes; Chapter 35), and note that it still includes passes on damaged cars.

P3. Distance alignment manufactures time

Telemetry distance is integrated from speed, so two laps' distances drift apart. Rescaling both to the same length with one factor (the toolkit's default delta_time) puts the drift error into slow corners, where a few metres are a lot of time.

== E.P3 Pitfall: distance alignment manufactures time
2025 Japanese GP Q, NOR vs VER,  uniform alignment: final +0.012 s, min -0.258 s at 2900 m, max +0.110 s
2025 Japanese GP Q, NOR vs VER,  sectors alignment: final +0.012 s, min -0.175 s at 2890 m, max +0.121 s

Both traces end at the true 0.012 s, but uniform rescaling invents an extra 0.08 s of Norris advantage at the hairpin. Chapter 7 found the statistical version of the same artefact: with uniform rescaling, the second-placed qualifier appeared to brake later than the pole-sitter in 47 of 64 resolved stops (73 %), a "finding" that vanished on the location-based track line (pole-sitter later 11 of 31, 35.5 % [21.1, 53.1]). Align on sector lines or the x/y track line, and treat telemetry differences under about 0.05 s or 20 m as noise (Chapter 19).

P4. Small-n wet races

== E.P4 Pitfall: small-n wet races
GPs with any INTERMEDIATE/WET lap, 2023-2026 R21: 11/91 = 0.121 [0.069, 0.204]
clean INTERMEDIATE laps per wet GP: median 254, races with >= 100: 8
  a rate of 1/5: 0.20, Wilson [0.04, 0.62]
  a rate of 3/9: 0.33, Wilson [0.12, 0.65]

There are thousands of wet laps but only 11 wet races, and each race's conditions are unique. The effective n for any wet question is the number of races, and often the number of races with the specific transition you care about. The book's wet numbers carry that weakness openly:

  • the wet pit loss for a fresh set of intermediates is 25.20 s [14.03, 46.54] from 5 stops (Chapter 15);
  • the driver-noise multiplier in the wet (×1.66) rests on four races (Chapter 9);
  • wet-skill rankings disagree between races and qualifying (Spearman −0.07), and split-half reliability of wet qualifying gaps is 0.27 (Chapter 21).

Report the race count with every wet number, use Wilson intervals on the race-level rates, and prefer a permutation or sign-flip test over the laps (E.4) to anything that treats laps as independent.

P5. The regression-to-the-mean trap in start ratings

Rank drivers by one season of lap-1 gains and the top of the list is mostly the drivers whose noise happened to be positive. Next season they "decline". E.12 shows the numbers: the 20 best raw seasons averaged +1.29 places per start, and the same drivers managed +0.20 the following year. Nothing happened to them; the first number was inflated by luck. The same trap waits in every season ranking: error rates (Chapter 9, position-adjusted year-to-year correlation 0.01–0.39), pit-crew slow-stop rates (Chapter 34), team DNF rates. The defence is E.11 before ranking (is it a trait?) and E.12 when you rank (shrink first).

P6. "Best of Q1–Q3" is not like-for-like

A team's best qualifying time is set in Q3 if its car got there, but in Q1 if it was knocked out. The track is faster by Q3 (track evolution, Chapter 16) and the cars run lower fuel and newer tyres. Measuring every team's best against the fastest team's best therefore penalises the teams that went out early.

== E.P6 Pitfall: 'best of Q1-Q3' is not like-for-like
Median (best-of-Q1-Q3 gap - Q1-only gap) to the fastest team, percentage points, dry rounds,
by the deepest session the team's faster car reached:
deepest     Q1     Q2     Q3
year                        
2023     0.988  0.763  0.065
2024     0.867  0.642  0.149
2025     0.794  0.559  0.117
2026     1.299  0.904  0.071
team-rounds: 830

A team eliminated in Q1 looks about 0.8–1.3 percentage points slower on the "best" measure than on a like-for-like Q1 comparison. That is roughly a second on a 90 s lap, invented by the format. Worse, the bias is correlated with the thing you're measuring: slow teams are the ones knocked out early, so the "best" measure stretches the field. Chapter 24 uses best-of for headline 2023–26 gaps (with this caveat) and like-for-like Q1 for history, and Chapter 28 shows how far apart the two can be: Audi's 2026 gap is 0.78 % on Q1 and 1.54 % on best-of. Say which one you use.


E.18 A checklist before you publish a number

  1. What is the independent unit? Laps, stints, races or seasons. Resample it, permute it, cluster on it (E.3, E.4, E.5).
  2. What is n, in that unit? Print it beside the estimate.
  3. Is there an interval? Wilson for rates, bootstrap for medians and anything awkward, a robust standard error for regression slopes.
  4. Is the bootstrap median near the point estimate? If not, check what the resampling changed (E.3.3).
  5. How many things did you test? Correct for it, and make sure your permutation count lets a correction succeed (E.10).
  6. Is the metric a trait? Split-half before ranking; shrink before publishing a ranking (E.11, E.12).
  7. Is the effect identified? Which variation in the data produces it? Could two causes be moving in lock-step (E.16)?
  8. Which definitions and assumptions are baked in? Fuel correction, best-of vs Q1, the overtakes filter, the DNF flag, the alignment method (E.17).
  9. If it is a forecast: was it scored on the future, and could every feature have been known at the time? (E.13, E.14).
  10. If it is a simulation: what is the Monte Carlo SE, and which input moves the answer most? (E.15).

None of these steps needs more than a few lines of code. The numbers that survived them are the ones in print.


Further reading

  • Bell, Smith, Sabel & Jones (2016), "Formula for success: Multilevel modelling of Formula One Driver and Constructor performance, 1950–2014", Journal of Quantitative Analysis in Sports: the random-effects approach to driver vs car that E.6 simplifies.
  • van Kesteren & Bergkamp (2023), "Bayesian analysis of Formula One race results: disentangling driver skill and constructor advantage", JQAS: the fully Bayesian version of the shrinkage in E.6 and E.12.
  • Heilmeier et al. (2020), "Application of Monte Carlo Methods to Consider Probabilistic Effects in a Race Simulation for Circuit Motorsport", Applied Sciences: the race-simulation framework behind E.15.
  • Kelly (1956), "A New Interpretation of Information Rate", Bell System Technical Journal: why log loss is the score that matters when probabilities are used for staking (Chapter 38).