Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(quantlib): a timestamp label cannot end before it starts, as a positional one cannot (#1556)

Haozhe Wu250ef7461728
diff --git a/agent/src/quantlib/crossvalidation.py b/agent/src/quantlib/crossvalidation.py
index 0f8a07575..1e33f07a5 100644
--- a/agent/src/quantlib/crossvalidation.py
+++ b/agent/src/quantlib/crossvalidation.py
@@ -137,6 +137,14 @@ def _as_label_spans(
"label_end_times index must be unique and monotonically increasing"
)
ends = label_end_times.to_numpy()
+ # A NaT end is a label that resolves after the sample ends (the tail of
+ # ``index.shift(-h)``); searchsorted places it last, which purges the
+ # most. An end before its own start is an error here as in the
+ # positional branch -- the clip below would lift it without a word.
+ if (ends < starts.to_numpy()).any():
+ raise ValueError(
+ "a label cannot end before the observation it belongs to starts"
+ )
# searchsorted on the start index converts label end *times* into label
# end *positions*; the right insertion point minus one keeps a label
# that ends between two observations attached to the earlier one.
diff --git a/agent/tests/quantlib/test_crossvalidation.py b/agent/tests/quantlib/test_crossvalidation.py
index 2111a850e..1fe27f48a 100644
--- a/agent/tests/quantlib/test_crossvalidation.py
+++ b/agent/tests/quantlib/test_crossvalidation.py
@@ -15,6 +15,7 @@ from src.quantlib.crossvalidation import (
DEFAULT_EMBARGO_FRACTION,
MIN_FOLDS,
Split,
+ _as_label_spans,
combinatorial_purged_splits,
detect_boundary_leakage,
group_purged_kfold_splits,
@@ -396,3 +397,19 @@ def test_timestamp_label_index_must_be_ordered_and_unique():
ends = pd.Series(duplicate, index=duplicate)
with pytest.raises(ValueError, match="unique"):
list(purged_kfold_splits(len(duplicate), ends, n_folds=2))
+
+
+
+def test_a_timestamp_label_cannot_end_before_it_starts():
+ """The positional branch rejected this; the Series branch clipped it to its start."""
+ index = pd.date_range("2024-01-01", periods=4)
+ ends = pd.Series([index[1], index[0], index[3], index[3]], index=index)
+ with pytest.raises(ValueError, match="cannot end before"):
+ list(purged_kfold_splits(len(index), ends, n_folds=2))
+
+
+def test_a_nat_label_end_purges_through_the_last_observation():
+ """NaT is the tail of ``shift(-h)``: a label resolving after the sample ends."""
+ index = pd.date_range("2024-01-01", periods=4)
+ ends = pd.Series([index[1], pd.NaT, index[3], index[3]], index=index)
+ assert _as_label_spans(ends).tolist() == [1, 3, 3, 3]