Combinatorial Purged Cross-Validation in Python: Leak-Free Backtest Splits

This post builds a dependency-free numpy CPCV splitter with purge and embargo, then runs a leakage-count demo where leaking train rows drop from 50 to 0. All experiment numbers here are synthetic, from 600 simulated bars with a five-bar label horizon, not from live market data.

How this post was built: This post is based on official documentation and a synthetic sandbox run; we did not run the method on live market data. The numpy code in this post was run in a sandbox on synthetic data and skfolio was NOT installed for the run; the figures come from the cited sources and the run output.

Why Standard K-Fold Leaks in Financial ML

Standard K-Fold treats rows as independent, but in a backtest each row’s label is computed from nearby bars of the same series, so train and test can share information. In our synthetic run, naive K-Fold left 50 train rows (summed over its six splits) whose label neighborhoods overlap the test set; the purged CPCV splitter left zero.

Standard cross-validation assumes rows are independent and identically distributed. Price bars are not. Each training example typically uses trailing features and a forward-looking label, for example the return over the next five bars. When you shuffle rows or cut consecutive blocks without a buffer, a training row sitting next to a test block shares bars with test labels and test features.

The purge and embargo methodology, as referenced by the purgedcv README (Evgenii Lazarev) to Lopez de Prado 2018, chapter 7, exists to close that gap. The same README reports the author’s own synthetic test, which must be labeled as the author’s claim, not independently verified: naive shuffled K-Fold scored R² 0.83–0.91 on an unpredictable target with 100% label overlap, while PurgedKFold fell to −1.48/−1.87 with 0% overlap. That pattern is diagnostic of leakage, not predictability.

Our own synthetic check uses the same intuition with a simpler count. We do not fit a model at all. We count train rows whose five-bar information window touches any test bar. On 600 synthetic bars with six folds, plain unshuffled K-Fold leaves 50 such rows across its six splits. The purged CPCV splitter described below leaves zero across its fifteen.

Purge and Embargo: The Two Guard Windows

Purging removes training observations whose label windows overlap a test block; embargoing removes training observations immediately after each test block to block serial-correlation leakage. Our numpy splitter sets both to the label horizon, five bars in the synthetic experiment. The run confirmed zero train bars inside any guard window across all fifteen splits.

Purge handles known overlap. If labels use the next h bars, any train row within h bars before a test block has a label that reaches into that block, and any train row within h bars after the end of the block may use lookback features computed from test bars. Those rows are removed. Embargo handles unknown persistence. Even after known label overlap ends, serial correlation (the ARMA-type persistence skfolio cites) means bars immediately after a test block can still carry information about it. A short embargo buffer after each test block breaks that contact.

The skfolio CombinatorialPurgedCV API parameterizes both windows as purged_size and embargo_size. Its documented example is instructive: with n_samples=12, n_folds=3, n_test_folds=2, purged_size=1, split 1 trains on [5 6], not [4 5 6 7]. In other words, purge trims train rows adjacent to test blocks on both sides. The methodology itself follows Lopez de Prado chapter 7 via the purgedcv README (Evgenii Lazarev). Our implementation mirrors that trim-on-both-sides behavior and then adds an extra embargo buffer after each block.

From Purged K-Fold to Combinatorial Purged CV

Purged K-Fold still yields one train/test path. CPCV instead forms every combination of K test folds from N consecutive folds, producing multiple backtest paths. With six folds and two test folds the synthetic run produced fifteen splits, matching C(6,2). skfolio exposes the count via its n_test_paths property.

Purged K-Fold fixes leakage but keeps the single-path structure. You still get one sequence of out-of-sample predictions. That makes it hard to tell whether a good backtest reflects a robust rule or one lucky path through history.

Combinatorial purged CV changes the combinatorics. Split the series into N consecutive folds, then test on every combination of K folds. The skfolio model selection guide frames this as multiple testing paths, noting that cross_val_predict with CombinatorialPurgedCV returns a Population of portfolios, one per path, while KFold returns one single path. The purgedcv README (Evgenii Lazarev) describes the same idea as C(N,K) combinatorial folds with reconstruct_paths to assemble folds into backtest paths.

A small documented case makes the counting concrete. Per the skfolio CombinatorialPurgedCV API, n_samples=12, n_folds=3, n_test_folds=2 yields 3 splits, each with 2 test blocks, which is C(3,2)=3. For path counts we cite only skfolio’s n_test_paths property, described as the number of test paths that can be reconstructed from the train/test combinations. Our synthetic run uses N=6 folds and K=2 test folds and produced 15 splits, matching C(6,2).

A numpy CPCV Splitter with Purge and Embargo

Below is a dependency-free numpy implementation. Folds are consecutive blocks without shuffling — the first N-1 folds get n//N bars and the last takes the remainder, mirroring skfolio’s documented split semantics. Each split trims purged_size bars from both sides of every test block, plus an embargo_size buffer after it. The code below was run in a sandbox with synthetic data.

Unlike skfolio, which requires at least two test folds and points to sklearn’s KFold for one, this class accepts n_test_folds=1.

import numpy as np
from itertools import combinations

class CombinatorialPurgedCV:
    """Combinatorial Purged CV with embargo, in plain numpy.

    Folds are consecutive blocks with no shuffling: the first n_folds - 1
    folds hold n_samples // n_folds bars each and the last fold takes the
    remainder (mirroring skfolio's documented split semantics). Every split
    tests n_test_folds folds; the train set drops a purged_size window on
    both sides of each test block, plus an extra embargo_size buffer after it.
    """

    def __init__(self, n_folds=6, n_test_folds=2, purged_size=5, embargo_size=5):
        if n_folds < 3:
            raise ValueError("n_folds must be at least 3")
        if not 1 <= n_test_folds < n_folds:
            raise ValueError("need 1 <= n_test_folds < n_folds")
        self.n_folds = n_folds
        self.n_test_folds = n_test_folds
        self.purged_size = purged_size
        self.embargo_size = embargo_size

    @property
    def n_splits(self):
        """Number of train/test combinations: C(n_folds, n_test_folds)."""
        from math import comb
        return comb(self.n_folds, self.n_test_folds)

    def fold_bounds(self, n_samples):
        sizes = [n_samples // self.n_folds] * (self.n_folds - 1)
        sizes.append(n_samples - sum(sizes))      # last fold: remainder
        out, start = [], 0
        for s in sizes:
            out.append((start, start + s))
            start += s
        return out

    def split(self, n_samples):
        bounds = self.fold_bounds(n_samples)
        for test_ids in combinations(range(self.n_folds), self.n_test_folds):
            test = np.concatenate(
                [np.arange(bounds[i][0], bounds[i][1]) for i in test_ids]
            )
            mask = np.ones(n_samples, dtype=bool)
            mask[test] = False
            for i in test_ids:                    # guard windows
                lo, hi = bounds[i]
                mask[max(lo - self.purged_size, 0):lo] = False                    # purge
                mask[hi:hi + self.purged_size + self.embargo_size] = False        # purge + embargo
            yield np.flatnonzero(mask), test

Use this splitter wherever you need explicit index control. It yields (train_idx, test_idx) pairs in the familiar scikit-learn style, so it plugs into manual loops, custom walk-forward harnesses, or portfolio backtest code without extra dependencies.

The Leakage-Count Demo: 50 vs 0 on Synthetic Bars

We count train rows whose five-bar label neighborhood touches any test bar. On 600 synthetic bars with six folds and K=2, naive K-Fold leaves 50 leaking train rows; the purged CPCV splitter leaves zero, and zero train bars fall inside any guard window. All numbers come from this synthetic run, not real markets.

The reproducibility spec is simple. A train row t leaks when any test bar b satisfies |t - b| <= h, where h=5. That covers an h-bar forward label spanning t..t+h and h-bar lookback features spanning t-h..t. The naive baseline is plain K-Fold without shuffling. On unshuffled K-Fold with 600 bars and six folds this counts exactly the ±5 bars around each test block: 5 + 4×10 + 5 = 50. All numbers in this section are synthetic.

def naive_kfold(n_samples, n_splits):
    """Plain K-Fold without shuffling -- the leaky baseline."""
    fold = n_samples // n_splits
    for k in range(n_splits):
        test = np.arange(k * fold, (k + 1) * fold)
        train = np.concatenate(
            [np.arange(0, k * fold), np.arange((k + 1) * fold, n_samples)]
        )
        yield train, test

def leaking_train_rows(train, test, horizon):
    """Train rows whose information set touches the test set: an h-bar
    forward label spans t..t+h and h-bar lookback features span t-h..t,
    so a row leaks iff some test bar b satisfies |t - b| <= h."""
    near = np.abs(train[:, None] - test[None, :]) <= horizon
    return int(near.any(axis=1).sum())

def guard_violations(train, test, purged_size, embargo_size):
    """Sanity check: train bars inside a purge/embargo window (must be 0)."""
    cuts = np.flatnonzero(np.diff(test) > 1)
    starts = np.r_[test[0], test[cuts + 1]]
    ends = np.r_[test[cuts], test[-1]] + 1
    bad = 0
    for lo, hi in zip(starts, ends):
        bad += ((train >= lo - purged_size) & (train < lo)).sum()
        bad += ((train >= hi) & (train < hi + purged_size + embargo_size)).sum()
    return int(bad)

if __name__ == "__main__":
    # synthetic setup: 600 bars, 6 folds, K=2 test folds, horizon h=5
    n, horizon = 600, 5
    cpcv = CombinatorialPurgedCV(n_folds=6, n_test_folds=2,
                                 purged_size=horizon, embargo_size=5)
    splits = list(cpcv.split(n))

    guards = sum(guard_violations(tr, te, cpcv.purged_size, cpcv.embargo_size)
                 for tr, te in splits)
    naive = sum(leaking_train_rows(tr, te, horizon)
                for tr, te in naive_kfold(n, 6))
    purged = sum(leaking_train_rows(tr, te, horizon) for tr, te in splits)

    print(f"splits: {len(splits)} = C(6,2)")
    print(f"purge/embargo: {guards} train bars inside any guard window")
    print(f"label-overlap train rows, naive KFold: {naive}")
    print(f"label-overlap train rows, CPCV purged: {purged}")
splits: 15 = C(6,2)
purge/embargo: 0 train bars inside any guard window
label-overlap train rows, naive KFold: 50
label-overlap train rows, CPCV purged: 0

The guard check is separate from the leak count. It verifies that no train bar falls inside any purge or embargo window across all fifteen splits. The leak count is a consistency check, not a performance result: with purge=5 and embargo=5 against a five-bar horizon, no train row’s window touches the test set by construction. As an attributed aside, the purgedcv README (Evgenii Lazarev) reports a similar 100%-vs-0% overlap contrast in its own unverified experiment.

What the Evidence Says — and What It Doesn’t

Arian et al.’s 2024 abstract reports CPCV achieving lower Probability of Backtest Overfitting and a higher Deflated Sharpe Ratio test statistic than K-Fold, Purged K-Fold and walk-forward; we cite this at abstract level only. The purgedcv author’s own unverified experiments show similar leakage-driven inflation.

The main study is Arian et al. (2024), available as Arian et al. (2024), SSRN abstract 4686376. At abstract level only, the authors report that CPCV showed lower Probability of Backtest Overfitting and a higher Deflated Sharpe Ratio test statistic than K-Fold, Purged K-Fold and Walk-Forward. The full text was blocked to our fetcher, so this remains unverified beyond the abstract and should not be quoted as an established result.

The second source is the purgedcv README (Evgenii Lazarev). Its synthetic test found naive shuffled KFold R² of 0.83–0.91 on an unpredictable target versus −1.48/−1.87 for PurgedKFold, with label overlap of 100% versus 0%. Again, that is the author’s claim, not independently verified. Taken together, there is no generalization beyond these two attributed sources. They suggest leakage inflates in-sample confidence and that purging removes the mechanical overlap, but they do not prove CPCV selects better live strategies.

What CPCV Does NOT Fix

CPCV removes leakage, not every backtest pathology. It cannot rescue a mis-specified label horizon — purging only guards the horizon you declare. It does not fix non-stationarity, since folds still come from one historical regime. And testing many configurations still invites selection bias, which needs Deflated Sharpe Ratio and Probability of Backtest Overfitting analysis.

First, label horizon mis-specification persists. Purge and embargo only guard the horizon you declare. If your label actually depends on ten bars but you purge five, leakage remains. If features use long lookbacks or cross-sectional normalizations that peek ahead, no fixed five-bar buffer will save the split. Declare the true information window first, then set buffers to cover it.

Second, non-stationarity remains. All folds still come from the same history. Because every fold is drawn from that one sample, the paths cannot show how a rule behaves in a regime the sample never contained. Multiple paths quantify sensitivity to sample choice; they do not extrapolate to structural breaks.

Third, selection bias across many configurations still needs explicit analysis. Trying many models and hyperparameters overfits the validation scheme itself, which calls for Deflated Sharpe Ratio analysis per Bailey and Lopez de Prado 2014 as referenced by the purgedcv README (Evgenii Lazarev), and Probability of Backtest Overfitting analysis as measured in the Arian et al. (2024), SSRN abstract 4686376. This section is not investment advice; it is a candid scope limit.

Production Pointer: skfolio’s CombinatorialPurgedCV

For production use, skfolio ships CombinatorialPurgedCV with n_folds (minimum 3), n_test_folds, purged_size and embargo_size parameters. Its cross_val_predict returns a Population of portfolios, one per test path, and get_path_ids maps each test set to its path.

See the skfolio CombinatorialPurgedCV API for parameters n_folds (minimum 3), n_test_folds, purged_size and embargo_size, plus the n_test_paths property and get_path_ids() for mapping each test set to its path. The skfolio model selection guide notes defaults of n_folds=10, n_test_folds=8 and points to optimal_folds_number(n_observations, target_n_test_paths, target_train_size) for choosing fold counts. The same guide notes that cross_val_predict with CombinatorialPurgedCV returns a Population of portfolios, one per path, while KFold returns one single path. We did not execute this API here; skfolio was NOT installed in this run and nothing here was executed against that API. The sandbox used the numpy implementation above.

FAQ

The common questions are how to pick N and K, whether CPCV replaces walk-forward, and whether purging alone prevents overfitting. Short answers: use skfolio’s optimal_folds_number helper for fold counts, treat CPCV as complementary evidence rather than a walk-forward replacement, and pair it with DSR/PBO for selection bias.

How should you choose n_folds and n_test_folds?

The skfolio CombinatorialPurgedCV API requires n_folds >= 3, with documented defaults of 10 and 8 for n_folds and n_test_folds. The skfolio model selection guide points to optimal_folds_number(n_observations, target_n_test_paths, target_train_size) to trade off train size against number of paths. Start from your label horizon for purge and embargo sizes, then pick N and K that leave enough training bars per split after buffers are removed.

Does purging and embargoing make a backtest overfit-proof?

No. Purging and embargoing remove mechanical leakage, which is necessary but not sufficient. If you test dozens of feature sets and hyperparameters, selection bias remains. That second problem needs Deflated Sharpe Ratio and Probability of Backtest Overfitting analysis, as discussed in the purgedcv README (Evgenii Lazarev) and measured at abstract level in the Arian et al. (2024), SSRN abstract 4686376. See the caveat section above for horizon and regime limits.

Is CPCV a replacement for walk-forward validation?

Only attributed evidence exists, so do not generalize. The Arian abstract reports CPCV favorably at abstract level, and the purgedcv author’s experiments show leakage-driven inflation under naive splits; both are cited with limits above. The skfolio model selection guide frames the practical difference as multiple testing paths for CPCV versus one single path for KFold. This post treats CPCV as complementary evidence next to walk-forward, not a drop-in replacement.

← Back to all posts