Coding Advice

This is the section that makes the artifact useful. Below is the actual winning train.py, byte-for-byte as committed at E0009 — the configuration that produced the decision track's best frontier value (27.584597) and became the incumbent for the sealed run — followed by what it does that matters, and the traps that actually fired in this study.

The winning train.py, verbatim



Annotated: seven things this file does that matter

  1. The mutable surface is a nine-line CONFIG block, and nothing else. MODE, CONVENTION, K, ESTIMATOR, FAMILY, TRIM. Every computation lives in analysis.py, the stable study library. That is what made E0003 possible: the fix that turned a guardrail-breaching discard into the track's only KEEP was one word — hazen → inverted_cdf — and the diff proves nothing else changed. If the convention had been buried in the estimator module, the same fix would have been an unfalsifiable multi-line edit.
  2. It refuses to run outside the harness. The missing check demands KLEIN_EVALUATION_KIND, KLEIN_EXPERIMENT_ID and KLEIN_TRACK from the environment and raises with the exact remedy (KLEIN_SMOKE=1 for a shape check) rather than defaulting. A train.py that “works” when run by hand is a train.py that will one day produce a number with no manifest behind it.
  3. Mode, track and metric name are cross-checked before any fitting. Two tracks mean two primary metric names, and klein run-one refuses a result whose printed metric name does not match the track being run. Rather than discover that after a run, analysis.MODE_TRACK[MODE] != TRACK raises immediately with a message naming both. This is cheap defensive code that pays for itself the first time you edit MODE and forget the --track flag.
  4. The sealed-mode guard is in the code, not in the discipline. sealed_repro and sealed_decision read pre-registered published truth and may only run under klein run-one --final-test. The file enforces both directions: a sealed mode without --final-test raises, and --final-test on an adaptive mode raises too (“--final-test spends a track's one sealed access”). A single sealed access per track is a contract you cannot un-spend, so the guard belongs where it cannot be forgotten.
  5. The data-identity anchor is re-verified on EVERY run, before any fitting. Twelve published quantities, checked in three lines — E0001's entire run, identity gate plus fit, took 2.2 ms. It is tempting to run this once in prepare.py and trust it thereafter. Don't: it is the only thing standing between this study and a silent substitution of extRemes::damage's genuinely-1925–95 top-30, which looks like the same dataset, is not, and would break every published comparison while raising no error. The gate is cheap; the failure it prevents is invisible.
  6. Guardrails are printed, not merely written. The runner reads guardrail values off the printed canonical block, so extra must carry every guardrail key of the running track with its measured value — analysis.check_extra asserts that before a mode may return, and wall_seconds is added here because this file is the only place that knows t0. This is study 05's lesson F1 imported as code: there, a metric that was written to aux_metrics.tsv but not printed cost a real experiment slot.
  7. The convention and the mode are recorded in extra on every run. "mode": MODE, "convention": CONVENTION — two strings that turn every ledger row into a self-describing record. When section 4's detective story needed to prove that E0002 and E0003 differed only in the convention, the evidence was already in aux_metrics.tsv; nobody had to reconstruct it from commit messages.

War stories — the traps that actually fired

Never form Σ★⁻¹ — factor and whiten

The textbook GLS formula invites you to compute . Do not. 's condition number runs to 2.7e4 for log-Cauchy across the reported trims (against about 35 for the normal member at k = 8, (0.05, 0.95)), and it grows sharply as ; on the r = 25 validation grid it is far worse still, since the standard Cauchy density at the 0.01 quantile is ≈3e−4. The mathematically identical, numerically safe route is Cholesky whitening:

L = cholesky(Sig, lower=True)
mu, sigma = lstsq(solve_tri(L, X), solve_tri(L, Y))[0]

# and the GoF statistic uses the SAME factor - a squared norm, again no inverse
r = Y - X @ [mu, sigma]
W = n / sigma**2 * (solve_tri(L, r) ** 2).sum()

And log the condition number on every fit. The study's estimator returns sigma_star_cond with each gQLS result, so the loop can see conditioning degrade rather than infer it from a bad answer. E0002 and E0003 both recorded sigma_star_cond_max = 27302.62 on the log-Cauchy family — identical across the two conventions, which is itself evidence that the convention change moved the data vector and not the covariance.

Make the code refuse what the mathematics refuses

log-Cauchy has no finite moments. In this implementation, mean_loss() and cte() raise NotImplementedError for such families rather than returning a number. The ledger carries the reason as a first-class aux metric on E0007:

moment_note: “log-Cauchy has NO finite moments: mean_loss() and cte() raise NotImplementedError by design, so this family can only ever be priced through QUANTILES — any mean/CTE/TVaR number for it is a truncation artifact.”

This is the cheapest control in the study and the one most likely to matter in production. A numerical quadrature would have returned a large float that is an artefact of where it was truncated, and it would have looked exactly like an estimate. The refusal fires at the moment of misuse and converts a silent pricing error into a stack trace. Note the corollary: a moment-based robust estimator (trimmed or Winsorized moments) has nothing to trim on a family with no moments — which is precisely the gap the quantile grid fills.

Export both conventions under different names, so they can never be confused

This study needs two quantile conventions for two different jobs, and mixing them up costs a guardrail breach. The implementation exports them as separately named constants — SUMMARY_QUANTILE_METHOD (Hazen, for the descriptive identity gate) and THESIS_QUANTILE_METHOD (inverted_cdf, for the estimators) — and takes method= everywhere, so a pre-registered convention sweep is still possible. One further wrinkle is exposed as quantile_space=: the thesis writes (quantile the dollars, then log), which is identical to quantiling the log-dollars under order-statistic conventions but not under interpolating ones.

A guardrail that fails while the metric passes is a signal, not a nuisance

E0001 produced parameters inside the reporting resolution and was discarded on a max_abs_w_deviation of 0.4940. The temptation in that moment is to widen the guardrail, because the headline number looked fine. The correct reading is that W is a quadratic form in the residuals and therefore far more sensitive to the exact grid than a two-parameter regression line through it — so the insensitive quantity passing while the sensitive one fails localizes the bug to the grid. That single discard is what sent the study back to Chapter 2's definition and produced its only reproduction KEEP.

Predict the disposition in the candidate description

Every candidate description in this study's ledger states the expected metric and the expected disposition before the run: E0002's says “predicted mean ~0.0093 with max_abs_param_deviation ~0.032 BREACHING the 0.02 guardrail … discard predicted”. Two benefits, both real. A prediction that lands makes the discard informative rather than disappointing — E0002 was a deliberate measurement of a convention, not a failed attempt. And a prediction that misses is caught immediately, while the reasoning is still in your head rather than three phases later.

Five transferable rules

  1. Pin the quantile convention AND k in any filing, paper, or model document whose parameters come from a quantile-based fit — and reproduce the source's descriptive table first to find out which convention it used. A gQLS specification is five things — (family, a, b, k, quantile convention) — and the last two are usually left to a library default. At n = 30 the convention alone moves a fitted parameter by up to 0.1040 and k by up to 0.1223: 20.8× and 24.5× the 0.005 reporting resolution. Swapping hazen for inverted_cdf is the whole difference between a discard at 0.009303 with a breached guardrail and a keep at 0.002754. (C7)
  2. Price a moment-free fit through quantiles only — and make the code refuse the rest. The best-fitting family on this data has no finite mean. An actuary who follows the goodness-of-fit test into a TVaR-loaded premium gets a confident number with no meaning; the NotImplementedError is the control. (C8)
  3. Treat the trim as the robustness knob, price it explicitly, and buy it before you need it. Moving from (0.05, 0.95) to (0.10, 0.90) cut 1-in-100 instability from 41.33 to 27.58 and raised the in-sample GoF from W p 0.5153 to 0.7310. The knob has a directly readable meaning: is the number of corrupted records you are buying protection against — 5% of 30 events is 1.5, so one bad record is tolerated and two are not; 10% tolerates three. Because the breakdown point is a guarantee with a cliff, not a slope, widen the trim while the sample is still clean; past the cliff there is no partial credit. And check the cost on your data: the classical efficiency argument says a wider trim must cost fit, and here it did not. (C9)
  4. State family-conditionality next to every return level, and anchor it to the empirical support. With n = 30 the largest observation sits at plotting position p = 0.9667 ≈ 1-in-30, so every 1-in-100 here is parametric extrapolation. The numbers make the point better than the caveat does: on the same data and the same estimator the 1-in-100 is $53.04bn (gQLS-lognormal 0.05/0.95), $56.66bn (gQLS-lognormal 0.10/0.90), $55.52bn (MLE-lognormal) and $4.08e7bn (gQLS log-Cauchy). All four pass the in-sample GoF test; three sit below the largest event actually observed and one sits five orders of magnitude above any loss in recorded history. Report the GoF-passing families side by side with the empirical 1-in-30 anchor, never a single number as “the” answer. (C10)
  5. When your “held-out” evidence is published targets rather than held-out data, say exactly that in the claim, not in a footnote. This study's sealed evidence is unusually strong on one axis — 120 third-party parameters fixed in print before the study existed, unmovable by anything the study does — and structurally blind on another: the same 30 observations underlie both evaluations, so sampling error is fully common-mode. The permitted claim is “our implementation reproduces their published numbers on their sample, and the estimator is robust within that sample”. The forbidden claim is any statement about generalization to another hurricane sample, another period, or predictive accuracy. Carry the wording verbatim into slides and verdict cards, where it is most likely to erode. (C11)

What the implementation cost

About 970 lines of numpy/scipy (estimators.py 802 + stress.py 171) covering six standard members, oQLS + gQLS + MLE, both goodness-of-fit tests and the B = 1000 parametric bootstrap, backed by 20/20 tests in 0.69 s. The mathematical core is about fifteen lines: grid → design matrix → known Σ★ → Cholesky-whitened least squares. There is no released R or Python package for gQLS — adoption means owning the code and its tests. Budget for the tests that pin your Σ★ specifically, because a wrong Σ★ fails silently and only the o2-versus-g2 split catches it.