Module contents
Lesson 28 of 30Advanced 120 min

Honest backtesting III: purged validation and the probability of backtest overfitting

Study validation under overlapping labels with purging, embargo and CPCV; measure selection overfitting with CSCV/PBO; and compare Reality Check, SPA and Romano-Wolf tests in controlled synthetic experiments.

After this lesson you can

  • Explain leakage from overlapping labels and autocorrelation in standard cross-validation.
  • Implement purging, embargo and combinatorial purged validation with its paths.
  • Calculate backtest overfitting probability with CSCV and interpret rank logits and performance degradation.
  • Apply White's Reality Check, Hansen's SPA and Romano-Wolf step-down using stationary bootstrap.
  • Design a known-truth synthetic comparison of walk-forward, k-fold, purged and CPCV validation.

Before you start

Validation is not necessarily a possible decision

A classifier can reach 70% validation accuracy and lose money live. The metric ignores, among other things, magnitudes of gains and losses, costs and regime changes. It can also be inflated if training receives information related to testing. A label based on a barrier observed between t0t_0 and t1t_1 occupies an interval, not just instant t0t_0. Two labels with overlapping intervals can share future returns.

Purged k-fold validation removes from training every label whose interval overlaps a test label. Half-open intervals [a,b)[a,b) and [c,d)[c,d) overlap if a<da<d and c<bc<b; touching an endpoint does not count. This convention must match the label definition. An embargo additionally removes nearby observations after a test block, for example to limit features with memory or residual dependence. Its length is a design choice, not an automatic remedy.

InteractiveLabels sharing the future

Each label is the sign of the sum of five independent future increments over a half-open interval. The toy classifier copies the nearest overlapping training label if available and otherwise predicts the training majority class. Copying demonstrates deliberate leakage in the synthetic data.

Label intervals for training and test

Red marks overlapping training intervals. Purging removes them and the embargo discards starts after the test block. Accuracy can differ from 50% on five observations, and other sources of leakage can remain after purging.

10
0
0
Training samples kept25
Removed0
Toy accuracy0.60
A deliberately leaked classifier copies overlapping labels.

Purging addresses declared intervals, not every dependence. A normalizer fitted on the whole sample, a feature calculated using future data or a retrospectively chosen universe still leaks information. If training uses blocks after the tested period, the result also does not simulate a chronological decision even without overlap. A final forward test preserves that distinction.

Suppose two events start on days 10 and 12, both with labels ending on day 15. Although stored in different rows, they share part of the path used to determine labels. A random split can place one row in training and the other in test; the model could exploit that dependence. Purging excludes that pair, but does not determine feature publication delay or guarantee stable distributions.

Embargo length also does not follow solely from fold size. If a feature needs 20 days of history, its availability and calculation window must be explicitly examined. Too short an embargo can leave dependence; too long reduces training and increases uncertainty. When test groups are noncontiguous apply the rule to each segment, avoiding accidental removal of entire intermediate blocks.

CPCV and paths

Combinatorial purged cross-validation divides history into NN groups and uses every combination of kk groups for testing. Each split has its own purged training data and, where applicable, embargo. There are (Nk)\binom Nk splits. Each block appears in (N−1k−1)\binom{N-1}{k-1} tests, because the other k−1k-1 groups are chosen from the remaining N−1N-1. Thus, assigning every appearance of each block once, one can construct

ϕ=kN(Nk)=(N−1k−1)\phi=\frac{k}{N}\binom Nk=\binom{N-1}{k-1}

paths covering all groups. Piece matching may not be unique and paths share data and models: they are not ϕ\phi independent histories. If a path combines models trained on data after their test blocks, it is not a causal deployment simulation.

With six groups and two for test there are 15 splits and five appearances of each group. Those five appearances can be assigned to five paths, one appearance per block and path. This accounting does not imply models for two pieces of one path were trained in temporal order. Nor does it turn dispersion of five Sharpes into five independent experiments; all pieces come from one history.

InteractiveReconstruct CPCV

Each row is a combination of test blocks. Blue highlights the pieces of one path, with each block appearing once. Synthetic returns illustrate the assembly without training or costs. Each Sharpe estimate uses only N observations.

Columns are blocks, rows are splits

The number of paths is k·C(N,k)/N = C(N−1,k−1). CPCV can train on data from after the test block, so a causal walk-forward evaluation uses a different split.

6
2
0
Splits15
Complete paths5
Path Sharpe0.09
Range of synthetic Sharpe ratios−0.11 to 1.44
The matrix shows splits and the chosen path.

Selection and PBO

Probability of backtest overfitting is estimated with CSCV on a matrix of synchronized returns by configuration. Periods are divided into an even number of blocks, one half is chosen for selection and the winning configuration evaluated on the complementary half. If its out-of-sample rank, ordered worst to best, is rr among MM strategies, define ω=r/(M+1)\omega=r/(M+1) and λ=log⁡(ω/(1−ω))\lambda=\log(\omega/(1-\omega)). Estimated PBO is the fraction with λ<0\lambda<0, equivalent to performance below the relative median. Tie convention and selection metric must be stated.

Bailey and coauthors propose CSCV as a selection diagnostic. A PBO of 0.6 says the training winner fell below the relative median on the complementary test in 60% of observed splits. It does not say 60% of capital will be lost or whether alpha exists. Low PBO can coexist with all strategies losing money.

Rank order is essential: here the worst receives 1 and the best MM. Ties receive average rank in the lab, and a logit exactly zero is not counted as below the median. Changing the metric from mean to Sharpe can change ranks. The method evaluates the supplied family; excluding failed variants before forming the matrix hides part of the search.

InteractiveRanks and degradation

The example generates six independent blocks and twenty variants. Each point corresponds to the in-sample winner and its value on the three complementary blocks. Out-of-sample rank runs from worst at 1 to best at 20, with omega = rank/21.

In-sample mean ±1.6Out of sample ±1.6Logit: −3 to 3

PBO is the fraction of splits with a negative omega logit, below the relative median. It describes relative ranks. Results across splits are dependent.

0.0
CSCV splits20
Fraction below the median0.10
Changing planted alpha modifies the synthetic experiment.

Data snooping and bootstrap

The Reality Check and SPA test the joint null that no strategy beats a benchmark. White uses the maximum of relative returns and bootstrap; Hansen studentizes and adjusts centering of clearly inferior alternatives to reduce Reality Check conservatism. The Romano-Wolf step-down procedure seeks to identify several strategies, recomputing the maximum over hypotheses not yet rejected and using joint resampling to account for dependence. Under its conditions it aims to control family-wise error asymptotically.

The Politis-Romano stationary bootstrap restarts at a uniform index with probability pp and otherwise advances circularly; block length is geometric with mean 1/p1/p. All columns are resampled with the same indices to preserve cross-sectional dependence. Appropriate length depends on the process; it does not make a changing real series stationary.

A global test and a list of discoveries answer different questions. Rejecting that all relative means are nonpositive does not automatically identify every superior strategy. Step-down compares the highest statistic with the bootstrap maximum, removes rejected hypotheses and repeats on the rest; adjusted p-values must respect the order. If benchmark, costs or family change after seeing p-values, the adjustment applied to the initial family no longer describes the entire search.

InteractiveThe maximum under the null

Synthetic zero-mean normal data. The histogram shows the centered bootstrap maximum of relative performance, and the orange line is the observed maximum. SPA studentizes and shifts the clearly inferior alternatives. The scales here come from the bootstrap.

Centered maximum: −0.26 to 4.34

The stationary bootstrap restarts with probability 0.1 and preserves cross-sectional dependence. The approximate p-values have resolution 1/301. Calibration across settings would require testing beyond one seed and model.

20
0.3
Reality Check p-value0.515
Approximate SPA p-value0.674
Bootstrap replicates300
The histogram and p-values use a synthetic joint bootstrap.

Lab: purging and paths

Rows are ordered by start time and each label has a half-open interval. Embargo is expressed as the number of rows immediately after each test block, not clock time. The class implements the basic scikit-learn interface; features must be built and normalized within each training set.

[ ]Interval-based splittersBrowser
import numpy as np
from itertools import combinations
class PurgedKFold:
    def __init__(self,n_splits,t1,embargo_pct=0.):
        self.n_splits=n_splits; self.t1=np.asarray(t1); self.embargo_pct=embargo_pct
    def get_n_splits(self,X=None,y=None,groups=None): return self.n_splits
    def split(self,X,y=None,groups=None):
        n=len(X); inicio=np.arange(n); fin=self.t1
        if len(fin)!=n or np.any(fin<=inicio) or not 2<=self.n_splits<=n or not 0<=self.embargo_pct<1: raise ValueError('Intervalos o parámetros inválidos')
        for test in np.array_split(inicio,self.n_splits):
            train=purga(inicio,fin,test,int(np.ceil(n*self.embargo_pct)))
            yield train,test
def purga(inicio,fin,test,embargo=0):
    n=len(inicio); test=np.asarray(test,dtype=int); prohibido=np.zeros(n,dtype=bool)
    for j in test: prohibido|=(inicio<fin[j]) & (inicio[j]<fin)
    prohibido[test]=True
    # Embargo tras cada tramo contiguo de filas de prueba.
    cortes=test[np.r_[np.diff(test)>1,True]]
    for ultimo in cortes: prohibido[ultimo+1:min(n,ultimo+1+embargo)]=True
    return np.flatnonzero(~prohibido)
def cpcv(inicio,fin,N,k,embargo=0):
    n=len(inicio); grupos=np.array_split(np.arange(n),N); partes=[]
    for seleccion in combinations(range(N),k):
        test=np.sort(np.concatenate([grupos[g] for g in seleccion]))
        train=purga(inicio,fin,test,embargo)
        partes.append((seleccion,train,test))
    return grupos,partes
def caminos(grupos,partes):
    N=len(grupos); k=len(partes[0][0]); phi=len(partes)*k//N
    salida=np.full((phi,N),-1,dtype=int); ocupacion=np.zeros(N,dtype=int)
    for idx,(sel,_,_) in enumerate(partes):
        for g in sel:
            salida[ocupacion[g],g]=idx; ocupacion[g]+=1
    assert np.all(ocupacion==phi) and np.all(salida>=0)
    return salida
inicio=np.arange(120); fin=np.minimum(inicio+5,120)
g,partes=cpcv(inicio,fin,6,2,embargo=2); paths=caminos(g,partes)
for sel,tr,te in partes:
    assert not np.any((inicio[tr,None]<fin[te]) & (inicio[te]<fin[tr,None]))
assert len(partes)==15 and paths.shape==(5,6)
print('Particiones:',len(partes),'| caminos:',paths.shape,'| sin solapamientos:',True)

Each path-matrix entry identifies which split supplies predictions to that block. For a backtest, train the corresponding model on the indicated split and concatenate predictions according to the matrix. The same split supplies several test blocks, so paths are not independent. The code checks all overlaps, including endpoints and noncontiguous blocks.

[ ]Triple-barrier labels and leakageBrowser
from sklearn.model_selection import KFold
from sklearn.neighbors import KNeighborsClassifier
rng=np.random.default_rng(282801); n=400; horizon=6
precios=np.r_[0.,np.cumsum(rng.normal(size=n+horizon))]
def triple_barrera(precios,n,h,umbral):
    fin=np.empty(n,dtype=int); y=np.empty(n,dtype=int)
    for i in range(n):
        delta=precios[i+1:i+h+1]-precios[i]
        hits=np.flatnonzero(np.abs(delta)>=umbral)
        paso=int(hits[0]+1) if len(hits) else h
        fin[i]=i+paso+1; y[i]=1 if delta[paso-1]>0 else 0
    return fin,y
fin,y=triple_barrera(precios,n,horizon,1.5); inicio=np.arange(n); X=inicio[:,None].astype(float)
kf=KFold(n_splits=10,shuffle=True,random_state=282802); ingenua=[]; purgada=[]; tamanos=[]
for train,test in kf.split(X):
    test=np.sort(test); limpio=purga(inicio,fin,test,embargo=0)
    assert not np.any((inicio[limpio,None]<fin[test]) & (inicio[test]<fin[limpio,None]))
    for indices,salida in [(train,ingenua),(limpio,purgada)]:
        modelo=KNeighborsClassifier(n_neighbors=3); modelo.fit(X[indices],y[indices])
        salida.extend(modelo.predict(X[test])==y[test])
    tamanos.append(len(limpio))
print('Exactitud KFold mezclada:',np.mean(ingenua),'| purga:',np.mean(purgada),
      '| clase mayoritaria:',max(y.mean(),1-y.mean()),'| entrenamiento mínimo:',min(tamanos))

Neighbors use only time as a feature and copy local information from labels that can share future movements: this is a leakage experiment, not a financial signal. Purging is applied to the same shuffled blocks to isolate overlap’s effect; resulting sets can be small and still include later training data. Sample randomness does not require exactly 50%, and the majority class is another benchmark. Deployment requires a temporal cutoff and training only on already available labels.

For this seed accuracy changes from 0.785 to 0.530 after purging, versus 0.505 for the majority class. This is an observation from this generator, not a claim that purging always reduces accuracy or leaves exactly chance level.

[ ]Out-of-sample predictions by CPCVBrowser
inicio=np.arange(n); grupos,partes=cpcv(inicio,fin,6,2,embargo=2); asignacion=caminos(grupos,partes)
predicciones={}
for i,(sel,tr,te) in enumerate(partes):
    modelo=KNeighborsClassifier(n_neighbors=3).fit(X[tr],y[tr])
    predicciones[i]=(te,modelo.predict(X[te]))
metricas=[]
for fila in asignacion:
    pred=np.full(n,-1)
    for grupo,idx in enumerate(fila):
        te,p=predicciones[idx]; mascara=np.isin(te,grupos[grupo])
        pred[te[mascara]]=p[mascara]
    assert np.all(pred>=0)
    metricas.append(float(np.mean(pred==y)))
print('Exactitud por trayectoria CPCV:',metricas,'| walk-forward no se infiere de estas trayectorias.')

Path dispersion describes these splits, not independent confidence intervals. Labels ending after a temporal cutoff must not be used before availability; even a procedure without label leakage can overfit the rule when compared many times.

Lab: CSCV and joint tests

We construct a synthetic return matrix where the first variant has a planted positive mean. Ranking uses mean return, not Sharpe; ties receive average rank. Complementary splits are counted separately because they exchange selection and test.

[ ]PBO from scratchBrowser
from scipy.stats import rankdata
def cscv(retornos,S=6):
    x=np.asarray(retornos,float); T,M=x.shape
    if S%2 or S>T or M<2: raise ValueError('Se necesitan bloques pares y al menos dos variantes')
    bloques=np.array_split(np.arange(T),S); logits=[]; pares=[]
    for sel in combinations(range(S),S//2):
        train=np.concatenate([bloques[j] for j in sel])
        test=np.concatenate([bloques[j] for j in range(S) if j not in sel])
        ins=x[train].mean(axis=0); outs=x[test].mean(axis=0); mejor=int(np.argmax(ins))
        rango=rankdata(outs,method='average')[mejor]; omega=rango/(M+1)
        logits.append(np.log(omega/(1-omega))); pares.append((ins[mejor],outs[mejor],mejor))
    return np.array(logits),np.array(pares)
rng=np.random.default_rng(282803); T=240; M=20
comun=rng.normal(size=(T,1)); retornos=.4*comun+np.sqrt(.84)*rng.normal(size=(T,M))
retornos[:,0]+=.25
logits,pares=cscv(retornos)
print('PBO:',np.mean(logits<0),'| particiones:',len(logits),'| ganadoras alfa:',np.sum(pares[:,2]==0))
print('Pendiente descriptiva train/test:',np.polyfit(pares[:,0],pares[:,1],1)[0])

The slope is descriptive and splits are not independent. Configurations, metric and blocks were fixed before observing outputs. A real matrix must include all variants and synchronized net returns; one already filtered selection can underestimate overfitting.

In the realization with planted alpha, 19 of 20 splits select the first variant and observed PBO is 0.05. That figure describes this matrix’s ranking, not the probability that a real strategy retains its edge.

For the bootstrap, dt,jd_{t,j} is return of strategy jj minus benchmark: positive values favor the strategy. Reality Check uses Tmax⁡jdˉj\sqrt T\max_j\bar d_j against the resampled centered maximum. SPA uses a long-run scale estimated from bootstrap means, a maximum truncated at zero and consistent centering: alternatives with statistic below −2log⁡log⁡T-\sqrt{2\log\log T} retain their negative mean in the resampled null; the rest are centered at zero. These calculations are a finite example, not a calibration guarantee.

[ ]Stationary bootstrap, Reality Check and SPABrowser
def stationary_indices(T,B,block_mean,rng):
    if not 1<=block_mean<=T: raise ValueError('Bloque inválido')
    idx=np.empty((B,T),dtype=int); idx[:,0]=rng.integers(T,size=B)
    for t in range(1,T):
        restart=rng.random(B)<1/block_mean
        idx[:,t]=np.where(restart,rng.integers(T,size=B),(idx[:,t-1]+1)%T)
    return idx
def contrastes(d,B=500,block_mean=10,seed=1):
    d=np.asarray(d,float); T,M=d.shape; rng=np.random.default_rng(seed)
    indices=stationary_indices(T,B,block_mean,rng)
    mu=d.mean(axis=0); bm=d[indices].mean(axis=1)
    centrado=np.sqrt(T)*(bm-mu)
    sigma=np.std(centrado,axis=0,ddof=1)
    if np.any(sigma<=0): raise ValueError('Varianza bootstrap nula')
    obs=np.sqrt(T)*mu; rc_obs=np.max(obs); rc_boot=np.max(centrado,axis=1)
    z=obs/sigma; spa_obs=max(0.,np.max(z)); limite=-np.sqrt(2*np.log(np.log(T)))
    ajuste=np.where(z<limite,z,0.); spa_boot=np.maximum(0,np.max(centrado/sigma+ajuste,axis=1))
    p_rc=(1+np.sum(rc_boot>=rc_obs))/(B+1)
    p_spa=(1+np.sum(spa_boot>=spa_obs))/(B+1)
    return p_rc,p_spa,z,centrado/sigma
pr,ps,z,boot=contrastes(retornos,B=500,block_mean=10,seed=282804)
print('Reality Check p:',pr,'| SPA p:',ps,'| estadísticos:',z)

The +1 corrected p avoids reporting zero with finitely many replicates. Bootstrap deviation estimates long-run scale once and remains fixed for studentization; other implementations may choose different estimators and centering. SPA truncation and the finite number of blocks affect the result. The example does not implement every alternative bound in Hansen’s paper.

[ ]Joint step-downBrowser
def romano_wolf(z,boot):
    z=np.asarray(z); boot=np.asarray(boot); B=boot.shape[0]
    orden=np.argsort(-z); ajustados=np.empty(len(z)); anterior=0.
    for k,j in enumerate(orden):
        maximo=np.max(boot[:,orden[k:]],axis=1)
        p=(1+np.sum(maximo>=z[j]))/(B+1)
        anterior=max(anterior,p); ajustados[j]=anterior
    return ajustados
ajustados=romano_wolf(z,boot)
assert np.all(np.diff(ajustados[np.argsort(-z)])>=-1e-12)
print('p ajustados step-down:',ajustados,'| rechazos al 5 %:',np.flatnonzero(ajustados<=.05))

Step-down uses the same centered-replicate matrix and per-strategy scales, a studentized approximation. Decreasing order and monotonicization make adjusted p-values coherent. Validity requires conditions on bootstrap, dependence and hypothesis family; running the function is insufficient. Global tests answer whether any improvement exists, while step-down provides adjusted individual decisions.

We apply the same functions to four reconstructed variants from the strategies lesson: three trend windows and carry. As in the previous lesson, this is only a subset of attempts and does not include the whole search. Returns already include simplified commission and borrow; zero is the explicit benchmark. The process keeps the same indices across all columns.

[ ]Tests on reconstructed variantsBrowser
rng=np.random.default_rng(282601); TT=1260
carry=np.tile(np.array([.00025,-.0001,.00015]),(TT,1))
regimen=np.where((np.arange(TT)//126)%2==0,.0006,-.0006)
r=rng.normal(0,.01,(TT,3))+regimen[:,None]*np.array([1.,-.4,.7])+carry
r[850:855]-=.035*np.array([1.,.6,.8])
def neto(r,w):
    prev=np.vstack([np.zeros((1,3)),w[:-1]])
    return (w*r).sum(axis=1)-.0005*np.abs(w-prev).sum(axis=1)-.02*np.maximum(-w,0).sum(axis=1)/252
variantes=[]
for ventana in (21,63,126):
    w=np.zeros_like(r)
    for t in range(ventana,TT):
        h=r[t-ventana:t]; vol=np.sqrt(np.mean(h*h,axis=0))
        w[t]=np.sign(h.sum(axis=0))*np.minimum(1.5,.01/np.maximum(vol,.001))/3
    variantes.append(neto(r,w))
w=np.zeros_like(carry); w[1:]=np.sign(carry[:-1])/3; variantes.append(neto(r,w))
rejilla=np.column_stack(variantes)[126:504]
pr,ps,z,boot=contrastes(rejilla,B=500,block_mean=10,seed=282805)
print('Cuatro variantes, benchmark cero | Reality Check:',pr,'| SPA:',ps,
      '| p ajustados:',romano_wolf(z,boot))

Local lab: validation tournament

This experiment is inspired by the question of Arian and coauthors, but does not reproduce their generator or results. Each search has 24 synthetic strategies, a changing regime and an autocorrelated common component. Selection uses mean over the first 120 periods. True future value is known because the generator defines the final regime’s mean; it is compared with the validation estimate, not a single noisy future return.

We calculate walk-forward, shuffled KFold, purged KFold with intervals of length 3 and CPCV with six blocks, two for test. Each split selects the best variant on training and measures its mean on test. Walk-forward excludes the final two training points before test. Mean scores are compared with the true future mean of the variant chosen using the entire initial segment: these rules evaluate similar but not identical selection processes. We measure correlation between estimate and truth and sign agreement; no universal superiority follows.

[ ]One thousand searches with synthetic regimesLocal GPU
import os,time
import numpy as np
from itertools import combinations
from joblib import Parallel,delayed
def torneo(seed):
    rng=np.random.default_rng(seed); T=160; M=24; corte=120
    alfa=rng.normal(0,.08,M); regimen=np.ones(T); regimen[80:]=-.5
    comun=np.zeros(T); ruido=rng.normal(size=T)
    for t in range(1,T): comun[t]=.5*comun[t-1]+ruido[t]
    x=regimen[:,None]*alfa+.3*comun[:,None]+rng.normal(size=(T,M))
    elegido=int(np.argmax(x[:corte].mean(axis=0))); verdad=-.5*alfa[elegido]
    def puntuar(tr,te):
        if len(tr)==0: return np.nan
        j=int(np.argmax(x[tr].mean(axis=0))); return x[te,j].mean()
    def limpiar(tr,te):
        # Intervalos semiabiertos [t,t+3), con purga de todo solapamiento.
        return tr[~np.any((tr[:,None]<te[None,:]+3)&(te[None,:]<tr[:,None]+3),axis=1)]
    wf=[]
    for inicio in (60,80,100):
        wf.append(puntuar(np.arange(inicio-2),np.arange(inicio,inicio+20)))
    perm=rng.permutation(corte); folds=np.array_split(perm,5); normal=[]; purgada=[]
    for te in folds:
        tr=np.setdiff1d(np.arange(corte),te)
        normal.append(puntuar(tr,te)); purgada.append(puntuar(limpiar(tr,te),te))
    bloques=np.array_split(np.arange(corte),6); combinada=[]
    for sel in combinations(range(6),2):
        te=np.concatenate([bloques[j] for j in sel]); tr=np.setdiff1d(np.arange(corte),te)
        combinada.append(puntuar(limpiar(tr,te),te))
    return verdad,np.mean(wf),np.mean(normal),np.mean(purgada),np.mean(combinada)
B=1000; trabajadores=os.cpu_count() or 1; comienzo=time.perf_counter()
filas=np.array(Parallel(n_jobs=trabajadores,prefer='threads')(delayed(torneo)(282900+i) for i in range(B)))
verdad=filas[:,0]
for j,nombre in enumerate(('walk-forward','k-fold mezclado','k-fold purgado','CPCV'),1):
    estimado=filas[:,j]
    print(nombre,'| correlación con verdad futura:',np.corrcoef(estimado,verdad)[0,1],
          '| acuerdo signo:',np.mean((estimado>0)==(verdad>0)),
          '| error absoluto medio:',np.mean(np.abs(estimado-verdad)))
print('Búsquedas:',B,'| variantes por búsqueda:',24,'| hilos:',trabajadores,
      '| CPU disponibles:',os.cpu_count(),'| segundos:',time.perf_counter()-comienzo)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Thread count uses total logical CPUs reported by the system; on a shared machine it can be explicitly reduced. The generator does not simulate costs, executions or trainable models, and purging applies to fixed-length intervals. Results depend on alpha magnitude and regime change; sign agreement is not a complete utility measure. Analysis requires repeating seeds and sizes before generalizing.

In the run of 1,000 searches with 24 variants, correlations with true future mean were negative for all four methods; sign agreement was 0.467 for walk-forward, 0.402 for shuffled KFold, 0.423 for purged KFold and 0.422 for CPCV. In this generator CPCV mean absolute error was lower, but that does not make it a causal prediction or establish a general ranking of methods. The final run and resources used are reported in the output.

Exercises

NumericTen blocks
With N=10 and k=2, how many test splits does CPCV have?
QuizCounting paths
Why does each block appear in C(N−1,k−1) test splits?
QuizInterpreting PBO
An estimated CSCV PBO of 0.6 means...
QuizGlobal and individual hypotheses
What distinguishes Reality Check from Romano-Wolf step-down?
CodeInterval purging
Implement PurgedKFold(n_splits,t1,embargo_pct) with split(X). Rows have integer starts 0,...,n−1 and exclusive end t1[i]. Split contiguous indices with np.array_split; remove from training any interval overlapping a test label. Also remove ceil(n*embargo_pct) rows after the test block. Return train,test indices in each iteration.
class PurgedKFold:
  def __init__(self,n_splits,t1,embargo_pct=0.):
      self.n_splits=n_splits; self.t1=t1; self.embargo_pct=embargo_pct
  def split(self,X):
      raise NotImplementedError()
Shift+Enter to run

Key takeaways

Key idea
Purging protects declared intervals; CPCV and PBO study variability and selection; multiple tests address explicit hypotheses. None replaces a final causal test.

Retain every variant, availability time, training schedule, cost and selection decision. Minimum length calculated without counting trials does not compensate for a massive search, and low PBO does not demonstrate profitability.

The previous lesson’s minimum-length formula can compare observed Sharpe with selection-adjusted threshold S0S_0 instead of zero. Holding moments fixed, length grows as S^−S0\widehat S-S_0 shrinks; if it is not positive, that formula does not reach the desired one-sided confidence. This approximation depends on trial count and dispersion, not a license to keep testing until an attractive score appears. Temporal dependence and regime changes require additional analysis and a reserved final test.