Validating Modeling Assumptions and Preventing Data Leakage

Medium · Analytics & Experimentation · Software Engineer · Technical Screen

Prompt

Choose a quantitative, analytics, or machine-learning project you have built and walk through its end-to-end empirical rigor:

  1. Core assumptions & rationale: State the primary statistical and engineering assumptions behind your approach and why each was reasonable to adopt initially.
  2. Falsifiable verification: Detail how you tested every assumption quantitatively—for instance through exploratory diagnostics, perturbation checks, feature/module removals, or chronological out-of-sample splits.
  3. End-to-end workflow & safeguards: Trace the pipeline from raw data ingestion through final holdout scoring, specifying the structural controls you used to eliminate lookahead leakage and curb overfitting.

Scope & Expectations

  • Distinguish empirical claims about real-world data behavior from code-level pipeline invariants enforced by timestamps and unit tests.
  • Connect each assumption to a concrete, falsifiable test and explain what outcome would have triggered a redesign.
  • Walk chronologically through raw snapshot archival, point-in-time feature/label construction, simple domain baselines, nested validation, and single-use holdout scoring.
  • Cover structural defenses against time-series/panel leakage (in-fold preprocessing, purging overlapping horizons, survivorship-free universes) alongside both model-level and researcher trial-budget overfitting controls.

Step-by-step walkthrough

  1. Frame the question and set up a concrete project

    Note: in a live interview you will anchor this answer in a specific project from your own resume. This walkthrough uses a concrete illustrative forecasting project so every check, split date, and formula can be shown with real numbers; swap in the facts from your own project when answering live.

    Interviewers ask this question to test three engineering and scientific habits:

    • Naming hidden assumptions: instead of treating your model as obviously valid, you can list what has to be true about the world and about your data for the model to work.
    • Designing falsifiable checks: every assumption is paired with a concrete test whose result could actually prove the assumption wrong—not just a plausible story.
    • Preventing leakage and overfitting by construction: your code and data splits make cheating structurally impossible rather than relying on everyone "being careful."

    Illustrative project used below. We want to forecast next-day price volatility across 40 liquid futures contracts (standardized exchange-traded contracts on equity indices, government bonds, currencies, and commodities) to size trading positions: on calm days the portfolio holds larger positions, and on turbulent days it scales positions down (position ~ target_risk / forecast_risk).

    • Raw data: 1-minute price bars from 2012 to 2023.
    • Target: next trading day's realized variance (RV), a measure of how much a contract's price actually bounced around during the day, computed by summing squared 5-minute percentage returns across the regular trading session.
    • Baseline: the HAR-RV model (Heterogeneous Autoregressive model), a classic 3-variable linear regression that predicts tomorrow's log RV from the average log RV over the past day, past week (5 trading days), and past month (22 trading days).
    • Candidate model: a gradient-boosted decision tree model trained jointly across all 40 contracts, adding overnight returns, yesterday's return sign, and a calendar of pre-scheduled macroeconomic announcements (such as central-bank rate decisions and inflation releases).
  2. List key assumptions and separate world claims from code claims

    A strong answer groups assumptions into claims about the world (which require statistical evidence from data) and claims about your own pipeline (which require code audits and automated unit tests). Pointing out this distinction immediately tells the interviewer you think like both a scientist and a software engineer.

    ID  Assumption                                    Why it was justified before testing
    --  --------------------------------------------  ----------------------------------------------------
    A1  Volatility is persistent: recent RV helps     Calm days tend to follow calm days and stormy days
        predict tomorrow's RV.                        follow stormy days ("volatility clustering").
    
    A2  5-minute RV is an accurate proxy for true     1-second prices bounce between bid and ask quotes
        daily variance.                               ("microstructure noise"); hourly bars are too coarse.
                                                      5 minutes is the standard middle ground.
    
    A3  Feature-to-target relationships stay stable   Institutional risk limits, trading hours, and macro
        enough over time to learn from past years.    release schedules change slowly over years.
    
    A4  Once RV is on a log scale, all 40 contracts   Pooling multiplies training rows per parameter by
        share similar dynamics and one pooled model   40x and regularizes noisy individual contracts.
        can serve all of them.
    
    A5  Every feature used for day t's forecast was   Forecasts run after day t's market close using only
        genuinely known at the close of day t.        bars and schedules published by that timestamp.
    

    A1 through A4 are empirical hypotheses about markets, so data could refute any of them. A5 is an invariant of our codebase, so we enforce it with timestamps and automated tests.

  3. Validate each assumption with a check that could fail

    Pair each assumption with the simplest quantitative check capable of disproving it, and state both what you ran and what number came back.

    • A1 — Exploratory data analysis (EDA) (plotting and summarizing raw data before modeling). Compute autocorrelation, the correlation between a series today and the same series shifted back by k days (lag k). Across our 40 contracts, the median daily log-RV autocorrelation was 0.70 at lag 1 and still 0.40 at lag 22 (one trading month). Had it been near 0.0, past volatility would carry no linear signal and we would stop before building complex models.
    • A2 — EDA plus sensitivity analysis (re-running the workflow after varying one modeling choice to check whether conclusions flip). First, plot average RV across different bar lengths (a volatility signature plot) to see where bid-ask bounce stops inflating the sum of squared returns:

    text Sampling interval 1 min 2 min 5 min 10 min 30 min Mean RV / 5-min RV 1.18 1.07 1.00 0.99 0.98

    The curve flattens from 5 minutes onward, confirming that 1-minute bars are inflated by `18%` bid-ask bounce while 5- and 10-minute bars agree. Second, retrain and re-evaluate the entire pipeline using 10-minute RV as the target: the improvement over the HAR baseline moved only slightly from `7.5%` to `7.1%` and the ranking of models did not change.
    
    • A3 — Rolling out-of-sample (walk-forward) tests (training on data up to year Y, testing on year Y + 1, and stepping forward one year at a time). Across the five validation years 2016–2020, the percentage change in loss relative to HAR (negative means lower error) was -6.6%, -8.8%, -7.5%, -9.9%, and -4.7% (mean -7.5%). Winning in all five years—including the 2020 pandemic shock—is far stronger evidence of stability than one -35% outlier year plus four flat years. A window-length sensitivity check comparing rolling 3-year, rolling 5-year, and expanding training windows differed by less than 1%, so we kept the expanding window.
    • A4 & features — Ablation study (adding or removing one component at a time while holding everything else fixed). Pooling HAR across all 40 contracts beat fitting 40 separate HAR models by 1.0% overall and never hurt any asset class (equities, rates, FX, energy, metals) by more than 0.5%. Adding feature groups one by one (and verifying by dropping each group from the full model) showed consistent incremental gains:

    text Model (walk-forward 2016-2020) Mean QLIKE vs. HAR baseline ------------------------------------------ ---------- ---------------- Random walk (tomorrow's RV = today's RV) 0.262 +31.0% HAR-RV, separate model per contract 0.200 - HAR-RV, pooled across 40 contracts 0.198 -1.0% Boosted trees, HAR features only 0.196 -2.0% + overnight return and yesterday's sign 0.190 -5.0% + pre-scheduled macro event calendar 0.185 -7.5%

    • A5 — Point-in-time audit. Every feature table stores an available_at timestamp alongside the market close_at timestamp; the feature builder rejects any join where available_at > close_at, backed by the automated truncation test in Step 5.
  4. Walk through the pipeline from raw data to final evaluation

    Describe the pipeline in strict chronological order so the interviewer can see where raw data ends, where tuning happens, and why the final test set stays untouched until the end:

    1. Ingest immutable snapshots: archive raw 1-minute bars, contract expiration/roll metadata, and original publication dates of macro calendars with ingestion timestamps so any run is reproducible bit-for-bit.
    2. Clean within single contracts: restrict to regular session hours, flag extreme ticks for inspection rather than silently dropping real market crashes, and compute percentage returns strictly inside one contract. When trading rolls from a March contract to a June contract, the price gap between March and June is a difference between two delivery dates, not a market return.
    3. Construct point-in-time features and labels: for sample day t, compute features strictly from bars up to day t's close and pair them with day t + 1's realized variance.
    4. Split strictly by calendar date:

    text 2012 ............ 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 ...... 2023 initial training | walk-forward validation folds | locked final test (4 years) | (expanding train, 1 test yr each)| (evaluated ONCE)

    1. Fit simple baselines first: evaluate both a naive random walk (forecast = today's RV) and HAR-RV across all validation folds before writing any tree model.
    2. Tune inside nested walk-forward folds: select hyperparameters and feature sets using only 2012–2020 walk-forward folds.
    3. Freeze and run once on the locked test: retrain the single chosen configuration on 2012–2020 and evaluate exactly once on 2021–2023.
    4. Report statistical and economic results: report loss metrics, statistical significance, breakdowns by year and asset class, and a portfolio check (how closely volatility-sized positions hit their target risk).
  5. Prevent data leakage structurally with point-in-time tests and purging

    Data leakage happens whenever information that did not exist at forecast time t sneaks into features, preprocessing, asset selection, or training labels. Guard every leakage channel in code:

    • Feature lookahead (such as a centered rolling average, a shift(-1) typo, or normalizing with a full-sample mean). Write a unit test that checks two invariants for any day t: removing all rows after t gives the exact same feature vector, and replacing future rows after t with extreme numbers also leaves day t's features unchanged.

    ```python import numpy as np

    def har_features(log_rv: np.ndarray, t: int) -> np.ndarray: """Build [daily, weekly, monthly] log-RV features at close of day t.""" if t < 21: raise ValueError("Need at least 22 days of history (t >= 21)") daily = log_rv[t] weekly = log_rv[t - 4 : t + 1].mean() # 5 days: t-4 .. t monthly = log_rv[t - 21 : t + 1].mean() # 22 days: t-21 .. t return np.array([daily, weekly, monthly])

    def check_no_lookahead(feature_fn, series: np.ndarray, t: int) -> None: """Verify feature_fn at index t never reads indices > t.""" from_full = feature_fn(series, t) from_truncated = feature_fn(series[: t + 1], t)

      corrupted = series.copy()
      corrupted[t + 1 :] = 999_999.0
      from_corrupted = feature_fn(corrupted, t)
    
      assert np.allclose(from_full, from_truncated), f"t={t} changed on truncation"
      assert np.allclose(from_full, from_corrupted), f"t={t} read future values"
    

    ```

    A buggy centered window like `log_rv[t - 2 : t + 3].mean()` or a full-sample z-score `(log_rv[t] - log_rv.mean()) / log_rv.std()` fails `check_no_lookahead` immediately.
    
    • Overlapping multi-day labels (purging and embargo). When predicting h days ahead (say h = 5, average RV over days t + 1 .. t + 5), the last h - 1 training rows right before a test split have targets that reach into the test period. Purging deletes those overlapping training rows. Suppose the first test forecast is made at day t = 1000 (predicting days 1001..1005):

    text Sample t Features use Target label uses days Safe for training before t=1000? -------- ------------ ---------------------- -------------------------------- t = 995 <= 995 996, 997, 998, 999, 1000 YES (all known by close of 1000) t = 996 <= 996 997, 998, 999, 1000, 1001 NO -> PURGE (uses day 1001) ... ... ... NO -> PURGE t = 999 <= 999 1000, 1001, ..., 1004 NO -> PURGE t = 1000 <= 1000 1001, 1002, ..., 1005 First test sample

    For `h = 1`, sample `t = 999` uses label day `1000`, which is already finished when we forecast at close of day `1000`, so `0` rows need purging. (If you ever use blocked k-fold cross-validation where training folds also come *after* a test block, also add an **embargo**: drop the first 22 training rows after the test block whose 22-day rolling features still contain test-period days.)
    

    python def walk_forward_folds(n_samples: int, first_test: int, test_len: int, horizon: int): """Yield (train_indices, test_indices) with overlapping multi-day labels purged.""" folds = [] test_start = first_test while test_start + test_len <= n_samples: # Sample t's label spans days t + 1 .. t + horizon; all must be <= test_start last_safe_train = test_start - horizon train_idx = range(21, last_safe_train + 1) test_idx = range(test_start, test_start + test_len) folds.append((train_idx, test_idx)) test_start += test_len return folds

    • In-fold preprocessing, point-in-time universe, and date splits:
      • Fit outlier clip bounds, missing-value imputers, and scalers inside each training fold only, then apply those frozen thresholds to the test fold.
      • Prevent survivorship bias (picking items based on who succeeded or survived at the end of the dataset): define the "liquid contracts" universe at each historical date using only prior trading volume, and keep delisted or expired contracts in the history.
      • Never use back-adjusted continuous price levels (stitched price series that shift historical prices using roll gaps from future years) to compute percentage returns or level features; compute returns strictly inside each individual contract.
      • Split by calendar date across all contracts at once, never by shuffling rows randomly—random splits put the same market crash day into training on 30 contracts and into testing on the other 10.
  6. Guard against both model overfitting and researcher overfitting

    Overfitting happens at two levels: the model memorizing training noise, and the researcher memorizing validation noise by trying too many ideas.

    • Model-level guards: start from a domain baseline that is hard to beat (HAR-RV captures most linear persistence with 3 weights), keep the feature list compact and economically motivated, regularize trees (shallow depth 4–6, high minimum samples per leaf, small learning rate), and run early stopping on an inner chronological validation slice at the tail of each training window—never on the test fold.
    • Nested walk-forward tuning: choose hyperparameters on inner time splits inside 2012..Y-1 before scoring on outer validation year Y, so the outer score honestly reflects the tuning process.
    • Prefer flat optima over sharp spikes: pick hyperparameter settings where neighboring values (say tree depth 4, 5, and 6) all score within 0.5% of each other; a lone sharp peak usually vanishes out of sample.
    • Budget and log researcher trials (multiple-testing bias). Even if 200 model variations all have zero true edge over HAR, random measurement noise (s = standard error of a fold score) makes the best-looking trial appear to win by roughly 2.75 * s:

    ```python import numpy as np

    rng = np.random.default_rng(0) # Simulate 20,000 experiments, each picking the best of 200 pure-noise models best_of_200 = rng.standard_normal((20_000, 200)).max(axis=1) print(round(best_of_200.mean(), 2)) # 2.75 standard errors by luck alone ```

    If each validation score has a standard error of `s = 0.5%`, picking the winner out of 200 useless configurations manufactures an illusory improvement of about `2.75 * 0.5% = 1.38%` (`~1.4%`) from luck alone. Logging every experiment, keeping the search grid small, requiring gains well above that noise floor, and holding back the `2021–2023` locked test set until the very end keeps us honest.
    
  7. Evaluate once on the locked test set and report uncertainty

    • Choose a loss function aligned with the downstream decision. We evaluate forecasts with QLIKE loss, defined as L(rv, f) = (rv / f) - ln(rv / f) - 1, where rv is realized variance and f is the variance forecast (L = 0 when f == rv). QLIKE has two major advantages: first, it ranks competing models accurately even when 5-minute RV is a noisy proxy for true variance; second, it penalizes underestimating risk more heavily than overestimating it:

    text True rv = 4, forecast f = 2 (risk underestimated by 2x): 4/2 - ln(2) - 1 = 0.307 True rv = 4, forecast f = 8 (risk overestimated by 2x): 4/8 - ln(0.5) - 1 = 0.193

    Underestimating variance by `2x` costs `1.59x` as much loss (`0.307 / 0.193`) as overestimating by `2x`, matching our trading risk where underestimated volatility leads to dangerously oversized positions.
    
    • Locked test result (2021–2023, 750 trading days). Mean QLIKE was 0.188 for the boosted-tree model versus 0.200 for HAR—a 6.0% out-of-sample improvement, compared with 7.5% in the 2016–2020 validation folds. Seeing a modest 1.5 percentage-point shrinkage from validation to locked test is normal after model selection; a collapse near 0% would have flagged validation overfitting.
    • Test statistical significance without inflating sample size. Do not treat 40 contracts * 750 days = 30,000 contract-days as independent samples, because all 40 markets react to shared daily macro shocks. Instead, average the loss improvement across the 40 contracts on each day t to get 750 daily differences d_t = L_HAR,t - L_model,t, and run a Diebold-Mariano test (a paired z-test comparing two forecast series' daily losses) using Newey-West (HAC) standard errors (an adjustment that accounts for day-to-day autocorrelation in d_t):

    text Mean daily gain: mean(d_t) = 0.200 - 0.188 = 0.012 Daily std dev: sd(d_t) = 0.100 Autocorrelation inflation factor (HAC / plain variance) = 1.5 Standard error: SE = sqrt(1.5 * 0.100^2 / 750) = 0.00447 Diebold-Mariano z: DM = 0.012 / 0.00447 = 2.68 -> two-sided p = 0.007

    • Concise spoken wrap-up for the interview: "In our futures volatility project, we wrote down five explicit assumptions—persistence, 5-minute RV proxy quality, stability across years, cross-contract poolability, and point-in-time feature availability—and paired each with a check that could fail: lag autocorrelations, a sampling-interval signature plot plus a 10-minute sensitivity rerun, year-by-year walk-forward splits, feature and pooling ablations, and automated lookahead truncation tests. Our pipeline computed returns strictly within single contracts, fitted all preprocessing inside chronological folds with label purging, logged our tuning trial budget, and touched the 2021–2023 locked test once, beating the HAR baseline by 6.0% in QLIKE (p = 0.007 after clustering by day and adjusting for autocorrelation)."

Intuition & how it works

Think of building a data or machine learning pipeline like building a highway bridge. Before pouring concrete, engineers write down what they are assuming about the ground ("bedrock sits 10 meters down"), the weather ("wind gusts stay below 150 km/h"), and their own blueprints ("every measurement uses metric units"), and they drill core samples or run stress tests that could disprove each assumption before opening day. In technical interviews, interviewers are not looking for a project whose assumptions were magically 100% perfect; they want to see that you named what could break, tested each assumption quantitatively, and structured your code so future data could never leak into past predictions.

The naive answer most candidates give—"we cleaned the dataset, ran an 80/20 random train/test split, tuned hyperparameters with cross-validation, and beat a basic baseline"—fails badly on real-world sequential data. Random splits place tomorrow's market shock into yesterday's training set, computing normalization constants on the whole table leaks future ranges, and trying 200 model ideas on one validation set manufactures a fake "winner" purely through multiple-testing luck.

Walk through a tiny 5-day timeline (Day 1 to Day 5) to see how a leak-proof workflow operates:

  • Point-in-time features: when predicting after Day 3's close, feature code is tested on a truncated array Days[1..3] to guarantee it cannot peek at Day 4 or Day 5.
  • Purging overlapping targets: if each row predicts a 2-day average (t + 1 and t + 2) and the test fold starts at Day 4 (predicting Days 5..6), training row Day 3 uses target Days 4..5, which overlaps the test period—so purging drops Day 3 and trains only up to Day 2 (target Days 3..4).
  • Assumption checks before tuning, locked test once at the end: simple domain baselines and year-by-year walk-forward validation (training on past years, testing on the next unseen year) verify stability and ablations first, and a locked final holdout period is evaluated exactly once after all modeling choices are frozen.

Key points

  • Separate world assumptions from code assumptions. Empirical claims about the world—such as persistence (past values predict future values), proxy accuracy, stability over time, and poolability across items—require statistical checks on data; pipeline claims like "every feature was known at prediction time" require timestamp audits and automated unit tests.
  • Pair every assumption with a falsifiable test:
    • Exploratory data analysis (EDA) (plotting and summarizing raw data before modeling), such as checking autocorrelation (correlation between today's value and values k days ago) and a sampling-interval signature plot.
    • Sensitivity analysis (re-running the pipeline after changing an arbitrary modeling choice, such as 5-minute vs. 10-minute bars or rolling vs. expanding windows, to confirm conclusions stay intact).
    • Ablation studies (adding or removing one feature group or pooling choice at a time while holding everything else fixed to isolate each component's real lift).
    • Walk-forward (rolling out-of-sample) validation across multiple consecutive years so one lucky regime cannot disguise four flat years.
  • Enforce leakage prevention structurally in code:
    • Run an automated no-lookahead unit test verifying that features at index t stay identical when rows > t are sliced off or overwritten with extreme numbers.
    • Purge training samples whose multi-day target window (t + 1 .. t + h) spills past the test split boundary (h - 1 rows dropped right before the split), and add an embargo (dropping rows right after a test block whose rolling lookback features still include test days) whenever training folds also follow test blocks.
    • Fit scalers, outlier clippers, and imputers strictly inside each training fold, define item universes point-in-time to avoid survivorship bias (selecting only items that survived to the end of the dataset), compute returns inside single contracts, and split strictly by date.
  • Defend against both model and researcher overfitting: benchmark against a strong domain baseline like HAR-RV (a 3-feature linear regression on daily, weekly, and monthly average log variance), tune inside nested walk-forward folds, favor flat optima (settings whose neighbors perform similarly), log every trial (the best of 200 pure-noise trials looks ~2.75 standard errors better by luck alone), and touch the locked final test set once.
  • Align the metric with business risk and report honest standard errors: QLIKE loss (rv / f - ln(rv / f) - 1) penalizes 2x underestimated variance 1.59x more than 2x overestimated variance, and a Diebold-Mariano test (a paired test on daily loss differences averaged across contracts each day) with Newey-West (HAC) variance (an adjustment for day-to-day serial correlation) prevents shared daily shocks from inflating significance.

Common mistakes

  • Stating assumptions without falsifiable tests, or naming vague activities ("we did EDA") without reporting the threshold or metric that would have rejected the assumption.
  • Using random k-fold splits on time-series or panel data. Neighboring days and cross-sectional items on the same date share shocks, letting the model memorize the test day's environment.
  • Fitting normalization, outlier clipping, or feature selection on the full dataset before splitting into train and test folds.
  • Peeking at the "final" test set repeatedly after tweaking features or hyperparameters, which silently turns the test set into another overfit validation fold.
  • Comparing only against a straw-man baseline. Beating a naive random walk by 30% sounds impressive until a 3-variable linear baseline (HAR-RV) captures almost all of that gap on its own.
  • Selecting today's top assets or users and backtesting them over the past decade, introducing survivorship and lookahead bias into the sample universe.
  • Exponentiating a log-scale forecast without Jensen's inequality bias correction. If log(RV) errors are roughly normal with standard deviation sigma = 0.5, then E[RV] = exp(sigma^2 / 2) * exp(E[log RV]) = exp(0.125) * exp(forecast) = 1.133 * exp(forecast), so naive exp(forecast) underpredicts variance by about 12% (1 - 1 / 1.133) and systematically oversizes risk.
  • Treating 40 contracts * 750 days = 30,000 observations as independent in p-value calculations, ignoring both cross-asset correlation on the same day and autocorrelation across consecutive days.
  • Reporting a single pooled headline number without breaking performance down by year and segment to check whether one unusual regime drove the entire average.

Follow-up questions

  • How would you choose between an expanding training history and a fixed-width sliding window? An expanding window keeps every historical year from the start of the dataset, which reduces parameter variance by giving trees more samples, whereas a fixed sliding window (say the latest 3 or 5 years) drops stale market regimes so the model adapts faster after structural shifts. Instead of guessing, treat window type as a pipeline choice evaluated across the walk-forward validation folds: in our example, sliding 3-year, sliding 5-year, and expanding windows scored within 1% of one another, so we chose the expanding window for lower variance. A practical middle ground in production is an expanding window with exponential sample-weight decay so recent years carry more weight without throwing older crises away completely.
  • Since model and feature choices used your walk-forward folds, how did you guard against overfitting those validation splits? Any validation split used to compare multiple ideas absorbs some selection bias, because picking the highest score out of N noisy trials adds luck (~2.75 standard errors across 200 independent trials). We bounded that risk in three ways: logging every trial to keep the search small and structured around economic hypotheses, requiring flat performance across neighboring hyperparameters, and holding 2021–2023 completely locked until one frozen model remained. Seeing the gain move modestly from 7.5% in validation to 6.0% on the locked test—right in line with ~1.4% expected selection shrinkage rather than collapsing to 0%—confirmed genuine out-of-sample signal, followed by live shadow-mode scoring before risking capital.
  • Which post-deployment failure modes pose the greatest risk, and what automated circuit breakers would catch them? The two biggest production failure modes are upstream data breakages (delayed macro calendar feeds, missing minute bars, or unflagged contract rolls) and unprecedented market regimes outside the training distribution. Before each daily run, automated data-quality gates check bar counts, return bounds, and feature availability timestamps, refusing to emit a new forecast if inputs are corrupt. Alongside input checks, we track a rolling 20-day QLIKE difference against the simple HAR baseline running in parallel; if the tree model trails HAR beyond a pre-set alert band or data gates trip, position sizing automatically falls back to HAR.

Follow-up questions

Similar questions

More Graham Capital interview questions

All 1 Graham Capital questions →