QQuant, Built

Act IV · Return Premia (P)

Part 26 of 43

Backtesting Without Fooling Yourself

Undergraduatestarts at this level62 min of film 19 chaptersprerequisites: Part 6, Part 25

You tested ten thousand trading rules and the best one has a Sharpe ratio of two. What have you learned?

Almost nothing, and the part shows exactly how little. Three leaks make a backtest lie: using information that was not yet known, using only the firms that survived, and choosing the best of many. The first two are fixed by engineering, a point-in-time store and an event-driven backtester that cannot see the future. The third is statistics: the Sharpe ratio's own error, the expected maximum of many trials, the deflated Sharpe ratio, purged cross-validation, reality checks. A market with planted alpha, where the truth is known, shows which procedures find it and which find noise.

What you need. Parts 6 and 25.

What you will be able to do

Undergraduate

  • Name look-ahead, survivorship and selection bias and give an example of each.
  • Compute a Sharpe ratio's standard error and the years needed to trust it.

Master's

  • Compute the expected best Sharpe ratio of N skill-less trials and the deflated Sharpe ratio of a result.
  • Run purged, embargoed cross-validation and a walk-forward test; estimate the probability of backtest overfitting.

PhD

  • Do inference on the winner: White's reality check, Hansen's SPA, Romano-Wolf, and the conditional approach of Andrews, Kitagawa and McCloskey.

Industry

  • Write a backtest protocol: what is registered before the hold-out is opened, how trials are counted, how a live strategy is monitored.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 20 min · Master's 49 min · PhD 62 min · Industry 27 min.

  1. 0Ten thousand rulesUndergraduate3 min
  2. 1Look-ahead and point in timeUndergraduate3 min
  3. 2SurvivorshipUndergraduate2 min
  4. 3Selection: the best of manyUndergraduate3 min
  5. 4The event-driven backtesterMaster's4 min
  6. 5The Sharpe ratio's errorUndergraduate3 min
  7. 6The trial counter and the hurdleMaster's3 min
  8. 7Technical rules that weren'tMaster's3 min
  9. 8The deflated Sharpe ratioMaster's3 min
  10. 9The probability of backtest overfittingMaster's3 min
  11. 10Purged cross-validation and walk-forwardMaster's4 min
  12. 11Reality checksPhD3 min
  13. 12Monitoring live strategies with e-valuesPhD3 min
  14. 13Planted alphaMaster's3 min
  15. 14How a strategy gets capitalIndustry3 min
  16. 15Registration and evaluation accountingIndustry2 min
  17. 16Rule 26: the backtest protocolIndustry3 min
  18. For the researcher: inference on the winnerPhD6 min
  19. Recap, desk questions, problemsAll tracks4 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Reading · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.

Ten thousand rulesUndergraduate3 min

Backtesting without fooling yourself: how a strategy's history is simulated, and the dozen ways that simulation lies.

The original experiment samples technical-rule configurations and selects on the daily US market through 1986. Its winner has earlier Sharpe . The chart compounds gross excess-cash returns under the library's lag assumptions, without calibrated costs. The later research window runs from 1987 through 2020. The same rule has later Sharpe , ranking . The decline alone cannot prove clean data, executable prices, absence of overfitting or a unique causal story. This lecture separates those questions and examines what each diagnostic can establish.

A strong selected backtest raises several concrete questions. Were inputs available at the decision time? Are missing firms and abandoned strategies represented? How many choices were explored? Could the assumed orders have filled? Were costs and corporate actions handled? How uncertain is the estimate? Did validation leak? Did the economic setting change? We inspect original calculations where the frozen inputs verify. Two unavailable historical originals are withheld and replaced with explicitly fixed arithmetic illustrations. The sealed strategy experiment stays unopened.

The doubt is old. In 1933 Alfred Cowles asked whether stock market forecasters could forecast, and found that they could not. Sidney Alexander's filter rules in 1961, and Eugene Fama and Marshall Blume's test of them in 1966, made trading rules a subject of statistics; in 1992 William Brock, Josef Lakonishok and Blake LeBaron found that simple rules had worked on ninety years of the Dow. Then the corrections: survivorship, found in fund databases in 1992; missing delisting returns in 1997; and in 1999 Ryan Sullivan, Allan Timmermann and Halbert White asked whether Brock's rules were the best of a much larger universe, using White's new reality check. Andrew Lo gave the Sharpe ratio a standard error in 2002. The modern toolkit came after 2010, much of it from David Bailey and Marcos Lopez de Prado: the deflated Sharpe ratio, the probability of backtest overfitting, purged cross-validation, and in 2019 a written protocol for backtesting from Robert Arnott, Campbell Harvey and Harry Markowitz.

The plan: diagnose look-ahead, survivorship and selection in the original examples; inspect an event-driven engine with specified fill and cost assumptions; qualify the Sharpe standard error and mean-based selection hurdle; distinguish DSR scores and CSCV rank frequencies from exact guarantees; and audit validation leakage and bootstrap inference. Retrospective clipped monitoring paths and simulated capital ramps illustrate mechanisms with explicit limitations. Registration and evaluation remain conceptual: no sealed experiment is opened or scored, and no substitute historical test is created.

In the House, this part builds the backtester itself, which the research desk and the data team share, and the statistics that keep it honest. From now on no strategy in the series is believed because of its backtest alone. It is believed, a little, because of what its backtest survived.

1Look-ahead and point in timeUndergraduate3 min

Look-ahead: a backtest that knew something its trader could not have known. Plant a timing error deliberately in the moving-average rule. A position determined with today's close can earn only a return starting after that information is available. With the original lag convention, the two-hundred-day rule has Sharpe during 1990 to 2020. Market buy-and-hold is . Letting that position earn the already-observed same-day return raises its ratio to . The five-day version reaches . This isolates a planted index error in a gross calculation; the lagged result is still not a fully implemented tradable strategy.

Look-ahead enters in four common ways. The same bar: the bug we just planted, or its milder cousin, trading at the very close a signal was computed from, which a real order can only approximate. The period instead of the release: a company's earnings for the year to December are filed in February or March; a quarter's GDP appears a month after the quarter ends. A database that stamps them by period hands them to the backtest early. The revision: today's database holds today's best estimate of the past, which is not what anyone saw at the time. And the whole sample: a z-score scaled by the full sample's mean, a parameter fitted on all the data, a universe chosen by what exists at the end. Each quietly leaks the future into every date.

The public Philadelphia archive preserves revisions to 2008 quarter-four growth. In the first finite monthly vintage the annualised estimate is percent. The saved path changes as later vintages arrive and ends at percent in December 2020. A monthly vintage is useful availability information, but it is not an exact release timestamp or a full intraday replay. The reader also accesses later published archive bytes before selecting its research window; that is separate from opening a sealed strategy experiment.

The saved comparison contains quarters from 1966 through 2019. First finite vintages and December 2020 estimates differ by an average absolute percentage points. percent change sign; their correlation is . Revisions need not bias every strategy in the same direction. An available-time replay must use release dates, vintage definitions and realistic execution timing.

A period date can be mistaken for an availability date. A quarter labelled October first was not fully known on that day. Merging revised quarterly data by the period can leak both later observations and revisions. In this original monthly-vintage illustration, the lagged-vintage timing ratio is , versus for the naive period merge. It is not a timestamp-complete real-time trading replay. A plausible-looking difference can still come from unavailable information. Neither its small size nor a visually reasonable chart validates the protocol.

Pause and predict. A value signal divides each company's book equity by its price, from a database of annual reports keyed by fiscal year end. What would you change, and in which direction does the bias run?

2SurvivorshipUndergraduate2 min

A database can exclude closed funds, failed companies or abandoned strategies. We study the mechanism with fixed arithmetic. The original SEC snapshot comparison is unavailable because its recorded data hash does not match; no replacement historical result is generated.

Here are four explicitly fabricated one-year outcomes: minus twenty, minus ten, plus ten and plus twenty percent. Their equally weighted arithmetic mean is zero. Now impose a reporting filter that retains only the two nonnegative outcomes. The reported mean becomes fifteen percent. Nothing about the four outcomes improved. Conditioning changed the group that appears in the report. This example is fixed arithmetic, not a market simulation, strategy backtest or estimate of an actual fund population.

The general lesson is conditional sampling. The return distribution among included records can differ from the distribution in the target population. The direction and size of that difference depend on the inclusion rule. Positive survivorship bias is not a universal identity. Fund closures, mergers, voluntary reporting, backfill and abandoned strategies can create different filters. Brown and coauthors studied fund survivorship in 1992. A historical universe must be defined using information available at the relevant date, with exits and identifier changes retained.

Exits also require return accounting. For compatible sequential intervals, compound a regular return and an exit return. In a fixed example, plus ten percent followed by minus fifty percent gives minus forty-five percent. Simply adding the two would give the wrong result. Provider definitions matter: do not omit an exit payment or count the same interval twice. A missing delisting return is not automatically zero. Shumway and later Shumway with Warther document why exit records matter; no delisting-return dataset is reconstructed here.

The original SEC example remains blocked. Its public ticker snapshot fails the recorded-source hash check. The computation and error are preserved, and its unavailable numbers are withheld. The manifest is unchanged. Even with matching bytes, membership in a later ticker file would not be a literal corporate-survival rate. Public-float frames and bankruptcy-report searches select particular reporting universes. Define the historical universe clock, retain exits and closed records, and document backfill, identifiers and return definitions before estimating performance.

Pause and predict. Four fixed outcomes average zero percent, while the selected retained pair averages fifteen percent. Does the higher reported mean establish manager skill? State the target population and identify the selection rule before interpreting the difference.

3Selection: the best of manyUndergraduate3 min

Selection: what the best of many strategies looks like when none of them works.

Start with independent zero-skill estimates over five years of daily returns. The saved simulation draws Student t Sharpe statistics, with T minus one degrees of freedom; the normal maximum is an approximation to this experiment. The best of ten averages . The best of one hundred averages , and one thousand . With ten thousand it averages . Only the search breadth changes. These are simulated selection effects, with no trading edge and no claim that real strategy estimates are independent.

Why does it slide, and how fast? Take N independent standard normal draws. The largest is below c only if every one is, so the probability is Phi of c to the power N. The maximum is typically near the level that one draw in N exceeds. Extreme-value theory makes this precise: the maximum of normals converges to a Gumbel distribution, and its mean sits a fraction gamma, Euler's constant, of the way from the one-in-N level to the one-in-N-e level. It grows like the square root of two log N: slowly, but without limit. Sharpe ratio estimates of strategies with no skill are close to normal, with variance V, about one over the number of periods. Scale by the square root of V, and this is the hurdle: the Sharpe ratio the best of N should reach by luck alone.

Compare the normal extreme-value approximation with the saved Student t simulations. Dots are simulated means; thin lines are the fifth to ninety-fifth percentiles of the selected estimate, not confidence intervals for a true strategy. At one million independent estimates, the approximation reaches over five years. This extrapolation depends on the noise model. Search breadth is essential context for an impressive selected backtest.

The point has been made as a joke. In 1995 David Leinweber, then at the asset manager First Quadrant, searched a United Nations database of economic series for the best predictor of the S and P five hundred's annual return, as a warning to his colleagues. The winner was butter production in Bangladesh, which explained three quarters of the variation. Adding American cheese production and the sheep populations of Bangladesh and the United States explained ninety-nine percent. Leinweber published it in 2007 as 'Stupid Data Miner Tricks'. Every search finds its butter. The question is only whether you can tell.

Where does N come from in practice? The parameter sweep: a lookback from ten to two hundred and fifty days, a threshold, a holding period. A grid of a few hundred cells is N in the hundreds, even if only the best cell is shown. The quiet choices: the start date, the universe, the rebalancing day, the treatment of outliers, the cost model. The colleagues: ten analysts each testing ten ideas and reporting their best give the firm an N of a hundred, though its report shows ten. And the literature itself, the zoo of Part twenty-five, which is a selection from everyone's tries.

Pause and predict. You sweep four hundred parameter settings of one idea on ten years of daily data, and the best has a Sharpe ratio of one point two. Is it better than noise, and what else would you need to know?

4The event-driven backtesterMaster's4 min

The original Yahoo-based calculation is unavailable because its recorded data hash does not match. We use fixed invented quotes and accounting identities to explain the mechanism, without generating another historical backtest.

Three invented quotes make the timing issue visible. The first close is one hundred, and the signal is computed after observing it. Suppose the next available modelled fill is the following open at one hundred and two. The next close is one hundred and one. Buying one share at the assumed open loses one dollar before costs. A calculation that instead fills at the already observed close would show a one-dollar gain. Neither path is a historical strategy result. The difference illustrates why the order clock and fill assumption must be stated.

Keep a ledger on a stated capital base. Start with one thousand dollars and buy one share at one hundred and two, with an illustrative fee of twenty cents. Cash falls by one hundred and two dollars and twenty cents. Marking that share at one hundred and one leaves portfolio value nine hundred and ninety-eight dollars and eighty cents. The return on the stated starting capital is minus point one two percent. The fee is a declared arithmetic assumption, not a calibrated market cost. Changing the capital denominator changes the reported return.

Event ordering reduces one class of mistakes. Match observations, decisions, orders, fills, corporate actions and marks to their own timestamps. Cost inputs must also be available at the fill time. An open-or-close fill model is not an order-book replay. Spread, commissions, impact, borrow, funding and capacity require assumptions or measurements; a touched price does not reveal queue priority or a guaranteed fill. Restricting the callback to past bars is useful, but it cannot stop future information embedded in revised data, leaked preprocessing, selected parameters or external code.

Corporate actions must preserve the accounting. In a fixed four-for-one split, one share priced at one hundred becomes four shares priced at twenty-five. Value stays one hundred. Treating the price reduction alone as a return would create an artificial seventy-five-percent loss. Share counts, pending orders and per-share fields must use consistent conventions. This is fabricated split arithmetic, not an Apple event study or a new market calculation.

A dividend creates a cash flow as well as a price observation. In a fixed example, a share starts at one hundred, ends at ninety-eight and pays two in cash. Total return is zero before fees and taxes. Real ex-dividend prices can move for many other reasons. Account for payments to a long and equivalent-payment obligations on a short, using the provider's price-adjustment convention. No SPY dividend history or historical return is substituted here.

The House source remains unchanged. These exact excerpts show the original event loop and the lagged volatility and participation inputs used by its fill-cost routine. They are code excerpts, not empirical evidence that a fill was executable or a cost model calibrated. The existing pure numerical tests check the library on synthetic inputs; this review does not change the algorithm or run another historical strategy.

The original Yahoo calculation remains blocked at its EEM data-integrity check. Its algorithm, public input and failure evidence are preserved. We have not refreshed the manifest, displayed unavailable Sharpe ratios, or generated a replacement historical strategy. The fixed quotes and corporate-action examples explain the accounting separately.

Pause and predict. After the invented close of one hundred is observed, one share fills next open at one hundred and two, is marked at one hundred and one, and incurs the illustrative twenty-cent fee. On one thousand dollars of starting capital, explain the cash ledger and the minus point one two percent return. Which fill assumption would change the sign before costs?

5The Sharpe ratio's errorUndergraduate3 min

The Sharpe ratio is an estimate, and estimates have errors. Take an explicitly simulated strategy with true annual Sharpe ratio one half and independent Gaussian monthly returns. In the saved twenty thousand five-year histories, the estimated ratio has standard deviation . percent have a negative estimated ratio. This illustrates low precision; it does not say that every five-year record is incapable of rejecting zero. Serial dependence and a search over strategies would require further treatment.

Where the spread comes from. The Sharpe ratio, per period, is the estimated mean divided by the estimated volatility. For independent normal returns the mean's error has variance sigma squared over T, and the volatility's about sigma squared over two T. The delta method combines them: the variance of the estimate is one over T, times one plus half the Sharpe ratio squared. The one is the mean's error and dominates for ordinary Sharpe ratios; Andrew Lo published this in 2002. Drop the normal assumption, as Thomas Mertens did the same year, and skewness and kurtosis enter. Negative skew and fat tails widen the error, so the strategies that sell insurance, whose returns are exactly like that, are the ones measured worst.

Turn it around: how long must a track record be? For the estimate to be two standard errors from zero, the Sharpe ratio times the square root of the number of years must exceed two, so the years needed are about four over the Sharpe ratio squared. A Sharpe ratio of one half needs sixteen years. One needs four. Two needs one. The equity premium itself, at about point four or point five, takes a working lifetime to see clearly, which is why Part six needed a century of data for it.

Two historical summaries, using the original public data. The US market has years of monthly observations, Sharpe ratio , IID standard error , and moment-adjusted error . The put-writing index has months, ratio , skewness and kurtosis . Its standard error changes from to . These are asymptotic estimates under independent-return assumptions. Neither formula handles serial dependence, guarantees tail estimation accuracy or certifies future performance.

Smoothing can also distort naive annualisation. This original Gaussian illustration reports a weighted mixture of current and lagged returns, as a simple stale-mark mechanism. For stationary arithmetic-sum moments, the scaling factor depends on all relevant autocorrelations. Positive weighted autocorrelation lowers that factor relative to square-root scaling. This is not an identity for compounded returns. In the saved simulation the naive annual ratio is , the Lo-adjusted ratio , and the original generating ratio . The naive ratio exceeds the adjusted one by percent. These results do not prove the same mechanism or magnitude for any particular historical fund.

Pause and predict. A manager shows you three years of monthly returns, a Sharpe ratio of two, and a first-order autocorrelation of point four. What is a fair range for the true annual Sharpe ratio?

6The trial counter and the hurdleMaster's3 min

The trial counter: the number every backtest in this series has been keeping, and the hurdle it implies.

The protected registry records strategies and their declared search counts. A registration includes code metadata, parameters and the number of configurations declared by the registering routine. A hash makes later changes detectable; it does not prevent a researcher from changing code or omitting trials. The count is a lower bound on documented research choices, not a complete audit of every informal idea. This review reads existing metadata and creates no registration or market trial.

The restored counter snapshot attributes configurations to Part three, to Part six, and to Part twenty-five. Its pre-Part-twenty-six total is . These are the saved registered counts, including choices from earlier work. The existing registry already includes the ten thousand Part twenty-six rules. The review neither adds them again nor opens the sealed experiment.

Interpret the count through an explicit hypothetical model. For independent zero-mean normal estimates over years, the extreme-value approximation gives this expected maximum. At estimates, it is . At , it is . These are mean noise benchmarks, not rejection thresholds. Real correlated, adaptive searches need additional assumptions; an unregistered choice does not disappear from the statistical problem.

Read the same approximation backwards. Under the independent normal noise model, the typical null maximum shrinks with the square root of the record length. Equating its approximate mean to a target Sharpe ratio gives a backtest-length heuristic. It specifies neither confidence nor detection power. The saved calculation allows about independent configurations over five years before the mean null maximum reaches one. This is a planning benchmark, not proof that a selected strategy clears a statistical test.

Two qualifications matter. Nearly identical rules carry less distinct information than independent ones. Counting them as independent can exaggerate a normal-noise benchmark. A correlation-based participation ratio is a useful sensitivity measure, but it does not identify a universal number of independent searches or correct arbitrary adaptive research. The registry also omits undocumented ideas and abandoned choices. Dependence and missing trials are separate uncertainties; neither turns a registered total into an exact inferential adjustment.

Pause and predict. A team has tried about two thousand correlated variations of one idea, which they estimate amount to a hundred independent tries. Their best has a Sharpe ratio of one over eight years. Does it clear the hurdle?

7Technical rules that weren'tMaster's3 min

Ten thousand technical-rule configurations inspired by the rule families studied by Brock, Lakonishok and LeBaron, and Sullivan, Timmermann and White. This is a House illustration, not an exact replication.

The four families, as Brock, Lakonishok and LeBaron and then Sullivan, Timmermann and White defined them. Moving averages: long when the price, or a short average of it, is above a long average. Filters: long after the price rises some percent from its last low, short after it falls that percent from its last high. Support and resistance: long when the price closes above the highest close of the last n days, short below the lowest. And channel breakouts: the same, but only after the price has traded in a narrow range. Each comes with variants: a band around the trigger, a delay before acting, a fixed holding period.

The implementation samples parameter configurations from four technical-rule families with a fixed seed. Many configurations are strongly correlated; this is not ten thousand independent experiments or an exact reconstruction of a published grid. Positions earn the next daily excess-cash return, before implementation costs. Selection uses data through 1986, followed by a descriptive 1987 to 2020 comparison. Cash and market buy-and-hold are distinct benchmarks.

The saved research eras differ sharply. Before 1987, of configurations exceed the market's Sharpe ratio. During 1987 to 2020, do. The earlier winner changes from to . These gross long-short excess-cash calculations do not establish market alpha, executable stale-price profits or a causal explanation of the decline.

Each saved dot represents a rule, with earlier and later Sharpe ratios. The full set's cross-era correlation is ; rankings are far from stable. The earlier winner ranks in the later era. The later sample is now public research data. Repeatedly studying it prevents treating it as a fresh untouched performance test.

The table selects the best earlier configuration within each family. It reports that selected rule's earlier and later ratios, alongside family averages. The later outcomes are descriptive gross returns, with neither calibrated execution costs nor a causal correction. Short-horizon trend rules are prominent among these earlier winners. That pattern motivates checking return timing, nonsynchronous prices and implementation, rather than declaring a universal source of alpha.

The saved decade summaries show changing daily autocorrelation. Nonsynchronous trading is one plausible mechanism: stocks with stale recorded prices can make an aggregate index adjust gradually. Fisher discussed this in 1966, and Lo and MacKinlay studied nonsynchronous trading in 1990. A historical index return is not automatically an executable index trade. Costs, market structure, economic change and selection may also matter. This chart does not identify how much each mechanism caused the decline, or prove that the early rules were free of overfitting.

Pause and predict. The best rule's in-sample t-statistic is above thirteen, so no correction for ten thousand tries can explain it away. Which of this part's checks, if any, could have warned you before 1987?

8The deflated Sharpe ratioMaster's3 min

The deflated Sharpe ratio: one number that accounts for the selection, the length of the backtest, and the shape of its returns.

Combine the approximate sampling variance with a selection benchmark. The formula assumes an asymptotically normal Sharpe estimate with suitable moments; it does not automatically account for serial dependence. PSR is a normal-reference confidence score against a fixed benchmark. It is not a posterior probability that the strategy is true. The expected maximum formula approximates an independent-normal null maximum, scaled by a chosen variance. Substituting the observed cross-rule spread and an effective trial count adds assumptions. DSR is PSR against that fitted hurdle. A score above point nine five is a convention, not an exact selection-adjusted type-I guarantee or a forecast certificate.

The effective-count input is a heuristic. The participation ratio of correlation eigenvalues measures concentration. The original implementation estimates correlations on fifteen hundred sampled rule returns, then scales the ratio to the full grid. It reports and for the two eras. These are not identified counts of independent search paths. The annualised spread of rule Sharpe estimates is and . Using that spread also changes the noise benchmark. The resulting score remains an approximate sensitivity calculation.

The saved summaries place the selected ratios next to their effective-count benchmarks. Before 1987, the selected ratio is , versus hurdle . In the later research era, the winner selected within that era has ratio , versus . Selecting a new winner on the later window is different from testing the earlier winner. Clearing either mean hurdle is not a calibrated selection-adjusted rejection or a guarantee of future returns.

Read the saved numbers as diagnostics, not probabilities that strategies are true. The earlier winner's raw-count and effective-count scores are and . Rounding near one proves neither absence of selection bias nor an unimportant search. For the later winner, PSR against zero is ; DSR is using the raw count and using the effective proxy. Interpretation depends on normal-moment approximations, trial spread, dependence and the search model. Neither a high nor low fitted score establishes future profitability or exactly zero skill.

Vary the assumed trial count while keeping this fitted diagnostic's other inputs fixed. The saved winner's score crosses point nine five at an interpolated count near . A high score at small N and a lower score at large N show sensitivity to the search model. They do not establish that a strategy is true or false at a precise number of trials. The participation-ratio count, moments, dependence and incomplete research history all remain uncertain.

Pause and predict. Two strategies each show a Sharpe ratio of one and a half over six years. One was the only idea its author tested; the other the best of five hundred. The first has skewness of minus two, the second of zero. Rank them.

9The probability of backtest overfittingMaster's3 min

The probability of backtest overfitting: how often the configuration chosen in sample turns out worse than the median out of sample.

Bailey, Borwein, Lopez de Prado and Zhu proposed combinatorially symmetric cross-validation. Take the matrix of every configuration's returns, day by day, and cut time into sixteen blocks. Choose eight blocks as the in-sample set, and leave the other eight out. Find the configuration with the best in-sample Sharpe ratio. Then find where it ranks among all of them in the eight blocks it never saw. And repeat for every one of the twelve thousand eight hundred and seventy ways to choose eight blocks of sixteen. Each split is symmetric, half and half, and every block is in sample exactly as often as out.

Summarise each combinatorial split by a relative rank. The implementation uses a half-tie rank and an offset to keep the rank fraction inside zero and one. Its logit is positive above the later half-sample median. The reported PBO is the fraction of splits whose selected rule is at or below that median. The splits overlap heavily; the fraction is not a probability calibrated for a future trading failure. Even a value of zero neither guarantees the top rank in every split nor rules out overfitting.

Apply CSCV separately to each research era. The earlier fraction at or below the complementary median is ; logits lie outside the saved minus-eight to eight histogram window. The large omitted positive tail explains the sparse earlier plot. The later PBO is , with logits outside that window. These omitted observations are counted explicitly rather than silently clipped into bins. The full split frequency remains a descriptive, dependent half-sample diagnostic.

Here are eight hundred saved split pairs from each era, displayed without clipping their returns. In the earlier era the mean selected ratio is in selection blocks and in the complementary blocks. In the later era the corresponding means are and ; percent have a negative complementary ratio. These are descriptive half-sample diagnostics, not independent prospective tests or a decomposition of the source of the decline.

Be precise about the scope. Strong early half-sample rankings indicate stability within that archive and rule grid. They do not prove absence of overfitting, point-in-time data quality or tradeability. Stale recorded prices are a possible implementation concern; the split diagnostic alone cannot identify that mechanism or predict a market-structure change. Use independent economic reasoning, available-time inputs, realistic fills and costs, and a fresh evaluation protocol. Statistical selection diagnostics answer only part of that problem.

Pause and predict. CSCV gives your family of strategies a probability of overfitting of only five percent on 2000 to 2020, but nearly all of them share one feature: they buy after big down days. What would you test next?

10Purged cross-validation and walk-forwardMaster's4 min

Cross-validation, the machine learner's standard tool, and the two ways it leaks on financial time series.

Financial labels overlap. A model that forecasts the next twenty days' return makes one observation a day: its features from the past, its label from the twenty days ahead. Neighbouring observations share almost all of their label: the day before shares nineteen of its twenty days. Shuffle the observations into random folds, as ordinary cross-validation does, and nearly every test day has its neighbours in the training set, with almost the same features and almost the same answer. The model does not need to forecast. It only needs to remember yesterday.

The unchanged nearest-neighbour experiment is useful because its limitations can be traced. It uses one-, five-, twenty- and sixty-day log returns and recent volatility. But it standardises every feature once using the full sample, before any split. That leaks scaling information into all the saved validation results. The target is the next twenty trading days' log return, so adjacent labels overlap. Predictions average twenty-five nearby training labels. R squared compares with the training mean, while hit rate classifies above or below the training label median. These are diagnostic scores, not certified real-time forecast estimates.

The original saved scores differ across validation schemes. Shuffling reports R squared percent and hit rate percent. Adjacent overlapping labels can make that comparison optimistic. Blocked, purged and walk-forward R squared are , and percent. These differences do not identify a causal effect or prove all forecasting impossible. Full-sample scaling remains in every score. Blocked and purged folds use future observations, and walk-forward retains labels that mature inside its test period.

Contiguous folds still leak at their edges, and Marcos Lopez de Prado's fix has two parts. Purge: remove from training every observation whose label period overlaps the test fold's, so no training answer contains a test day. Embargo: also remove a gap after the test fold. Its length must reflect the information carried by labels and features, not just one convenient horizon. This code uses a twenty-day embargo but features look back sixty days. Purging does not repair full-sample preprocessing or turn future-fold training into a historical deployment simulation.

A walk-forward design fits on earlier observations and tests later ones. A real replay must also wait for training labels to mature, fit scaling only on the available training data, and keep model choices separate from the final evaluation. The saved implementation splits feature timestamps chronologically but leaves overlapping twenty-day training labels at the test boundary. Its negative score is an illustrative original result with residual leakage. Chronology alone neither removes those leaks nor guarantees performance through a future regime change.

Read these scores with their remaining leaks in view. The five-fold purged calculation drops an average training observations per fold, and the twenty-fold version . Small score differences here do not establish that leakage is unimportant. All methods use full-sample scaling; the blocked and purged designs can train on future observations. Purging removes specified overlapping label intervals. A suitable gap also depends on feature lookbacks, label maturity and the evaluation target. For a future trading forecast use a chronological, available-time protocol. Random splitting can answer a different exchangeable-sample question, but it does not validate that live forecasting claim.

Pause and predict. A credit model labels each firm-year by whether the firm defaults within three years, and is validated with five random folds of firm-years. Where is the leak, and what is the fix?

11Reality checksPhD3 min

Halbert White's reality check for data snooping, and the two tests that improved on it.

White's idea, in 2000, was to test the right null hypothesis. For each of N rules, take its return over a benchmark, day by day. After a search, the question is not whether one rule has an edge, but whether any of the N does; the null is that the best of them has none. The natural statistic is the best rule's average, scaled by the square root of T. Its distribution under the null depends on how all N rules move together, which no formula knows, so White bootstrapped it.

The bootstrap has to respect two kinds of dependence. Through time: returns cluster, and some of these rules depend on autocorrelation, so resampling single days would destroy what is being tested. Dimitris Politis and Joseph Romano's stationary bootstrap resamples blocks of random length, here ten days on average, from random starting points. And across rules: every rule is resampled on the same days, so their correlation is kept. Each resample gives every rule a new average, and the best of them, recentred, is one draw of the statistic under the null.

In symbols. On each resample b, every rule gets a new average. For ten thousand rules this is one matrix product, the resample's day counts times the returns. Subtract each rule's own sample mean, which imposes the null by setting every edge to zero, and take the best. The p-value is how often that best-of-N luck matches the real best. Five hundred resamples, as Sullivan, Timmermann and White used.

The original reality check uses five hundred stationary-bootstrap draws. The earlier bootstrap exceedance fraction is ; zero means zero out of five hundred, not zero true probability. This random rule universe and market series are not an exact replication of the cited Dow study. The later fraction is . Nonrejection does not prove all rules useless or establish equivalence. Stationarity, moment and resampling assumptions, the original studentisation choices and Monte Carlo uncertainty all limit interpretation.

Two refinements motivate the next diagnostics. Hansen's superior predictive ability approach studentises and reduces the influence of clearly inferior rules on the bootstrap null. Proper time-series inference needs suitable long-run variance and bootstrap regularity conditions. Romano and Wolf's step-down method repeatedly compares remaining statistics with bootstrap critical values. Familywise error control is an asymptotic result under appropriate assumptions, not an unconditional finite-sample promise. The unchanged House implementation uses sample standard deviations and five hundred resamples; its reported results are simplified approximations to those methods.

The original procedures yield different research-era diagnostics. Earlier RC and SPA exceedance fractions are and , while the saved step-down algorithm rejects rules. Model-based rejection does not identify individually true effects with certainty. Later RC and SPA fractions are and , with step-down rejections. These are gross returns relative to cash, not market-active performance. Sample-standard-deviation studentisers do not estimate serial long-run variance; finite-bootstrap results remain approximate, with no exact paper-replication or future-profit guarantee.

Pause and predict. You add five thousand deliberately terrible rules to the universe, each the mirror image of a good one. What happens to White's p-value, and to Hansen's?

12Monitoring live strategies with e-valuesPhD3 min

Betting monitors and retrospective diagnostics. We examine what the original paths show, and the stronger bounded-process assumptions needed for an anytime guarantee.

Repeated looks require a decision process. Reusing a nominal five-percent fixed-horizon test can inflate the chance of at least one false rejection. Its exact size depends on dependence between looks. Fix the claim, data, scaling, betting choices and error budget from available information. A fitted historical path does not automatically become a prospectively calibrated test. Testing by betting gives a useful theorem: a valid nonnegative supermartingale starting at one obeys Ville's bound. We must separately justify why its null holds for the financial increments.

The implementation and its necessary null must be distinguished. The original code clips the scaled shortfall between minus point nine nine and point nine nine. The target, scale and betting grid must be chosen from information already available. For the guarantee, the clipped increment must have conditional mean at most zero. A raw return mean above the target does not imply this after clipping. Under that bounded conditional null, every positive predictable bet is a nonnegative supermartingale; a fixed mixture starts at one. Ville bounds its chance of ever reaching twenty by five percent. Our retrospective raw-return examples do not verify this null, so their threshold counts remain diagnostics.

The original whole-panel calculations remain visible. These are published predictors with positive estimated in-sample means. The first row counts full-target diagnostic paths that ever cross twenty and the terminal e-BH rule's selections. The second row uses half the fitted target. The time summary is a difference of calendar years, among flagged cases, not a universal speed of evidence. Terminal e-BH can control expected false-discovery rate under any cross-predictor dependence if its inputs are valid e-values under their stated nulls. The fitted clipped paths here do not establish those premises for raw-return claims. Published-universe selection, revised histories and estimated targets remain material limitations.

Pause and predict. In a separate mathematical example, a valid e-process stands at twelve. A colleague wants to lower the threshold from twenty to ten. That cannot retain the original five-percent anytime bound. Ville gives a ten-percent bound at ten. Restarting monitors also requires justified claims and an overall error budget; it is not a source of free repeated five-percent tests.

13Planted alphaMaster's3 min

Testing the tests: plant real alpha in a simulated market, and see what each method finds, and what it invents.

Every check in this part can itself be checked, by running it where the truth is known. A simulated market of a thousand strategies, five years of daily returns, all sharing a common factor, as strategies on one market do. In ten of them the House plants a real edge, a Sharpe ratio of one, or in a second experiment of two; the other nine hundred and ninety have none. The methods are not told which are which. Forty markets of each kind.

This is the original saved single simulated market, sorted by its realised test statistics. Green marks the ten planted effects; their positions also reflect the realised shared factor. In this particular sample, strategies exceed the one-point-nine-six line. A planted positive mean need not produce a significant statistic in one realised market. The next table averages all forty simulated markets per edge rather than treating this selected picture as representative performance.

These are averages over fixed-seed simulated markets for each planted edge. With planted Sharpe one, the naive test finds real and false strategies on average. Bonferroni finds real and false; the step-down implementation finds real and false. At Sharpe two, their real discoveries rise to and . Zero observed false discoveries in that finite run does not imply zero population error. The selected-rule DSR proxy exceeds point nine five in and percent of markets. Those are simulation frequencies, not universal posterior probabilities or error guarantees.

This experiment illustrates a power tradeoff. The stricter procedures produce fewer false discoveries in the saved simulated markets. Their theoretical guarantees still require their own assumptions. At planted Sharpe one, power is low in this particular five-year search. That does not prove an information-theoretic impossibility for every method, prior or market. A narrower, well-motivated search can lower a multiplicity hurdle. Its benefit depends on dependence, signal strength and what information was used to choose the search.

Pause and predict. In the market with a planted Sharpe ratio of one, roughly how many years of data would Bonferroni need to find about half of the ten real strategies?

14How a strategy gets capitalIndustry3 min

What happens between a good backtest and real money. Firms that run many strategies describe a similar path from idea to capital. It begins with an idea and a reason the edge should exist, written down before the data are touched. Then a research review: is the protocol sound, are the data point in time, how many trials were run, what will it cost to trade. Then incubation: the strategy runs live, on data it has never seen, with no capital at all. Then a capital ramp: a small allocation, raised step by step while the live record holds up. Full allocation, sized for its capacity and for how it correlates with everything else. And finally monitoring, with a rule that can stop it, and a record that is kept after it dies. Marcos Lopez de Prado calls this the meta-strategy paradigm: research run as a production line, with a check at every station.

Why consider a capital ramp? Selecting the strongest fitted history can inflate reported performance. Counting trials documents the search but does not remove estimation error, and any correction depends on a model. Implementation costs also remain uncertain. Measure fills and costs at relevant sizes, and consider funding, borrow and capacity. A paper fill is not evidence that a real order would execute on those terms. A capital policy needs a precommitted economic target, exposure limits and retirement rules, with room for slow detection and model error. The next example illustrates one assumed policy rather than prescribing an allocation rule.

This is a fixed-seed Gaussian simulation, not a live strategy record. The assumed backtest Sharpe is one point five. One simulated strategy has true Sharpe one, and the other zero. Both violate the full-target null of at least one point five. Capital follows the specified paper period and quarterly arithmetic ramp, gated by a clipped e-process diagnostic with known simulation volatility. No execution costs or market capacity are modelled. The true-one strategy is stopped in percent of careers. That is not a false-alarm estimate under the full-target null. The true-zero strategy stops in percent, with median stop month among stopped careers. The result illustrates slow evidence accumulation and assumed capital exposure, not a calibrated operating policy.

Changing the target changes the hypothesis and detection frequency. Against the full backtest target, the simulated true-zero strategy stops in percent of careers. Against half the target it stops in percent. The true-one strategy exceeds the half-target mean of point seven five, but clipping still requires checking the bounded-increment null before invoking an e-process guarantee. Targets should follow a precommitted economic claim; this toy simulation does not dictate a firm's capital allocation.

Pause and predict. A strategy's capacity is estimated at two hundred million dollars, and its backtest Sharpe ratio is one point two after costs at fifty million. The ramp reaches a hundred and fifty million, and the live Sharpe ratio falls to point six. Overfitting, or something else?

15Registration and evaluation accountingIndustry2 min

This review preserves the original experiment code but excludes its cache, payload and score. We examine the conditions a fresh test would need.

A defensible test begins before its outcomes are inspected. Freeze the rule, its code hash, parameters, signal and execution timestamps, universe and publication vintages. Freeze trading, borrow and financing assumptions and the capital base. Freeze the evaluation window, benchmark, uncertainty calculation and stopping rule. Record every variant considered. A timestamp cannot make an already examined sample unseen.

The existing cumulative ledger through Part twenty-six contains registered trials. That is existing metadata, not a new registration by this review. This review adds no market trials, registrations, sealed openings or scores. A recorded count is a lower bound on the broader research search. Informal variants and adaptive decisions can matter even when no separate registration was made.

Five years can still be a noisy test. Under an independent, stable, modest-Sharpe approximation, the mean t-statistic is the annual Sharpe ratio times the square root of years. At five years, the rough standard error is point four five. A fixed illustrative Sharpe ratio of point four gives a t-statistic near point eight nine. These numbers are arithmetic examples, not a sealed outcome. Dependence, tails, selection and costs can change the conclusion. Nonrejection of zero does not establish equivalence or absence of an economic effect.

The boundary is explicit. Original experiment code is preserved but excluded. No experiment cache, payload, performance row or substitute historical strategy test is used. Public archive readers can retrieve later published observations before their historical cut; that does not certify a blind test. Pause and predict. A prespecified test has a t-statistic near point eight nine after five years. What does nonrejection establish, and what remains uncertain about costs, selection and future performance?

16Rule 26: the backtest protocolIndustry3 min

The House's twenty-sixth rule: the protocol every backtest must pass. The diagnostic sheet preserves the original numbers with their scope. A same-bar signal illustrates look-ahead. The original SEC and Yahoo calculations remain blocked by source hash mismatches. Their unavailable numerical outputs are withheld; fixed illustrations cover the conditioning and execution mechanisms. The selected rule is compared across the two research eras only. DSR, PBO and bootstrap fractions are qualified inference diagnostics. Every validation score retains some leakage, and the clipped monitoring paths do not certify raw-return error rates. The ledger reports existing registrations; this review adds none. The sealed experiment remains unopened and unscored.

The protocol is a set of checks, not a certificate produced by a software class. Write the economic claim, document search choices and available-time data, retain exits and inspect plausible execution and costs. Match validation to the target: fit preprocessing on available training data, wait for labels to mature, remove relevant overlap, and preserve a fresh evaluation sample. A chronological split alone does not prove those conditions. Complexity and robustness checks also count as research choices. A failed test is a result to record. No fitted diagnostic, timestamp or selected backtest replaces a defensible information clock and evaluation design.

The deflation is three short functions. The expected best of N, from the normal quantiles and Euler's constant. The benchmark it implies. And the probabilistic Sharpe ratio against that benchmark, with the skewness and kurtosis in the denominator. Six lines; the hard part is not the code but the honesty of the N that goes into it.

The tools this part adds to the House. The engine and the vectorised line it replaces; the Sharpe ratio's error; selection and its hurdle; overfitting and validation; data snooping, bootstrapped; and the rules and the planted market. And the twenty-sixth rule. No strategy is believed because of its backtest. A backtest counts only if it ran on point-in-time, survivorship-free data, through the event-driven engine with its costs and corporate actions, validated without shuffling, with its trials counted and its deflated Sharpe ratio and probability of overfitting reported with their assumptions. Capital ramps need implementation controls and a monitor with a justified process null; a clipped diagnostic alone does not certify the raw-return claim.

Apply the protocol to four cases. An impressive selected backtest prompts an audit of information availability, assumed fills, costs, research choices and uncertainty. No failure frequency is inferred from these examples. A long historical record needs point-in-time inputs, a documented universe and executable trading assumptions. A prediction model needs mature labels, training-only preprocessing and a split that matches its forecasting target; purging alone does not remove every leak. A slipping strategy needs a precommitted economic claim and a monitor whose actual conditional null is justified. Lowering a threshold cannot retain the original error bound. These are checks on evidence, not automatic certificates of truth or future performance.

For the researcher: inference on the winnerPhD6 min

For the researcher: Chapters 3 and 8 deflated the best backtest against a hurdle, and asked whether it beats noise. A sharper question: given that we picked it for being the best, what is an honest estimate of how good it really is, with an interval that covers? Isaiah Andrews, Toru Kitagawa and Adam McCloskey give exact results in a specified Gaussian model; the historical Sharpe application below is an approximation.

Start with a statistical model. Estimates are jointly Gaussian with known covariance, and we select the largest. The later Sharpe-ratio application only approximates that model. Selection can bias the chosen estimate upward. Nonnegative bias does not by itself imply that every selected interval strictly undercovers. With independent standard-normal null estimates, coverage of the selected symmetric interval is Phi of one point nine six to the number of estimates, minus the opposite-tail probability to that same power. With two it is about ninety-five percent; with fifty it is about twenty-eight percent.

Condition on the winner and suitable residuals. Subtract the covariance projection of the winning estimate. Joint Gaussianity makes the residual vector independent of that estimate when the covariance is known. Each rival imposes a scaled inequality. A positive coefficient gives a lower bound, a negative coefficient gives an upper bound, and a zero coefficient imposes a residual feasibility condition. In the equal-variance examples the upper bound is infinite. Conditional on a feasible winning event and the residuals, the estimate has a truncated normal distribution. Exact inversion gives exact conditional coverage in this model. Finite search brackets, a gridded hybrid and simulated critical values introduce numerical approximations; estimated Sharpe covariances add further uncertainty.

The theorem and its implementation have different precision. Under a known Gaussian model, the conditional distribution function falls as the candidate mean rises. Exact tail inversion defines conditional intervals and a median-unbiased estimator. The original numerical routine searches only sixty standard errors on either side of the observation and returns a boundary when no root is bracketed. A boundary is not an exact interval endpoint. The hybrid additionally uses a simultaneous projection event and an adjusted tail level. Its ideal coverage theorem requires a valid simultaneous critical value. Here the hybrid is approximated on eight hundred and one grid points, and the critical values are simulated or estimated. Neither numerical example is an exact historical coverage guarantee.

These saved known-Gaussian simulations use estimates, pairwise correlation , and worlds per row. With all means zero, naive coverage is percent; with one clear winner it is percent. Selection effects depend on the model and mean configuration. The table gives actual conditional and hybrid coverage frequencies, and median estimator bias. These are finite Monte Carlo results, with conditional root brackets and a gridded hybrid. The parenthesised quantities are median lengths. Simultaneous critical values were estimated from twenty thousand Gaussian draws. The ideal theorem does not turn those finite numerical frequencies into exact guarantees, and the hybrid need not be longer than naive in every sample.

This plot shows only candidate means from minus three to two for the 1987 to 2003 winner. Its gap above the fitted selection boundary is proxy standard errors. The naive curve crosses one half at . The conditional median root is . Crucially, its lower-tail root is not found within the finite bracket: the stored value is the sixty-standard-error solver floor, so the true model-based lower endpoint lies farther left. The gridded hybrid median is , with approximate grid bounds and . Estimated correlations and an IID Sharpe standard-error proxy add uncertainty beyond this numerical truncation.

Apply the unchanged plug-in calculation to the two saved rule searches. The 1926 to 1986 winner has ratio , a fitted gap of standard errors, and conditional roots and . Its later ratio is . The 1987 to 2003 winner has ratio , a gridded hybrid median , and later ratio . Its conditional lower endpoint is beyond the displayed solver floor. Common IID Sharpe errors, estimated return correlations and four hundred IID Gaussian multiplier draws make this historical analysis approximate. The later contrast identifies neither a unique causal explanation nor future performance.

Read the two historical examples cautiously. The earlier winner has a wide lead under the fitted common-error model, so that model makes little selection correction. Its later collapse does not identify a unique regime-change cause or eliminate other sources of bias. The later winner has many close rivals and receives a substantial conditional adjustment. Subsequent performance does not establish that selection explained all of its decline. These procedures concern a selected same-window mean under stated assumptions. Estimated correlations, an independent-return standard-error proxy and finite numerical search prevent an exact historical coverage claim or a forecast certificate.

Three research questions remain. Known Gaussian covariance is a strong assumption. Dependent, heavy-tailed or nonstationary returns need a justified limiting distribution, covariance estimation and finite-sample assessment; a large sample alone is not sufficient. Real adaptive searches involve a whole history of choices. Conditioning only on one maximum does not account for that full path. Finally, selection-adjusted inference for a past-window mean is different from prediction through structural change. A future-performance interval needs a credible model of that change as well as selection.

Pause and predict. Two uncorrelated rules, each with standard error point two. Their estimates are one and point nine eight. Is the winner's conditional interval wide or narrow? And if the estimates were one and point two?

Recap, desk questions, problemsAll tracks4 min

Part twenty-six in fourteen qualified lines. A same-bar signal demonstrates look-ahead, while economic data require actual publication clocks. The original SEC snapshot fails its source hash check, so its unavailable numerical comparison is withheld. Selection makes the best noise strategy look strong. The original Yahoo execution item is also blocked; fixed arithmetic explains fills and costs without another historical strategy. Sharpe standard errors require distribution and dependence assumptions. The recorded trial ledger is a lower bound on the broader research process. The selected technical rule is compared across two research eras without a sealed score.

DSR is an approximate confidence score, not a probability that a strategy is true. PBO counts below-median rank events inside overlapping historical splits. The original validation results retain scaling and boundary leakage. Bootstrap zero means no exceedance in five hundred draws, not zero true probability. Clipped historical monitor paths do not establish raw-return error guarantees. Planted alpha and capital ramps illustrate specified simulations. Existing experiment code is preserved but remains unopened and unscored throughout this review.

Six desk questions. For an unusually strong backtest, trace data availability, universe selection, search choices, timestamps, fills, costs, corporate actions and sampling uncertainty. Four hundred independent-normal tries over ten years give a mean-maximum hurdle near point nine four, but an observed winner of one point two is not thereby a significant discovery. Dependence and the trial spread matter, while DSR remains an approximation. With a reported annualised Sharpe ratio of two and first-order autocorrelation point four, assuming all higher autocorrelations zero gives a population scaling correction near one point five two. Those summaries alone do not establish a valid confidence interval.

Three more questions. A one-basis-point per-trade margin is sensitive to implementation error. The illustrative two-percent annual arithmetic assumes two hundred full-capital turnovers and no other costs. For three-year default labels, align evaluation with the prediction target, prevent overlapping label periods, and fit preprocessing using available training information. Group separation also matters when assessing generalisation to new firms. A valid e-process at twelve cannot retain a five-percent threshold guarantee if the threshold becomes ten. Ville instead gives ten percent at ten. New monitoring claims and restarts require justified nulls, past-measurable choices and a controlled overall error budget.

The first six problems derive the independent-normal Sharpe variance, a normal maximum distribution and median, an approximate expected noise hurdle and its mean-based backtest length, the PSR confidence score, and Lo's conditional annualisation correction. Distinguish asymptotic formulas and confidence scores from exact selection tests.

Problems seven through ten count the combinatorial cross-validation splits, derive the interior-fold loss under the library's explicit inclusive purging convention, calculate a geometric bootstrap block probability, and compare a valid e-process with repeated fixed-horizon tests. Repeated monthly tests are dependent; the independent-case calculation is a benchmark, not their universal error rate.

Two qualifying problems derive both lower and upper selection bounds in the known-covariance Gaussian model, then compute the naive winner interval's coverage for independent null estimates. With two estimates coverage is approximately ninety-five percent, while fifty give about twenty-eight percent. All twelve worked solutions are retained in English and Chinese.

Later chapters revisit validation for machine learning and text, broad searches, impact and capacity, and allocation. Their checks still need available-time inputs, mature labels, appropriate search accounting and explicit execution assumptions. Adding purging or a fitted deflation score is not a certificate. The final lecture audits what the recorded results and search counts can support.

The references connect data availability, selection, inference and implementation. Original public-data calculations, saved simulations, explicitly fabricated fixed arithmetic and known-Gaussian theorems are different kinds of evidence. Unavailable frozen historical outputs remain withheld. The reading list and all twelve worked solutions are retained in English and Chinese in the accompanying notes.

The House now has a backtester that cannot see tomorrow, a count of every trial it has run, and the statistics to judge a result against that count. It knows that a backtest can be clean, correct and still wrong, and that the only cure is evidence the backtest has not seen. Next, Part twenty-seven: machine learning for returns. Models with millions of parameters, trained on decades of characteristics, and every one of them validated, deflated and registered the way this part has taught.

Where it goes next. Every strategy in the rest of the series is held to this protocol (registered before its test, its trials counted); the finale asks what such a record can and cannot establish.

Key results

The part's results in one place, for revision.

Standard error of a Sharpe ratio\[\operatorname{se}(\widehat{\mathrm{SR}})\approx\sqrt{\frac{1+\tfrac12\mathrm{SR}^2}{T}}\]
Expected best of N\[\mathbb E[\max\widehat{\mathrm{SR}}]\approx\sqrt{V}\Bigl((1-\gamma)\,N^{-1}\bigl(1-\tfrac1N\bigr)+\gamma\,N^{-1}\bigl(1-\tfrac1{Ne}\bigr)\Bigr)\]
Deflated Sharpe ratio\[\mathrm{DSR}=N\!\Bigl(\frac{(\widehat{\mathrm{SR}}-\mathrm{SR}_0)\sqrt{T-1}}{\sqrt{1-\hat\gamma_3\widehat{\mathrm{SR}}+\tfrac{\hat\gamma_4-1}{4}\widehat{\mathrm{SR}}^2}}\Bigr)\]
Minimum backtest length\[T_{\min}\approx\Bigl(\frac{\mathbb E[\max_N z]}{\mathrm{SR}}\Bigr)^2\ \text{years}\]

Try it

Lab 26 · The best backtest of nothing, and the deflated Sharpe ratio

Backtest N strategies with no skill for five years and keep the best. Compare its Sharpe ratio with the expected-maximum formula, then deflate a reported Sharpe of 1.5 for the number of trials behind it.

Figure produced by Lab 26: The best backtest of nothing, and the deflated Sharpe ratio
Produced by the lab below, seed 0, in 0.6 s. Simulated data.
python -m videos.quant.labs 26 needs numpy, scipy, matplotlib, numba · download lab26.py · source on GitHub
Best of      1 skill-less strategies          annual Sharpe -0.00   (formula 0.00)
Best of     10 skill-less strategies          annual Sharpe 0.69   (formula 0.70)
Best of    100 skill-less strategies          annual Sharpe 1.13   (formula 1.13)
Best of  1,000 skill-less strategies          annual Sharpe 1.45   (formula 1.46)
Best of 10,000 skill-less strategies          annual Sharpe 1.73   (formula 1.73)
A reported Sharpe of 1.5: P(true Sharpe > 0)  N=1: 100%  N=10: 96%  N=100: 79%  N=1,000: 54%  N=10,000: 31%

Five years, one trial: 1.5 is convincing. After a thousand trials it is what noise is expected to produce. The trial count is part of the result.
The code (51 lines; it asserts its own result)
"""Lab 26: the best of N backtests of nothing, and the Sharpe ratio deflated for it."""

import numpy as np

from videos.quant import labs
from explainer.quant.house import backtest

TITLE = "The best backtest of nothing, and the deflated Sharpe ratio"
GOAL = ("Backtest N strategies with no skill for five years and keep the best. Compare its Sharpe ratio with the "
        "expected-maximum formula, then deflate a reported Sharpe of 1.5 for the number of trials behind it.")
TASKS = [
    "How many years of data would make the best of 1,000 noise strategies look like a Sharpe of 1? (backtest.min_btl)",
    "Give the returns negative skew and fat tails (skew=-1, kurt=8) in deflated_sharpe. What happens?",
    "Split one noise sample in two halves and pick the in-sample best. What is its out-of-sample rank? (backtest.cscv)",
]


def run(seed=0):
    T = 5 * 252  # five years of daily returns
    ann = np.sqrt(252)
    ns = np.array([1, 10, 100, 1000, 10000])
    sim = [ann * backtest.noise_max_sr(int(n), T, sims=1000, seed=seed).mean() for n in ns]
    theory = [ann * backtest.expected_max_sr(float(n), 1 / T) if n > 1 else 0.0 for n in ns]
    lab = labs.Lab()
    for n, s, th in zip(ns, sim, theory):
        lab.row(f"Best of {n:>6,} skill-less strategies", f"annual Sharpe {s:.2f}   (formula {th:.2f})")
    sr = 1.5 / ann
    dsr = {int(n): backtest.deflated_sharpe(sr, T, float(n), 1 / T)["dsr"] if n > 1 else backtest.psr(sr, 0.0, T) for n in ns}
    lab.row("A reported Sharpe of 1.5: P(true Sharpe > 0)", "  ".join(f"N={n:,}: {100 * v:.0f}%" for n, v in dsr.items()))
    lab.note = ("Five years, one trial: 1.5 is convincing. After a thousand trials it is what noise is expected to "
                "produce. The trial count is part of the result.")
    assert all(abs(s - th) < 0.12 for s, th in zip(sim[1:], theory[1:])) and dsr[1] > 0.99 > 0.6 > dsr[1000]

    fig, ax = labs.figure(2, size=(11, 4.2))
    grid = np.logspace(0.31, 5, 100)
    ax[0].semilogx(grid, [ann * backtest.expected_max_sr(float(n), 1 / T) for n in grid], color=labs.P, label="expected maximum (formula)")
    ax[0].semilogx(ns, sim, "o", color=labs.SPOT, label="simulated")
    ax[0].axhline(1.5, color=labs.LOSS, ls="--", lw=1)
    ax[0].text(1.2, 1.54, "the reported 1.5", color=labs.LOSS, fontsize=8)
    ax[0].set(title="Best annual Sharpe among N noise strategies, 5 years", xlabel="strategies tried, N", ylabel="Sharpe ratio")
    ax[0].legend(fontsize=8)
    best = ann * backtest.noise_max_sr(1000, T, sims=3000, seed=seed + 1)
    one = ann * backtest.noise_max_sr(1, T, sims=3000, seed=seed + 2)
    bins = np.linspace(-1.5, 2.5, 80)
    ax[1].hist(one, bins=bins, color=labs.CASH, alpha=0.8, label="one strategy")
    ax[1].hist(best, bins=bins, color=labs.SPOT, alpha=0.8, label="the best of 1,000")
    ax[1].axvline(1.5, color=labs.LOSS, ls="--", lw=1)
    ax[1].set(title="Sharpe ratios that pure noise produces", xlabel="annual Sharpe ratio")
    ax[1].legend(fontsize=8)
    lab.fig = fig
    return lab

Now change it

  1. How many years of data would make the best of 1,000 noise strategies look like a Sharpe of 1? (backtest.min_btl)
  2. Give the returns negative skew and fat tails (skew=-1, kurt=8) in deflated_sharpe. What happens?
  3. Split one noise sample in two halves and pick the in-sample best. What is its out-of-sample rank? (backtest.cscv)

Problems, with solutions

Try each problem before opening its solution; the last two of each set are at qualifying-exam level.

Desk questions, with solutions

Six desk questions and answers

  1. Sharpe 3: what could be wrong?
    AnswerTrace available-time inputs, missing firms, every search choice, signal/fill timing, costs, borrow and corporate actions. Inspect dependence, precision, validation and structural change. An event loop alone cannot validate external inputs or executable prices.
  2. 400 settings, ten years, best Sharpe 1.2?
    AnswerThe independent-normal approximate mean maximum is about 0.94. Exceeding a mean is not rejection at a stated level. Dependence, trial spread and the omitted research path matter; DSR is a sensitivity diagnostic.
  3. Three years, annualised Sharpe 2, lag-one correlation 0.4?
    AnswerIf every higher autocorrelation is zero, stationary arithmetic aggregation maps 2 to about 1.52. Those summaries do not identify a valid confidence interval; additional moments and dependence estimation are needed.
  4. 200 trades, 4 bp gross, 3 bp costs?
    AnswerThe margin is 1 bp per trade. A 2% annual arithmetic margin additionally assumes 200 full-capital turnovers and no other costs. A 1 bp cost error erases it; trade size and cost calibration matter.
  5. Three-year default labels, five random folds of firm-years?
    AnswerRespect label maturity and overlap, fit transformations only within available training data, and evaluate chronologically for future prediction. Group separation is needed when the target is new-firm generalisation. Choose gaps from actual label/feature spans.
  6. E-process at 12, move threshold 20 to 10?
    AnswerThe 5% bound at 20 is not retained. For a valid e-process starting at one, Ville gives a 10% crossing bound at ten. New monitors and restarts need valid conditional nulls, predictable choices and an overall error budget.

Problems, with worked solutions

Twelve worked problems: 6 foundations, 4 graduate, 2 qualifying

These are explicitly fixed mathematical examples, not new market trials.

  1. IID normal Sharpe variance. For iid normal returns show, by the delta method, that \(\operatorname{Var}\widehat{SR} \approx (1 + SR^2/2)/T\).

    Solution

    For g(μ,σ)=μ/σ, gradient (1/σ,−SR/σ). Under normal IID observations, asymptotic Var(μ̂)=σ²/T, Var(σ̂)=σ²/(2T), Cov=0. The delta method gives Var(SR̂)≈(1+SR²/2)/T. This is an asymptotic per-period result, not an exact small-sample or serially dependent variance.

  2. Normal maximum. Show that the maximum of \(N\) independent standard normals has CDF \(\Phi(c)^N\), and find its median for \(N = 100\).

    Solution

    Independence gives P(max Zᵢ≤c)=∏P(Zᵢ≤c)=Φ(c)^N. At N=100 the median is Φ⁻¹(2^(−1/100))≈2.46204.

  3. 100 noise estimates, five years. Use the independent-normal extreme-value mean approximation for the best annualised Sharpe ratio of 100 noise strategies over five years.

    Solution

    Let A_N=(1−γ)Φ⁻¹(1−1/N)+γΦ⁻¹(1−1/(Ne)). The normal/Gumbel mean approximation gives A_100/√5≈1.13172 annual Sharpe. This is not an exact Student-t simulation mean or significance threshold.

  4. N=1,000, target Sharpe 1. Equate the approximate mean null maximum to a target Sharpe of 1 for \(N=1{,}000\) independent tries. Find the mean-hurdle length, not a power requirement.

    Solution

    Equate the approximate null mean maximum to one: Y≈A_1000²≈10.5958 years. This mean-hurdle length does not specify confidence or detection power.

  5. PSR score. PSR: monthly \(\widehat{SR} = 0.1\), \(T = 60\), skewness \(-1\), kurtosis 6. Find \(\text{PSR}(0)\).

    Solution

    With monthly SR̂=0.1,T=60,skew=−1,kurtosis=6, z=0.1√59/√(1−(−1)0.1+(6−1)0.1²/4)≈0.72824. Φ(z)≈0.76677. This normal-reference confidence score is not a Bayesian posterior or an exact selection test.

  6. Lo aggregation. Find Lo's \(\eta(12)\) when \(\rho_1 = 0.3\) and all other autocorrelations are zero. By how much does \(\sqrt{12}\) overstate the annual Sharpe ratio?

    Solution

    With ρ₁=0.3 and all other lags zero, η(12)=12/√(12+2·11·0.3)≈2.78243. Naive √12 scaling is about 24.50% larger. The assumptions concern stationary arithmetic-sum moments, not a universal compounded-return identity.

  7. CSCV counts. CSCV with \(S = 16\) blocks: how many splits are there, and in how many is a given block in sample?

    Solution

    Choose 8 of 16 blocks: C(16,8)=12,870. A specified block is selected in C(15,7)=6,435 splits. The splits share observations and are not independent experiments.

  8. Inclusive purging convention. Use the library convention \(t_0=i,t_1=i+20\), inclusive spans, 5 contiguous folds of 5{,}000 observations and 20 additional embargo days after the test label span. How many training observations does an interior fold lose?

    Solution

    There are 5,000 observations, five contiguous folds, training label spans [i,i+20], and 20 additional embargo indices after the test label span. For an interior test fold [a,b] of 1,000 indices, its union of labels is [a,b+20]. Twenty earlier training spans intersect at the left; twenty later indices overlap the right; another twenty are embargoed. Thus 60 training observations are removed and 3,940 of the initial 4,000 remain. End folds have different counts. A different interval convention changes the answer.

  9. Stationary bootstrap. A stationary bootstrap with \(p = 0.1\): the expected block length, and the probability a block is at least 20 days long.

    Solution

    With restart probability p=0.1, geometric block length on {1,2,…} has E[L]=1/p=10 and P(L≥20)=(1−p)^19≈0.135085.

  10. Repeated looks. A valid e-process under its bounded conditional-mean null is read 120 times at threshold 20. Bound any rejection. Compare with 120 independent 5% tests, then explain why nested monthly \(t\)-tests need not follow that benchmark.

    Solution

    A nonnegative supermartingale E₀=1 under the actual conditional null satisfies P(sup_t E_t≥20)≤0.05, including 120 looks. For 120 independent 5% tests, P(any rejection)=1−0.95^120≈0.997878. Nested monthly tests are dependent, so that independent-test benchmark is not their universal error rate. Clipped raw-return monitors first need a justified clipped-increment null.

  11. General Gaussian winner bounds. (qual) \(X \sim N(\mu, \Sigma)\), winner \(\hat\jmath = \arg\max X\). Show \(Z = X - \Sigma_{\cdot j}X_j/\Sigma_{jj}\) is independent of \(X_j\), and that given \(\hat\jmath = j\) and \(Z\), \(X_j\) is a normal truncated to \([L(Z), U(Z)]\). Find \(L, U\).

    Solution

    X∼N(μ,Σ), Σ_jj>0, and known covariance. Set ρ_k=Σ_kj/Σ_jj and Z_k=X_k−ρ_kX_j; Gaussian projection makes Z independent of X_j. The event X_j≥X_k is Z_k≤a_kX_j with a_k=1−ρ_k. For a_k>0 it gives X_j≥Z_k/a_k; for a_k<0 it gives X_j≤Z_k/a_k; for a_k=0 it requires Z_k≤0. Combine all lower/upper bounds with feasibility. For equal variances and nondegenerate correlations below one, the upper bound is infinite. Conditional on feasible Z and winner j, the known-model distribution is the corresponding truncated normal. Exact inversion gives conditional coverage; finite solver caps, grids and estimated covariances do not inherit exact numerical guarantees.

  12. Naive interval for an independent null winner.

    Solution

    For N independent standard normals, a symmetric interval max Zᵢ±1.96 covers the selected true mean zero iff max Zᵢ∈[−1.96,1.96]. Coverage is Φ(1.96)^N−Φ(−1.96)^N. It is approximately 95.00% for N=2 and 28.20% for N=50. Positive winner bias does not imply strict undercoverage for every N or covariance structure; the two-estimate case is a useful counterexample.

Reading and notes

The part's papers

from READING.md

  • Brown, S., Goetzmann, W., Ibbotson, R., Ross, S. (1992). "Survivorship bias in performance studies." RFS.
  • Brock, W., Lakonishok, J., LeBaron, B. (1992). "Simple technical trading rules and the stochastic properties of stock returns." Journal of Finance.
  • Shumway, T. (1997). "The delisting bias in CRSP data." Journal of Finance.
  • Sullivan, R., Timmermann, A., White, H. (1999). "Data-snooping, technical trading rule performance, and the bootstrap." Journal of Finance.
  • Lo, A. W., Mamaysky, H., Wang, J. (2000). "Foundations of technical analysis." Journal of Finance.
  • White, H. (2000). "A reality check for data snooping." Econometrica.
  • Lo, A. W. (2002). "The statistics of Sharpe ratios." FAJ.
  • Hansen, P. R. (2005). "A test for superior predictive ability." JBES.
  • Romano, J., Wolf, M. (2005). "Stepwise multiple testing as formalized data snooping." Econometrica.
  • Ledoit, O., Wolf, M. (2008). "Robust performance hypothesis testing with the Sharpe ratio." J. Empirical Finance.
  • Bailey, D., López de Prado, M. (2012). "The Sharpe ratio efficient frontier." J. Risk.
  • Bailey, D., López de Prado, M. (2014). "The deflated Sharpe ratio: correcting for selection bias, backtest overfitting and non-normality." JPM.
  • Bailey, D., Borwein, J., López de Prado, M., Zhu, Q. J. (2014). "Pseudo-mathematics and financial charlatanism." Notices of the AMS.
  • Harvey, C., Liu, Y. (2015). "Backtesting." JPM.
  • Bailey, D., Borwein, J., López de Prado, M., Zhu, Q. J. (2017). "The probability of backtest overfitting." J. Computational Finance.
  • Arnott, R., Harvey, C., Markowitz, H. (2019). "A backtesting protocol in the era of machine learning." J. Financial Data Science.
  • Grünwald, P., de Heide, R., Koolen, W. (2024). "Safe testing." JRSS B.
Textbook auditReferences and textbook map
  • Brown, Goetzmann, Ibbotson and Ross (1992), Survivorship bias in performance studies; Shumway (1997), The delisting bias in CRSP data; Shumway and Warther (1999), Nasdaq delisting returns. Missingness and population definitions, not a substitute for blocked SEC outputs.
  • Brock, Lakonishok and LeBaron (1992); Sullivan, Timmermann and White (1999); White (2000); Politis and Romano (1994); Hansen (2005); Romano and Wolf (2005). Trading-rule selection and bootstrap inference under stated assumptions.
  • Lo (2002), The statistics of Sharpe ratios; Mertens (2002), Variance of the IID estimator in Lo (2002); Getmansky, Lo and Makarov (2004). Estimation, finite moments and serial correlation.
  • Bailey and López de Prado (2014), deflated Sharpe ratio; Bailey, Borwein, López de Prado and Zhu (2014; 2017), backtest length and PBO. Separate heuristic mean hurdles from exact inference.
  • López de Prado (2018), Advances in Financial Machine Learning, chapters 1 and 7; Arnott, Harvey and Markowitz (2019), A backtesting protocol in the era of machine learning. Evaluation design and implementation.
  • Ville (1939); Shafer and Vovk (2019); Wang and Ramdas (2022), e-BH. Betting evidence needs its actual conditional null; valid e-values precede multiplicity control.
  • Andrews, Kitagawa and McCloskey (2024), Inference on winners, QJE 139. Known-model theorem versus the finite numerical and historical plug-in examples here.
  • Leinweber (2007), Stupid data miner tricks. Historical illustration of search, not an empirical result generated by this review.
Data, scope and reproducibilityEvidence and data boundary

The presentation uses fourteen restored original calculations from unchanged compute.py and unchanged House algorithms. Sixteen normal original invocations produced fourteen successes and two source-verification failures, with no retries, force, refresh, registry changes or additional market trials. The existing cumulative registered count through Part 26 is 10,348; the global count is 23,562. The pre-Part-26 snapshot is 348. All 98 protected files retain their baseline hashes.

The original survivor calculation stops at the SEC ticker-file hash check. The original engine calculation stops at the Yahoo EEM extract hash check, before the later AAPL and SPY readers. Neither original empirical result is available for this review. The current workspace files fail the frozen manifest hashes; recovery found no matching workspace copy or git version. Their original code, failure logs and mismatching public inputs are preserved in the local QA archive. We do not refresh the manifest, bypass verification, fabricate caches or substitute a historical strategy. The Survivorship and Engine chapters instead use explicitly fabricated, fixed arithmetic examples. Current CIK membership would not, by itself, measure literal corporate survival.

common.load rejects envelope, survivor and engine prefixes before the cache/counting loader. The Envelope class is a conceptual registration and evaluation-accounting chapter; it does not read the sealed experiment cache, register anything, or open its market payload. Build commands below render the presentation; do not run all compute items, use force/refresh or open the envelope.

The access audit lists 32 possible pre-existing public manifest keys, not 32 confirmed reads: public OSAP panels, French data through 2020, Philadelphia monthly vintages, Cboe PUT, and the SEC/Yahoo readers reachable from the original code. Failed early readers prevent some downstream accesses. The public OSAP archive contains later-published/backfilled vintages before the research-date cuts. Reading that public archive is distinct from a sealed strategy opening, and does not make its older observations a timestamp-complete point-in-time panel.

Chapter notesNineteen chapters
  1. Hook. The earlier winner among 10,000 configurations has Sharpe 1.67 through 1986 and 0.02 in 1987–2020. Gross excess-cash compounding and a later decline do not prove clean data, tradeability or a unique cause.
  2. Look-ahead. A deliberate same-day index error changes the 200-day rule's Sharpe from 0.22 to 1.31; the five-day version reaches 8.75. GDP revisions compare 216 quarters, 1966–2019, with December 2020 vintages: mean absolute revision 1.54 points, 7.4% sign changes. Monthly vintage availability is not a complete release-timestamp replay.
  3. Survivorship. The blocked SEC original is withheld. Four invented returns −20%, −10%, +10%, +20% average zero; retaining only the positive pair gives +15%. A fixed +10%, then −50% sequence compounds to −45%. Selection need not always bias upward; missing and delisting returns require provider-specific definitions.
  4. Selection. Saved Student-t noise simulations give mean best annual Sharpe 0.69, 1.12, 1.46, 1.73 for 10, 100, 1,000, 10,000 estimates over five years. The independent-normal maximum law is exact for that stated model; the Gumbel mean formula is an approximation.
  5. Engine. The blocked Yahoo original is withheld. Invented quotes 100 at decision close, 102 next open, 101 next close separate decision, assumed fill and mark. One share loses 1 before costs; with 1,000 capital and a 0.20 fee, ending wealth is 998.80. Fixed split and dividend examples show accounting identities. A protected loop excerpt explains event ordering without certifying external data or realistic fills.
  6. Sharpe error. IID delta-method and moment formulas; stationary arithmetic aggregation under autocorrelation. Market ratio 0.44, estimated standard error 0.10; PUT ratio 0.45, error 0.27 or 0.30 with moments. These errors omit serial dependence. Fixed two-standard-error planning approximations are not power guarantees.
  7. Counter. Existing registrations, the 348 pre-part snapshot, and 10,348 through this part. Approximate mean maxima are not significance cutoffs. Registered counts omit informal choices; correlations do not identify a universal independent-search count.
  8. Technical rules. A seeded sample of configurations from four families, inspired by the literature rather than an exact replication. Gross excess-cash returns, two research eras and selected-family comparisons. Stale prices are a plausible concern, not an identified causal decomposition.
  9. Deflated Sharpe. PSR/DSR normal-reference confidence scores, not posterior probabilities or exact selection-adjusted tests. A participation ratio estimated from 1,500 sampled return correlations and scaled to 10,000 gives heuristic effective counts around 176 and 155. Later-era selection is distinct from testing the earlier winner.
  10. PBO. 12,870 overlapping half-sample splits, a precise half-tie rank convention and PBO 0.00/0.43. Zero does not mean rank one in every split or no overfitting. The saved logit histogram has a finite window; omitted tails are counted explicitly. All 800 saved scatter pairs are shown without clipping.
  11. Cross-validation. Full-sample feature scaling leaks into every original score. Blocked/purged folds can use future training; walk-forward training labels cross the boundary before maturity. A 20-day embargo does not remove every 60-day feature overlap. Hit rate uses the training-label median. These are leakage diagnostics, not clean live forecast estimates.
  12. Reality checks. Cash-relative differential means; 500 stationary-bootstrap draws with mean block length 10; simplified RC, SPA and step-down implementations. Zero means 0/500 exceedances. Sample-SD studentisers do not estimate serial long-run variance; approximate inference needs bootstrap assumptions. Nonrejection is not equivalence.
  13. Monitoring. Retrospective clipped-increment diagnostics on published-selected predictors. A valid nonnegative betting supermartingale requires a precommitted/predictable process with conditional clipped mean at most zero. A raw-return mean claim does not imply that null after clipping. e-BH requires valid unit-expectation-bounded e-values under true nulls; the saved counts alone do not establish those conditions.
  14. Planted alpha. Forty simulated markets per edge, 1,000 strategies, ten nonzero means. Saved discovery and DSR-score frequencies illustrate power/error tradeoffs under this simulation; they prove no universal impossibility or zero error.
  15. Funding. Fixed Gaussian simulated careers and an assumed arithmetic capital ramp. True Sharpe 1 is below the tested full target 1.5: its 3.8% stopping frequency is not a full-null false-alarm rate. True-zero stopping is 61.7%, median month 43 among stopped careers; half-target stopping is 9.6%. No calibrated execution costs or live capacity are modelled.
  16. Registration and evaluation accounting. Conceptual protocol, an existing metadata count, and fixed precision arithmetic. No sealed experiment opening or replacement historical performance test.
  17. House protocol. Available-time inputs, known exclusions, trial accounting, training-only transformations, mature labels, costs and a fresh evaluation design. Protected algorithms remain unchanged.
  18. Research: inference on a winner. Known-Gaussian selection bounds versus estimated historical Sharpe proxies. Exact ideal inversion is separate from finite ±60-standard-error brackets, an 801-point hybrid grid, simulated critical values and a 400-draw IID Gaussian multiplier calculation. The later conditional lower endpoint is beyond its stored −13.47 solver floor; that floor is not the exact endpoint. Historical differences do not isolate regime change from selection.
  19. Outro. Qualified recap, six desk questions, twelve problems in continuous 6/4/2 pages, references and next-part link.

中文讲义

本讲的中文说明、交易台问题与习题解答(与英文版对应)。

导言中文:第26讲,不自欺的回测

本讲保留19章,区分数据可用时间、研究选择、执行假设、估计误差、验证与监控。教育材料,不构成投资建议。

原始计算共正常调用16次,14项成功;SEC股票代码表和Yahoo EEM数据未通过冻结哈希校验,相关历史结果不展示。两章改用明确虚构的固定算术,不伪造缓存、不刷新清单、不绕过校验、不另做历史策略测试。原始代码、失败日志和不匹配的公开输入均已保存。common.load在缓存及计数加载器之前拒绝这两项及封存实验。封存章只讲登记、精度和评估记账,不打开市场载荷。原有累计计数为本讲之前348、截至本讲10,348、全局23,562;98个保护文件保持原哈希。

访问审计列出32个原代码可能访问的既有公开数据键,并非声称全部实际读取。公开OSAP档案含事后发表和回填版本,按研究日期切片不等于完整时点数据库,也不等于打开封存策略实验。GDP月度版本不能代替精确发布日期和日内执行回放。

章节顺序:开场;前视;生存者选择的固定算术;多次选择;执行时钟的固定算术;夏普估计误差;试验计数;技术规则;DSR;PBO;交叉验证;现实检验;监控;植入信号;资金爬坡;登记与评估记账;House协议;胜者推断;总结。十四项成功缓存的结果及模型限制见上文英文逐章说明。

核心限制:所有原交叉验证分数都用了全样本标准化;分块与清除设计仍可能用未来训练数据,前向设计的训练标签也未完全成熟。PSR和DSR是近似置信分数,不是后验概率或精确选择校正检验。PBO拆分高度重叠,零值不证明没有过拟合;有限直方图区间外的数量明确列出。500次自助抽样中的零超越不等于真实概率为零,原样本标准差不估计序列长期方差。

监控的有效条件是实际截断增量在给定过去下的条件均值不大于零;原始收益均值限制不能自动推出此条件。e-BH先要求真零假设下有效的e值。资金模拟中真实夏普1低于完整目标1.5,所以3.8%的停止率不能称为该零假设下的误报率。胜者推断的已知高斯定理与历史插件近似必须分开:原算法根搜索限制为观测值上下60个标准误,混合区间用801点网格。后来胜者的−13.47是搜索下限,不是精确区间端点。

Desk questions, with solutions六道面试题与答案
  1. 回测夏普3,哪里可能出错? 查数据可用时点、消失公司、研究选择、信号与成交时间、成本、融券、公司行动、相关性、估计误差、验证和结构变化。事件循环本身不能证明外部数据无泄漏或成交价可得。
  2. 400组参数、十年、最好夏普1.2? 独立正态模型的近似零技能最大值均值约0.94。超过均值不是给定水平的拒绝;相关性、试验间离散度和未记录的研究路径都重要。DSR是近似敏感性诊断。
  3. 三年、年化夏普2、一阶自相关0.4? 若其他自相关全为零,平稳算术聚合的缩放修正约为1.52。仅这些统计量不能确定有效置信区间,还需更高阶矩和依赖估计。
  4. 每年200笔、毛利4基点、成本3基点? 每笔净余1基点。年化算术2%还假定每笔用满本金、全年200次完整周转且无其他成本。成本误差1基点就能抹平优势。
  5. 三年违约标签,企业年度记录随机五折? 标签须成熟,清除实际重叠区间,预处理只能用当时可得训练数据。预测未来用时间设计,推广到新企业还需按企业隔离;间隔由实际特征和标签窗口确定。
  6. e过程到12,把阈值20改成10? 不能保留5%界限。有效非负超鞅从1开始时,Ville在阈值10给10%的穿越概率上界。重启还需有效条件零假设、可预测选择和总体错误预算。
Problems, with worked solutions十二道完整解答:6道基础、4道研究生、2道资格题

均为固定数学例题,不产生市场试验。

  1. 夏普方差。 g(μ,σ)=μ/σ,梯度为(1/σ,−SR/σ)。独立正态下,均值估计方差σ²/T、标准差估计渐近方差σ²/(2T),两者协方差为零。Delta法得Var(SR̂)≈(1+SR²/2)/T。这是每期渐近式,不是小样本或序列相关下的精确方差。
  2. 正态最大值。 独立性给P(max Zᵢ≤c)=Φ(c)^N。N=100时中位数Φ⁻¹(2^(−1/100))≈2.46204。
  3. 100个噪声估计、五年。 令A_N=(1−γ)Φ⁻¹(1−1/N)+γΦ⁻¹(1−1/(Ne))。正态极值均值近似为A_100/√5≈1.13172。这不是Student-t模拟的精确均值或显著性阈值。
  4. 1,000次、目标夏普1。 把近似零技能最大值均值设为1,得Y≈A_1000²≈10.5958年。这个均值门槛不指定置信水平或检验功效。
  5. PSR。 月夏普0.1、T=60、偏度−1、峰度6,z=0.1√59/√(1+0.1+5·0.1²/4)≈0.72824,Φ(z)≈0.76677。这是正态参考置信分数,不是贝叶斯后验或精确选择检验。
  6. Lo缩放。 ρ₁=0.3,其他滞后为零,η(12)=12/√(12+2·11·0.3)≈2.78243。朴素√12缩放高估约24.50%。条件是平稳算术和的矩,不是普遍的复利恒等式。
  7. CSCV计数。 C(16,8)=12,870;指定块入选的拆分有C(15,7)=6,435。拆分共享观测,不是独立实验。
  8. 含端点清除。 5,000个观测分五个连续折,标签[i,i+20]含端点,测试标签范围之后再禁运20个索引。内部测试折[a,b]含1,000个观测,标签并集为[a,b+20]。左侧20个训练标签相交,右侧20个索引相交,另禁运20个,共删除60个,原4,000个训练观测剩3,940。边缘折及其他区间约定答案不同。
  9. 平稳自助抽样。 重启概率p=0.1时,块长在正整数上服从几何分布,E[L]=10,P(L≥20)=0.9^19≈0.135085。
  10. 反复查看。 在实际条件零假设下,E₀=1的非负超鞅满足P(sup E_t≥20)≤0.05,120次查看也适用。120个独立5%检验至少拒绝一次的概率为1−0.95^120≈0.997878。嵌套月度检验相关,不能直接套独立结果。截断收益监控必须先证明截断增量的条件均值限制。
  11. 一般高斯胜者。 已知Σ且Σ_jj>0,令ρ_k=Σ_kj/Σ_jj、Z_k=X_k−ρ_kX_j;高斯投影使Z与X_j独立。X_j≥X_k等价于Z_k≤a_kX_j,其中a_k=1−ρ_k。a_k正时给下界,负时给上界,零时要求Z_k≤0。合并全部界限与可行性;等方差且非退化相关小于1时上界无穷。给定可行残差和胜者,X_j服从对应截断正态。精确反演的定理不能直接赋予有限搜索、网格或估计协方差同样的精确数值保证。
  12. 独立零均值胜者的朴素区间。 max Zᵢ±1.96覆盖零,当且仅当最大值位于[−1.96,1.96]。覆盖率Φ(1.96)^N−Φ(−1.96)^N;N=2约95.00%,N=50约28.20%。胜者向上偏不意味着所有N和协方差结构下都严格欠覆盖。

参考文献和教材对应关系见英文列表。科学源稿、双语构造和实际渲染视觉审查已完成,证据索引见下文;完整生产语音听审和发音检查仍另行待办。

Review log of the earlier QA passes on this part: docs/qa/quant/part26.md.

Build the film

python -m videos.quant.quant26.compute      # the part's numbers, into .cache/quant26
python tools/make.py quant26                # the narrated film, English and Chinese
EXPLAINER_TTS=silent python tools/qa_scene.py quant26 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/quant/quant26. Setup: see the course page. Source of these notes: the part's README and the scenes' narration.