Skip to Content

Cross-validation

Split time-ordered data with purging, embargo and walk-forward windows so that no training label overlaps a test label.

Ordinary k-fold cross-validation assumes that rows are independent. Financial labels are not. A 5-observation forward return starts at one observation and ends five observations later, so the label on Monday and the label on Tuesday share four days of price movement. If Monday is in the training set and Tuesday is in the test set, the model has already seen most of the outcome it is being tested on. The cross-validated score comes out higher than the score you would get live, and nothing in the score tells you so.

lacuna.cv builds splits that account for this. A purged split removes every training row whose label interval overlaps a test label, and an optional embargo removes the observations that immediately follow a test block. Every split is returned as an inspectable object: which rows are in training, which were purged, which were embargoed, and the evidence of how that was decided.

A first example

Twelve observations, each with a label that covers the observation and the next one. The label interval is half-open: [label_start, label_end).

import lacuna as lc
import polars as pl

labels = pl.DataFrame(
    {
        "observation_time": list(range(12)),
        "label_start": list(range(12)),
        "label_end": [t + 2 for t in range(12)],
    }
)
spans = list(zip(labels["label_start"], labels["label_end"]))


def overlaps(i, j):
    """True when the half-open label intervals of rows i and j overlap."""
    return spans[i][0] < spans[j][1] and spans[j][0] < spans[i][1]


def leaking(train_rows, test_rows):
    """Training rows whose label overlaps the label of any test row."""
    return [i for i in train_rows if any(overlaps(i, j) for j in test_rows)]


test_rows = [3, 4, 5]
train_rows = [i for i in range(12) if i not in test_rows]
print("plain split, leaking training rows:", leaking(train_rows, test_rows))
plain split, leaking training rows: [2, 6]

A plain split that holds out rows 3, 4 and 5 trains on rows 2 and 6, and their labels overlap the test labels. Now the same hold-out with PurgedKFold:

split = lc.cv.PurgedKFold(n_splits=4, embargo=2).split(labels)
fold = split.folds[1]
print("test:", fold.test_indices)
print("purged:", fold.purged_indices)
print("embargoed:", fold.embargoed_indices)
print("train:", fold.train_indices)
print("purged split, leaking training rows:", leaking(fold.train_indices, fold.test_indices))
test: (3, 4, 5)
purged: (2, 6)
embargoed: (7,)
train: (0, 1, 8, 9, 10, 11)
purged split, leaking training rows: []

The fold tests the same three rows, drops rows 2 and 6 because their labels overlap the test labels, and drops row 7 because it falls inside the two-observation embargo after the test block. This table shows the reason for every row:

role = {}
for name, rows in (
    ("train", fold.train_indices),
    ("test", fold.test_indices),
    ("purged", fold.purged_indices),
    ("embargoed", fold.embargoed_indices),
):
    for i in rows:
        role[i] = name

table = pl.DataFrame(
    {
        "row": list(range(12)),
        "label": [f"[{a}, {b})" for a, b in spans],
        "role": [role[i] for i in range(12)],
        "overlaps_test_rows": [
            ", ".join(str(j) for j in fold.test_indices if j != i and overlaps(i, j))
            for i in range(12)
        ],
    }
)
with pl.Config(tbl_rows=12):
    print(table)
shape: (12, 4)
┌─────┬──────────┬───────────┬────────────────────┐
│ row ┆ label    ┆ role      ┆ overlaps_test_rows │
│ --- ┆ ---      ┆ ---       ┆ ---                │
│ i64 ┆ str      ┆ str       ┆ str                │
╞═════╪══════════╪═══════════╪════════════════════╡
│ 0   ┆ [0, 2)   ┆ train     ┆                    │
│ 1   ┆ [1, 3)   ┆ train     ┆                    │
│ 2   ┆ [2, 4)   ┆ purged    ┆ 3                  │
│ 3   ┆ [3, 5)   ┆ test      ┆ 4                  │
│ 4   ┆ [4, 6)   ┆ test      ┆ 3, 5               │
│ 5   ┆ [5, 7)   ┆ test      ┆ 4                  │
│ 6   ┆ [6, 8)   ┆ purged    ┆ 5                  │
│ 7   ┆ [7, 9)   ┆ embargoed ┆                    │
│ 8   ┆ [8, 10)  ┆ train     ┆                    │
│ 9   ┆ [9, 11)  ┆ train     ┆                    │
│ 10  ┆ [10, 12) ┆ train     ┆                    │
│ 11  ┆ [11, 13) ┆ train     ┆                    │
└─────┴──────────┴───────────┴────────────────────┘

Row 1 has the label [1, 3) and the first test label starts at 3. The two intervals touch but do not overlap, because the end of a half-open interval is excluded, so row 1 stays in training. Row 8 is kept for the same reason on the other side: its label starts at 8 and the last test label ends at 7. Row 7 also survives the purge, since its label [7, 9) starts where the last test label ends. The embargo is what removes it.

Why purging works the way it does

For a fold with test rows TT, a candidate training row ii is purged when there is a test row jj with

starti<endjandstartj<endi\text{start}_i < \text{end}_j \quad\text{and}\quad \text{start}_j < \text{end}_i

where start is label_start and end is label_end. This is the overlap test for half-open intervals. It purges on both sides of the test block: a row before the block whose label reaches into it is removed, and so is a row after the block whose label begins inside it. Two intervals that only share an endpoint do not overlap.

The fold boundaries are separate from the label intervals. Lacuna takes the sorted distinct values of the time column, cuts them into n_splits contiguous groups with numpy.array_split (group sizes differ by at most one, with the larger groups first), and treats every row whose time falls in a group as the test set of that fold. With panel data, one fold therefore holds out all instruments for a range of dates. A row never moves between folds based on its label.

Purging needs label_start < label_end for every row. Equal or reversed intervals raise a DataContractError.

What split takes

ParameterMeaning
dataA table with the three columns below: Polars, pandas, Arrow or anything to_polars accepts. A LabelResult is not accepted directly; pass its .frame.
timeThe observation-time column that defines the folds. Integer, Date or Datetime. Default "observation_time".
label_startThe start of each label interval. Default "label_start".
label_endThe end of each label interval. Must have the same dtype as label_start. Default "label_end".

The defaults match the columns of forward_returns, so lc.cv.PurgedKFold().split(labels.frame) works on its output. If the label frame holds several horizons, filter it to the horizon you are validating first, because each row is split and purged on its own interval.

Row order does not matter. The indices in a fold are positions in the table you passed in, not sorted positions, and a shuffled table produces the same folds in terms of observation times. Nulls in any of the three columns raise a DataContractError.

Reading a split

split returns a SplitResult:

MemberMeaning
foldsA tuple of Fold objects.
evidenceAn AnalysisResult with the configuration, counts and a fold table.
fold_tableThe folds table of the evidence, as JSON-compatible rows.
to_json()The evidence serialized as JSON.
iterationYields (train_indices, test_indices) pairs of integer NumPy arrays, which is the shape most training loops want.

Each Fold has fold (its number), train_indices, test_indices, purged_indices and embargoed_indices, all tuples of source-row positions. For PurgedKFold and CombinatorialPurgedKFold, every row outside the test set is in exactly one of train, purged or embargoed. For WalkForward, purged_indices and embargoed_indices are always empty, and rows outside the training and test windows belong to no role.

for train, test in split:
    print(len(train), len(test))
print(split.evidence.metrics)
7 3
6 3
6 3
8 3
{'n_folds': 4, 'purged_observations': 6, 'embargoed_observations': 3}

The evidence table lists, for each fold and role, the first and last observation time and the number of rows:

print(pl.DataFrame(split.fold_table).filter(pl.col("fold") == 1))
shape: (4, 5)
┌──────┬─────────┬───────┬─────┬────────────────┐
│ fold ┆ role    ┆ start ┆ end ┆ n_observations │
│ ---  ┆ ---     ┆ ---   ┆ --- ┆ ---            │
│ i64  ┆ str     ┆ i64   ┆ i64 ┆ i64            │
╞══════╪═════════╪═══════╪═════╪════════════════╡
│ 1    ┆ train   ┆ 0     ┆ 11  ┆ 6              │
│ 1    ┆ purge   ┆ 2     ┆ 6   ┆ 2              │
│ 1    ┆ test    ┆ 3     ┆ 5   ┆ 3              │
│ 1    ┆ embargo ┆ 7     ┆ 7   ┆ 1              │
└──────┴─────────┴───────┴─────┴────────────────┘

The role column uses purge and embargo, where the Fold attributes say purged and embargoed. start and end are the smallest and largest observation time among the rows in that role, so a training set made of two separate stretches of time shows only its outer bounds. A role with no rows has null bounds and zero observations.

Embargo

An embargo removes the observations that follow a test block, whether or not their labels overlap it. It exists for dependence that purging cannot see: features built from rolling windows, or any serial correlation that carries information from the test period into the rows right after it. Purging handles the label overlap exactly. The embargo length is a judgement you make from how long that dependence lasts, so Lacuna takes it as a number you choose and records it.

embargo on PurgedKFold and CombinatorialPurgedKFold is a non-negative integer count of distinct observation times, not rows and not calendar units. With a panel of 500 instruments and embargo=5, the five dates after the test block are removed for every instrument. It must be an int: both splitters check n_splits (or n_groups) and embargo at construction and raise a MethodContractError for a string such as "5D", a float, a bool or a NumPy integer.

Three details follow from the implementation:

  • The embargo applies after the last observation time of each test block, never before it. Rows before a test block are covered by purging only.
  • It removes rows that survived the purge. A row that was purged is reported as purged, not embargoed, so the embargoed count can be zero even with a positive embargo when the labels are long enough that purging already covers those dates. The 5-observation example in Supplying a split to the audit shows this.
  • The embargo counts the next embargo distinct times after the test block ends, and stops at the end of the data.

The Duration type, which accepts either an integer observation count or a string such as "3W", is used by WalkForward and is described there.

The PurgedKFold parameters

ParameterMeaning
n_splitsThe number of folds, at least 2 and no more than the number of distinct observation times. Every observation time is in the test set of exactly one fold. Default 5.
embargoThe number of distinct observation times to drop after each test block. Default 0, which applies no embargo.
use_nativeUse the compiled purge kernel when it is available, and fall back to the Python implementation otherwise. The folds are identical; the backend that ran is recorded in the evidence parameters. Default True.

Combinatorial purged k-fold

A single PurgedKFold run gives you one out-of-sample estimate per row, assembled from one particular partition of the history. Combinatorial purged cross-validation (CPCV) takes the other route: split the history into NN contiguous groups, hold out every combination of kk of them, and rebuild several complete out-of-sample paths from the pieces. You get a distribution of path-level results instead of a single number, which says something about how sensitive the result is to which stretch of history happened to be held out.

With NN groups and kk test groups per split there are

(Nk) splitsandφ=(N−1k−1) paths.\binom{N}{k} \text{ splits} \qquad\text{and}\qquad \varphi = \binom{N-1}{k-1} \text{ paths}.

Each group is in the test set of φ\varphi splits, so each group has φ\varphi different out-of-sample predictions, and path pp takes the pp-th of them for every group. Purging works as above, per split, against the union of its kk test groups. The embargo is applied after the last observation time of each held-out group.

import numpy as np

rng = np.random.default_rng(11)
n = 60
cpcv_labels = pl.DataFrame(
    {
        "observation_time": list(range(n)),
        "label_start": list(range(n)),
        "label_end": [t + 3 for t in range(n)],
    }
)
cpcv = lc.cv.CombinatorialPurgedKFold(n_groups=6, n_test_groups=2, embargo=1).split(cpcv_labels)
print(cpcv.evidence.metrics)
print(pl.DataFrame(cpcv.evidence.table("combinations")).head(4))
for path in cpcv.paths:
    print(path.path, path.fold_by_group)
{'n_groups': 6, 'n_combinations': 15, 'n_paths': 5, 'purged_observations': 80, 'embargoed_observations': 0}
shape: (4, 2)
┌──────┬─────────────┐
│ fold ┆ test_groups │
│ ---  ┆ ---         │
│ i64  ┆ list[i64]   │
╞══════╪═════════════╡
│ 0    ┆ [0, 1]      │
│ 1    ┆ [0, 2]      │
│ 2    ┆ [0, 3]      │
│ 3    ┆ [0, 4]      │
└──────┴─────────────┘
0 (0, 0, 1, 2, 3, 4)
1 (1, 5, 5, 6, 7, 8)
2 (2, 6, 9, 9, 10, 11)
3 (3, 7, 10, 12, 12, 13)
4 (4, 8, 11, 13, 14, 14)

Fifteen splits, five paths. fold_by_group says, for each of the six groups in chronological order, which split supplies that group’s predictions on this path. Group 0 appears in splits 0 to 4, so path 0 uses split 0 for group 0, path 1 uses split 1, and so on.

To score a path you fit one model per split, predict that split’s test rows, and then assemble each path from the splits it names. This sketch uses a deliberately trivial model, the mean of the training labels, to show the bookkeeping:

y = rng.normal(0.0, 1.0, n)
groups = pl.DataFrame(cpcv.evidence.table("groups"))

# One "model" per split: the mean of the training labels.
fold_prediction = [float(y[list(fold.train_indices)].mean()) for fold in cpcv.folds]

path_mse = []
for path in cpcv.paths:
    errors = []
    for row in groups.iter_rows(named=True):
        in_group = (
            (cpcv_labels["observation_time"] >= row["start"])
            & (cpcv_labels["observation_time"] <= row["end"])
        ).to_numpy()
        prediction = fold_prediction[path.fold_by_group[row["group"]]]
        errors.extend((y[in_group] - prediction) ** 2)
    path_mse.append(float(np.mean(errors)))
print([round(value, 3) for value in path_mse])
[0.85, 0.813, 0.841, 0.865, 0.843]

Every path covers each row exactly once, so the five numbers are five full-history out-of-sample estimates built from different splits. They are not independent of one another, because they share training rows.

CombinatorialSplitResult has folds, paths, evidence, fold_table, path_table and to_json(). Iterating it yields (train_indices, test_indices) pairs for each of the splits. A CPCVPath has path, fold_by_group and test_indices; the last is the same tuple for every path, namely all rows ordered by group and then by time. The evidence has four tables: groups (each group’s first and last time and its row count), combinations (the test groups of each split), folds and paths.

ParameterMeaning
n_groupsThe number of contiguous groups of distinct observation times, NN. At least 2, and no more than the number of distinct times. Default 6.
n_test_groupsHow many groups are held out in each split, kk, from 1 to N−1N-1. Default 2.
embargoDistinct observation times to drop after each held-out group. Default 0.
max_combinationsA safety limit on (Nk)\binom{N}{k}. The constructor raises if the count exceeds it. Raise it only when you intend to run that many fits. Default 10 000.
use_nativeAs for PurgedKFold. Default True.

CombinatorialPurgedKFold.split takes the same data, time, label_start and label_end arguments as PurgedKFold.split.

Walk-forward

WalkForward is the split that matches how a strategy is run live: train on the past, test on the next window, then move forward. In "expanding" mode the training set grows from the first observation. In "rolling" mode it is a fixed-length window that slides with the test window.

WalkForward has no label columns. It splits on observation time only and does not purge, so its purged_observations and embargoed_observations are always zero. If your labels look ahead by hh observations, the last h−1h-1 training observations carry labels that extend into the test window. Filter them out yourself (the example below does it) or use PurgedKFold.

Sizes are Duration values: either an integer count of distinct observation times, or a string made of a positive integer and a unit, "D" (days), "W" (weeks), "M" (months) or "Y" (years), in either case. String sizes are calendar spans, so on trading-day data "3W" holds about 15 observations, not 21, and a test window that contains no observations is skipped. The three must use the same convention. Strings need Date or Datetime times and are measured on the calendar from the first observation; a month is added with the day clamped to the end of shorter months. Note that D here means calendar days, whereas a "5D" label horizon in forward_returns means five observations.

from datetime import date, timedelta

dates = [date(2025, 1, 1) + timedelta(days=i) for i in range(60)]
series = pl.DataFrame(
    {
        "time": dates,
        "label_end": [d + timedelta(days=5) for d in dates],
    }
)

for mode in ("expanding", "rolling"):
    walk = lc.cv.WalkForward(train="3W", test="1W", step="1W", mode=mode).split(series)
    print(mode, [(len(f.train_indices), len(f.test_indices)) for f in walk.folds])
expanding [(21, 7), (28, 7), (35, 7), (42, 7), (49, 7)]
rolling [(21, 7), (21, 7), (21, 7), (21, 7), (21, 7)]

Both modes start the first test window three weeks after the first observation. The final test window must lie entirely inside the data, so the trailing days that do not fill a window are not tested. In calendar mode a window is kept only if the data fully cover it. Over Date times each observation covers its whole day, so a window whose exclusive end is one day past the last observation is kept and the last observation is tested, as it is with integer sizes. Over Datetime times an observation is an instant with no bar length, so the window’s exclusive end must be no later than the last observation, and a window that would end after it is dropped. Cast daily Datetime bars to Date to test the final window. Pass allow_incomplete=True to keep a shorter final window.

With "20D" training and "10D" test windows, the fourth test window covers the last of the 60 days and ends one day after it. That makes the difference between Date and Datetime times visible:

as_datetime = series.with_columns(pl.col("time").cast(pl.Datetime))
for label, frame in (("Date", series), ("Datetime", as_datetime)):
    walk = lc.cv.WalkForward(train="20D", test="10D", step="10D").split(frame)
    print(label, len(walk.folds), "last test day:", max(frame["time"][i] for i in walk.folds[-1].test_indices))
Date 4 last test day: 2025-03-01
Datetime 3 last test day: 2025-02-19 00:00:00

The leak across the train/test boundary is visible in the label ends:

walk = lc.cv.WalkForward(train="3W", test="1W", step="1W", mode="rolling").split(series)
for f in walk.folds[:2]:
    first_test_day = min(series["time"][i] for i in f.test_indices)
    reaching = [i for i in f.train_indices if series["label_end"][i] > first_test_day]
    print(f.fold, "training rows whose label reaches into the test window:", len(reaching))
0 training rows whose label reaches into the test window: 4
1 training rows whose label reaches into the test window: 4

Dropping those rows from train_indices before you fit is the manual equivalent of purging.

Integer sizes count distinct observation times, not rows, so a panel with several instruments per date still moves one date at a time. Here two instruments share each of 60 dates:

panel = pl.concat([series.select("time").with_columns(instrument=pl.lit(name)) for name in ("A", "B")])
integer = lc.cv.WalkForward(train=20, test=10, step=10).split(panel)
print([(len(f.train_indices), len(f.test_indices)) for f in integer.folds])
[(40, 20), (60, 20), (80, 20), (100, 20)]

The first fold trains on 20 dates, which is 40 rows, and tests on the next 10 dates, which is 20 rows.

ParameterMeaning
trainThe length of the first training window, as a Duration. In expanding mode, later folds keep the same start and grow.
testThe length of each test window.
stepHow far each fold’s test window moves from the previous one. A step equal to test gives non-overlapping test windows.
mode"expanding" (default) or "rolling".
allow_incompleteKeep a final test window that is shorter than test. Default False, which stops before it.

WalkForward.split(data, *, time="time") takes only the time column, whose default is "time" rather than "observation_time". It does not require sorted rows. If the configuration cannot produce any fold, for example a training window longer than the data, it raises a DataContractError.

Supplying a split to the audit

SignalStudy.audit has a check, PURGED_VALIDATION_SUPPLIED, that asks whether any validation split with interval-aware purging was used. Lacuna cannot know how you validated your model, so without a split the check is UNKNOWN, and you answer it by passing the split.

The study below uses a 5-observation horizon on a small synthetic panel.

from datetime import date, timedelta

instruments = ("A", "B", "C", "D", "E", "F")
days = (date(2025, 1, 2) + timedelta(days=n) for n in range(80))
sessions = [day for day in days if day.weekday() < 5][:40]

prices = pl.DataFrame(
    {
        "time": [s for _ in instruments for s in sessions],
        "instrument": [i for i in instruments for _ in sessions],
        "close": [
            100.0 + 4.0 * a + d * (0.3 + 0.05 * a) + 0.2 * ((d + a) % 3)
            for a in range(len(instruments))
            for d in range(len(sessions))
        ],
    }
)
signal = pl.DataFrame(
    {
        "time": [s for s in sessions for _ in instruments],
        "instrument": [i for _ in sessions for i in instruments],
        "signal": [
            float(((d + 2 * a) % 11) - 5)
            for d in range(len(sessions))
            for a in range(len(instruments))
        ],
    }
)
study = lc.SignalStudy(
    signal=signal,
    prices=prices,
    horizons=("5D",),
    signal_observed_at="open",
    entry="current_close",
    price_adjustment="total_return_adjusted",
    quantiles=5,
)


def purged_check(report):
    finding = next(f for f in report.findings if f.code == "PURGED_VALIDATION_SUPPLIED")
    return finding.state.value, finding.message


print(purged_check(study.audit(seed=1)))
('UNKNOWN', "required 'split' analysis evidence was not supplied")

Now build a PurgedKFold split from the study’s own labels and pass it in:

label_frame = study.labels().frame
purged = lc.cv.PurgedKFold(n_splits=5, embargo=2).split(label_frame)
print(purged.evidence.metrics)
print(purged_check(study.audit(seed=1, split=purged)))
{'n_folds': 5, 'purged_observations': 192, 'embargoed_observations': 0}
('PASS', 'A supplied validation split applied interval-aware purging. The split evidence does not identify its input, so this does not verify that it was built from the audited labels.')

The finding moves from UNKNOWN to PASS, and its evidence records the number of purged observations. The rule reads the method that produced the evidence and its purge count. Two things to know about what that PASS means:

  • Only a PurgedKFold or CombinatorialPurgedKFold result can pass. A WalkForward result is accepted but gives UNKNOWN (“the supplied split evidence does not establish purged validation”), because walk-forward does not purge. So does a split whose evidence reports no purge count.
  • It confirms that a purged split was supplied. Split evidence carries no input fingerprint, so the rule cannot verify that the split was built from this study’s labels, and the finding records data_identity_verified: False. It also cannot tell that your model was trained on its folds, or that the embargo is long enough. Those remain claims you are making.

The one consistency check is the purge count. When the inference horizon spans two or more observations ("5D", say) and the split purged nothing, the rule gives WARN, because consecutive labels of that horizon overlap and a split purged against them would have removed rows. A split of non-overlapping sampled labels legitimately purges nothing, and the rule cannot tell the two apart.

walk_forward = lc.cv.WalkForward(train=20, test=5, step=5).split(label_frame, time="observation_time")
print(purged_check(study.audit(seed=1, split=walk_forward)))
('UNKNOWN', 'The supplied split evidence does not establish purged validation.')

study.audit(split=...) accepts a SplitResult, a CombinatorialSplitResult or the .evidence of either, and the check recognizes both purged methods:

combinatorial = lc.cv.CombinatorialPurgedKFold(n_groups=5, n_test_groups=2, embargo=2).split(label_frame)
print(purged_check(study.audit(seed=1, split=combinatorial))[0])
PASS

See Supplying evidence for the other checks you can answer this way.

scikit-learn

Lacuna’s splitters return index arrays, which is what scikit-learn’s cross-validation protocol expects. lc.adapters.as_sklearn_cv wraps a splitter and a table into a SklearnCV object that any scikit-learn function taking cv= can use: cross_val_score, cross_validate, GridSearchCV and so on.

The example below builds a case where the right answer is known. The feature is a slow random series with no connection to prices, and the label is the 20-observation forward return of a random walk. Neither the feature nor the label has any information about the other, so a fair estimate of the model’s skill is at or below zero. The feature is strongly autocorrelated and neighbouring labels overlap, so in a shuffled k-fold every test row has training rows on both sides with nearly the same feature value and nearly the same label. A nearest-neighbour model can look up the answer from the row next door.

from sklearn.model_selection import KFold, cross_val_score
from sklearn.neighbors import KNeighborsRegressor

rows = []
for seed in (7, 8, 9, 10, 11):
    gen = np.random.default_rng(seed)
    n_obs = 600
    stamps = [date(2024, 1, 1) + timedelta(days=i) for i in range(n_obs)]
    close = 100 * np.exp(np.cumsum(gen.normal(0, 0.01, n_obs)))
    noise = gen.normal(size=n_obs)
    feature = np.empty(n_obs)
    feature[0] = noise[0]
    for i in range(1, n_obs):
        feature[i] = 0.97 * feature[i - 1] + noise[i]

    px = pl.DataFrame({"time": stamps, "instrument": "X", "close": close})
    fwd = lc.labels.forward_returns(px, horizon="20D", price_adjustment="total_return_adjusted")
    frame = fwd.frame.join(
        pl.DataFrame({"observation_time": stamps, "feature": feature}),
        on="observation_time",
    ).sort("observation_time")
    X = frame.select("feature").to_numpy()
    target = frame.get_column("forward_return").to_numpy()

    model = KNeighborsRegressor(n_neighbors=5)
    shuffled = cross_val_score(
        model, X, target, cv=KFold(5, shuffle=True, random_state=0), scoring="r2"
    )
    contiguous = cross_val_score(model, X, target, cv=KFold(5), scoring="r2")
    purged_cv = lc.adapters.as_sklearn_cv(lc.cv.PurgedKFold(n_splits=5, embargo=10), frame)
    honest = cross_val_score(model, X, target, cv=purged_cv, scoring="r2")
    rows.append(
        {
            "seed": seed,
            "shuffled": shuffled.mean(),
            "contiguous": contiguous.mean(),
            "purged": honest.mean(),
        }
    )

print(pl.DataFrame(rows).with_columns(pl.col(pl.Float64).round(3)))
print(purged_cv)
shape: (5, 4)
┌──────┬──────────┬────────────┬────────┐
│ seed ┆ shuffled ┆ contiguous ┆ purged │
│ ---  ┆ ---      ┆ ---        ┆ ---    │
│ i64  ┆ f64      ┆ f64        ┆ f64    │
╞══════╪══════════╪════════════╪════════╡
│ 7    ┆ 0.074    ┆ -0.205     ┆ -0.223 │
│ 8    ┆ -0.205   ┆ -0.531     ┆ -0.615 │
│ 9    ┆ -0.089   ┆ -0.254     ┆ -0.276 │
│ 10   ┆ -0.071   ┆ -1.048     ┆ -1.041 │
│ 11   ┆ -0.192   ┆ -0.759     ┆ -0.809 │
└──────┴──────────┴────────────┴────────┘
SklearnCV(n_splits=5, n_samples=580)

In every seed the shuffled estimate is the highest, and in the first it is positive for a feature that carries no information. Most of that gap comes from shuffling itself: contiguous folds, even without purging, already score close to the purged result here. Purging and the embargo then remove the remaining leak at the fold boundaries, where the last training labels overlap the first test labels. On this example that last step is small; it grows with the label horizon and with the number of folds, because there are more boundaries and each one leaks more rows.

All three scores are negative mostly because a random-walk return has a different average in each contiguous block, so even a model that predicts the training mean scores below zero on the next block. That is a property of the data, not of the splitter. The purged score is the one to believe.

SklearnCV computes the folds once, in the constructor. It freezes the row order, so the folds cannot change between estimator evaluations, and it keeps the original evidence:

print(purged_cv.get_n_splits(), purged_cv.evidence.metrics)
5 {'n_folds': 5, 'purged_observations': 152, 'embargoed_observations': 0}

Some points that follow from the implementation:

  • X and y must have the same number of rows as the table you passed to as_sklearn_cv; a different count raises a DataContractError. The fold indices refer to rows of that table, and Lacuna cannot check that X and y are in the same order as it, so build them from that table, as the example does.
  • The groups argument is rejected with a MethodContractError. Temporal splitters do not use it; encode grouping in the table instead.
  • The wrapper accepts a PurgedKFold, CombinatorialPurgedKFold or WalkForward instance. Anything else raises a MethodContractError.
  • The time argument defaults to "observation_time" for the purged splitters and "time" for WalkForward. label_start and label_end are ignored for WalkForward.
  • cross_val_predict needs the test sets to partition the data, so it works with PurgedKFold but not with WalkForward or CombinatorialPurgedKFold, where it fails with scikit-learn’s own cross_val_predict only works for partitions error. cross_val_score and GridSearchCV work with all three. For a combinatorial splitter the number of splits is the number of combinations.
  • Importing lacuna.adapters does not import scikit-learn. You install scikit-learn yourself, and the wrapper only follows its protocol.
ParameterMeaning
splitterA WalkForward, PurgedKFold or CombinatorialPurgedKFold instance.
dataThe table to split: the same one whose rows line up with your X and y.
timeThe observation-time column. None selects the splitter’s default.
label_startThe label start column, for the purged splitters.
label_endThe label end column, for the purged splitters.

What to report with a result

A cross-validated score is only as credible as the split that produced it. When you report one, state the splitter, n_splits or the walk-forward windows, the embargo and why it has that length, and the label horizon. split.evidence records all of it, including the purge and embargo counts, and split.to_json() serializes it for an experiment record or a reproducibility bundle.

The full signatures are in the API reference.