Panel Data Cross-Validation with Temporal Embargo
Machine LearningModel answerLast updated
Design a time-series CV splitter for panel data that prevents entity leakage across train/test sets using an embargo period and supports geographic holdout folds.
You're building a cross-validation strategy for a financial forecasting model that uses panel data with loans tracked across multiple metropolitan areas over time.
Your task is to design and implement a cross-validation splitter with these specifications:
Input: A DataFrame with columns loan_id, msa (metropolitan statistical area), and month.
Requirements:
-
Expanding-window folds: Create 5 folds with increasing time cutoffs. For fold k, training data should include all months up to cutoff k minus an embargo period, and test data should span from the embargo boundary to the next cutoff.
-
Embargo mechanism: Use a 90-day embargo to prevent information leakage. Any loan appearing in the test set must be completely removed from training data within that embargo window—this handles the same entity appearing at different times.
-
Geographic holdout: In at least one fold, hold out an entire MSA's data for testing while maintaining temporal ordering within each region.
-
Determinism: The splitter must produce identical results regardless of input row order.
-
Algorithm specification: Provide the complete algorithm with time/space complexity analysis in terms of N (rows), G (number of MSAs), and K (folds).
-
Testing strategy: Describe comprehensive unit tests covering adversarial scenarios: duplicate timestamps, gaps in the time series, loans that move between MSAs, and heavily imbalanced geographic distributions.
What matters: preventing both temporal leakage (future information bleeding into training) and entity leakage (the same loan in both sets during overlapping periods).
Hints
Hint 1
Think about how to achieve determinism when the input might arrive in any order—what canonical ordering would work?
Hint 2
The embargo operates on entities (loan_id), not just time windows. How do you ensure a loan in the test set is fully purged from nearby training periods?
Hint 3
For the geographic holdout fold, consider which MSA to select deterministically and how to exclude it from training while still respecting the time boundaries.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem combines three cross-validation challenges: time-series ordering, panel data with repeated entities, and grouped holdouts. The key insight is that we need two layers of protection: temporal boundaries to prevent future leakage, and entity-based purging to prevent the same loan from appearing in both sets.
Algorithm Design
Step 1: Canonical Ordering
To guarantee determinism under arbitrary input shuffling, establish a total ordering:
- Sort by
(month, msa, loan_id, index_label)using a stable sort - This creates a canonical representation where any permutation of input rows produces identical results
- Store original index labels since those survive all transformations
Step 2: Compute Time Cutoffs
- Extract unique months and sort them:
M = [m₁, m₂, ..., m_U] - Require at least K+1 distinct months
- Compute cutoffs using quantiles:
cutoff_k = M[⌊k·U/(K+1)⌋ - 1]for k = 1..K - Define final boundary as
cutoff_{K+1} = M[U-1] - This ensures strictly increasing cutoffs even with duplicate timestamps within months
Step 3: Generate Each Fold
For fold k:
-
Initial temporal split:
- Training:
month ≤ cutoff_k - embargo(expanding window from beginning) - Testing:
cutoff_k - embargo < month ≤ cutoff_{k+1}
- Training:
-
Geographic holdout (if applicable):
- Select one fold (typically the last, which has maximum training history)
- Choose holdout MSA deterministically: most rows, breaking ties by lexicographic order
- Restrict test set to that MSA only
- Remove that MSA from all training data (not just the fold's training window)
-
Entity-based purging:
- Collect all
loan_idvalues present in the test set - Remove any training row whose
loan_idappears in that collection - This handles loan migration across MSAs and prevents entity leakage
- Collect all
-
Validation:
- Verify train and test are both non-empty
- Return index labels in canonical order
Why This Works
Temporal safety: Training months are bounded by cutoff_k - embargo, test months start strictly after that boundary. No training data comes from the test period's future.
Entity safety: The purging step operates on loan_id after geographic filters are applied, creating a guaranteed-empty intersection between train and test loan sets.
Migration handling: When a loan moves between MSAs, purging by loan_id catches all instances across all regions.
Geographic isolation: In the holdout fold, the held-out MSA contributes zero training rows at any time period, while still respecting temporal boundaries within that MSA's test data.
Complexity Analysis
Time:
- Canonical sort: O(N log N)
- Unique month extraction: O(N)
- MSA counting for holdout selection: O(N + G log G)
- Per-fold operations (K times):
- Boolean masking: O(N)
- Hash-based set membership for purging: O(N)
- Total: O(N log N + K·N + G log G)
Space:
- Working frame with canonical order: O(N)
- Boolean masks per fold: O(N)
- Test loan set: O(N) worst case
- Using generator pattern (yield): O(N) peak memory
- Materializing all folds simultaneously would be O(K·N)
Optimization: Convert loan_id and msa to categorical dtype, storing as int32 codes. This accelerates comparisons and reduces memory for high-cardinality columns.
Implementation
import numpy as np
import pandas as pd
def panel_timeseries_cv(df, n_folds=5, embargo_days=90,
holdout_fold_idx=None, holdout_msa=None):
"""
Generate train/test index splits for panel data with temporal embargo.
Yields: (fold_number, train_indices, test_indices)
Indices are from df.index in canonical order.
"""
# Validate inputs
required_cols = {"loan_id", "msa", "month"}
if not required_cols.issubset(df.columns):
raise ValueError(f"Missing required columns: {required_cols - set(df.columns)}")
if not df.index.is_unique:
raise ValueError("DataFrame must have unique index")
if n_folds < 1:
raise ValueError("n_folds must be >= 1")
# Build canonical frame
month_normalized = pd.to_datetime(df["month"]).dt.to_period("M").dt.to_timestamp()
canonical = pd.DataFrame({
"idx": df.index,
"loan": df["loan_id"],
"msa": df["msa"],
"month": month_normalized,
}).sort_values(["month", "msa", "loan", "idx"],
kind="stable", ignore_index=True)
# Compute cutoffs from distinct months
unique_months = np.sort(canonical["month"].unique())
n_months = len(unique_months)
if n_months < n_folds + 1:
raise ValueError(f"Need >= {n_folds + 1} distinct months, have {n_months}")
cutoffs = []
for k in range(1, n_folds + 1):
cutoff_idx = (k * n_months) // (n_folds + 1) - 1
cutoffs.append(unique_months[cutoff_idx])
cutoffs.append(unique_months[-1]) # final boundary
# Determine geographic holdout
if holdout_fold_idx is None:
holdout_fold_idx = n_folds - 1
if holdout_msa is None:
msa_counts = canonical["msa"].value_counts()
holdout_msa = msa_counts.index[0] # most frequent, ties broken by pandas sort
embargo = pd.Timedelta(days=embargo_days)
# Generate folds
for k in range(n_folds):
embargo_line = cutoffs[k] - embargo
train_mask = (canonical["month"] <= embargo_line).values
test_mask = ((canonical["month"] > embargo_line) &
(canonical["month"] <= cutoffs[k + 1])).values
# Apply geographic holdout
if k == holdout_fold_idx:
is_holdout = (canonical["msa"] == holdout_msa).values
test_mask = test_mask & is_holdout
train_mask = train_mask & ~is_holdout
# Entity purging
test_loans = canonical.loc[test_mask, "loan"].unique()
train_mask = train_mask & ~canonical["loan"].isin(test_loans).values
if not train_mask.any() or not test_mask.any():
raise ValueError(f"Fold {k}: empty train or test set")
train_indices = canonical.loc[train_mask, "idx"].values
test_indices = canonical.loc[test_mask, "idx"].values
yield k, train_indices, test_indices
Testing Strategy
Create a test harness that validates these invariants on every fold:
Invariant checks:
- No temporal overlap:
max(train_months) <= cutoff_k - 90 days < min(test_months) - No entity overlap:
set(train_loans) ∩ set(test_loans) = ∅ - No duplicate indices within or between sets
Test case 1: Duplicate timestamps
- Create 100 rows with the same
(loan_id, month)but different index values - Verify: All land on the same side of each split
- Verify: All rows preserved with distinct indices
Test case 2: Irregular time gaps
- Build panel with months [Jan, Feb, Mar, Sep, Oct, Nov] (6-month gap)
- Verify: Embargo still computed in calendar days, not month counts
- Verify: Cutoffs span the gaps correctly
Test case 3: Loan migration
- Loan starts in MSA_A (months 1-3), moves to MSA_B (months 4-6)
- In a fold where months 4-6 are in test
- Verify: All rows for that loan removed from training, regardless of MSA
Test case 4: Imbalanced MSAs
- 90% of rows in one MSA, 10% across five others
- Verify: Holdout fold selects the dominant MSA deterministically
- Verify: Train set still has reasonable size after geographic exclusion
Test case 5: Shuffled input
- Run CV twice: once with original order, once with random permutation
- Verify: Identical train/test indices returned (order-independent)
Test case 6: Edge counts
- Exactly K+1 distinct months (minimum viable)
- Verify: No cutoff collisions, all folds valid
Common Mistakes
-
Purging only by time window: This misses loans that appear in both sets at different times within the embargo radius.
-
Row-count quantiles for cutoffs: Dense months would collapse multiple cutoffs into one timestamp. Always use distinct month quantiles.
-
Geographic holdout applied only to test window: The held-out MSA must be removed from training data at all time periods, not just near the fold's cutoff.
-
Mutable state in generator: Reusing arrays across folds can cause subtle bugs. Always create fresh masks per iteration.
-
Ignoring migration: Loans can change MSAs. Entity purging must operate on
loan_idglobally, not within-MSA.