purgedcv: scikit-learn-compatible purged and combinatorial cross-validation (CPCV) for time-series and financial machine learning in Python
Honest, leakage-aware cross-validation for time series and quantitative finance: purged k-fold, embargo, walk-forward, and combinatorial purged CV (CPCV) with backtest-path reconstruction, plus deflated and probabilistic Sharpe ratios.

Documentation → · Example notebooks → · purge/embargo, walk-forward, and CPCV with PSR/DSR worked end to end on real ICU-mortality, turbofan-RUL, rainfall, and electricity-demand data.
Cite this software: see Citation for the Zenodo DOI and a BibTeX entry.
Installation
pip install purgedcv
# Or from conda-forge (conda or mamba)
conda install -c conda-forge purgedcv
mamba install -c conda-forge purgedcv
# Directly from the repository
pip install git+https://github.com/eslazarev/purged-cross-validation.git
Time inputs are framework-agnostic: pandas Series/DatetimeIndex, NumPy
datetime64/timedelta64 arrays, Python datetime sequences, and Polars
Series are accepted. Polars remains optional; inputs are converted to a
one-dimensional NumPy array at the API boundary.
API summary
| Symbol |
Domain |
Description |
purge |
D2 |
Remove overlapping-horizon training rows |
apply_embargo |
D3 |
Remove time-, row-, or fraction-based post-test buffers |
WalkForwardSplit |
D5.1 |
Sliding / expanding walk-forward CV |
PurgedKFold |
D5.2 |
Contiguous test folds with purge + embargo |
PurgedGroupKFold |
D5.3 |
Group-aware purged k-fold |
CombinatorialPurgedCV |
D5.4 |
C(N,K) combinatorial folds |
CombinatoriallySymmetricCV |
D5.4 |
CSCV: symmetric IS/OOS folds, the PBO substrate |
reconstruct_paths |
D6 |
Assemble CPCV folds into backtest paths |
path_metrics |
D6 |
Per-path Sharpe / Calmar / drawdown / return table |
PathMetricFn |
D6 |
Callback type for custom per-path metrics |
probabilistic_sharpe_ratio |
D7 |
PSR: P(true SR > benchmark) |
deflated_sharpe_ratio |
D7 |
DSR: PSR corrected for multiple testing |
deflated_sharpe_ratio_full |
D7 |
DSR plus the intermediate deflation quantities |
DSRDiagnostics |
D7 |
Frozen result type returned by deflated_sharpe_ratio_full |
probability_of_backtest_overfitting |
D7 |
PBO via CSCV: how often in-sample selection overfits |
PBOResult |
D7 |
Frozen result type returned by PBO |
PerformanceMetric |
D7 |
Callback type for a custom PBO selection metric |
min_track_record_length |
D7 |
Minimum observations to establish SR |
minimum_backtest_length |
D7 |
MinBTL: backtest years below which a Sharpe is selection luck |
effective_n_trials |
D7 |
Independent-trial count for a correlated search, for DSR |
optuna_integration.TrialSharpeRecorder |
D7 |
Collect per-trial Sharpe variance + effective count for DSR |
audit_splitter |
D8 |
Per-fold filtering, overlap, block/envelope, and group audit report |
diagnostics.* |
D8 |
Leakage and embargo audit functions |
Contents
- The problem
- Does it actually catch leakage?
- Does an honest CV deploy better?
- What about a market with no real edge?
- Example notebooks
- Quickstart
- 1. The core primitive:
purge
- 2. The post-test buffer:
apply_embargo
- 3. Walk-forward CV:
WalkForwardSplit
- 4. Purged k-fold:
PurgedKFold
- 5. CPCV + path reconstruction + metrics: the full workflow
- Methodology references
- Citation
- License
The problem
Time-series rows can share information. When a label resolves over the next few days, its outcome window overlaps those of nearby rows, so a shuffled split can put overlapping labels into training and test sets. Rows immediately after a test window may also be serially dependent on it. purgedcv removes label overlap and supports a post-test embargo chosen for the task. These controls do not guarantee independence or prevent every form of leakage.
Why this package? purgedcv brings label-aware splitting, group separation, CPCV path reconstruction, and fold diagnostics into one MIT-licensed package. It uses the scikit-learn splitter interface, so you can use it in an existing model-selection workflow. The methodology guide explains its scope and links to related projects.
Does it actually catch leakage?
A controlled check on synthetic data whose target is built so that no feature can predict it. The honest out-of-sample score must never be positive. Naive shuffled k-fold runs against PurgedKFold side by side (examples/synthetic_leakage_proof.ipynb, deterministic, no downloads; run it in your browser: ):
| model |
naive shuffled KFold R² |
PurgedKFold R² |
| predict-the-mean (reference) |
-0.01 |
-0.13 |
| k-NN |
0.83 |
-1.48 |
| RandomForest |
0.91 |
-1.87 |
Train/test label overlap: 100% under naive → 0% under PurgedKFold.

Naive CV reports R² ≈ 0.83–0.91 on a target nothing can predict. That is pure leakage from the overlap. PurgedKFold removes the overlap and the fabricated skill collapses below a predict-the-mean baseline. The negative number is not the point; no positive skill is the correct answer, and only the purged split reports it. The library does not make models look better; it stops them looking better than they are.
Does an honest CV deploy better?
Same kind of question, opposite framing: on a partially predictable real task, does PurgedGroupKFold pick a model that deploys better than naive shuffled KFold? UK Low Carbon London smart meters, 48 households for model selection, 12 truly held-out households for deployment (examples/selection_regret_lcl.ipynb):
| selection method |
picked model |
deployment MAE |
deployment R² |
| naive shuffled KFold |
RF d=None |
2.638 kWh |
+0.759 |
| PurgedGroupKFold |
Ridge α=0.01 |
2.464 kWh |
+0.783 |
The honest-selected model deploys at 6.6% lower MAE on the 12 unseen households. Across 30 random 48/12 household partitions, honest wins every single one: naive picks deep RandomForest in all 30, honest picks Ridge in all 30, and the honest selection deploys better in all 30:
|
value |
| Honest deploys better |
30 / 30 partitions |
| Naive selector regret, median (IQR) |
0.28 kWh (0.18 to 0.52) |
| Honest selector regret, median (IQR) |
0 (exactly zero) |
| Naive − honest MAE, median |
0.28 kWh (13.3% relative) |
| Range |
0.11 to 1.79 kWh |
Plain sklearn.GroupKFold gives the same selection as PurgedGroupKFold here: the effect is a property of group-aware validation, not of a specific package (examples/selection_regret_lcl_seeds.py).

The naive selector picks deep RandomForest because the household-identifier feature lets it memorise per-household baselines inside the shuffled CV. On truly unseen households that feature is useless and the model collapses. An ablation that removes the identifier flattens the gap to zero. A second variant replaces the raw identifier with a causal target-mean encoding of the customer's average load (the kind of feature a careful practitioner would use): the gap reproduces at median 0.2154 kWh (10.1% relative, 29/30 wins), confirming the effect is not an artifact of the contrived identifier (examples/selection_regret_lcl_targetenc.py).
What about a market with no real edge?
On a task where no honest model has predictive power (daily BTC/USDT 2021-2023 with ordinary technical features), the question changes from "does honest CV pick a better model" to "does honest CV stop me from picking a worse one" (examples/selection_regret_crypto.ipynb):
|
naive shuffled KFold |
PurgedKFold |
| picked model |
RF d=None |
Ridge α=100 |
| deployment R² (180 held-out bars) |
-1.64 |
+0.011 |
| deployment Sharpe |
-0.77 |
-0.26 |
Both strategies lose money over the sideways-down deployment window; the naive pick loses three to five times more per unit of risk. Direction stable across 5 seeds. The library's value on a no-edge market is loss avoidance rather than gain.

Example notebooks
Fifteen notebooks in examples/ run on pip install "purgedcv[examples]". Each one downloads its data on the first run and caches it, so later runs work offline. The examples page in the documentation has longer descriptions, and the examples README lists data sources and licences.