Past-Only Panel Features for Loan Histories
Medium · Data Manipulation (SQL/Python) · Data Scientist · Onsite
Problem Statement
You are given monthly loan performance records where each entry is a 6-tuple (loan_id, msa, month, property_type, delinquent_90dpd, upb):
loan_id(str): unique identifier for an individual loan.msa(str): metropolitan market code where the property is located.month(int): integer calendar month index (such asyear * 12 + calendar_month - 1), so adjacent calendar months always differ by1.property_type(str): collateral category (for example townhouse, condo, or multifamily).delinquent_90dpd(int): binary indicator (1if the loan is 90+ days past due inmonth,0otherwise).upb(float): unpaid principal balance for that snapshot.
Implement leakage_safe_features(rows, window=12, half_life=6.0, smoothing=10.0) to compute three strictly historical features for every observation at calendar month t. No feature at month t may inspect any outcome from month t or later (s >= t), even from other loans in the same market:
rolling_rate: Among all records sharing the same(msa, property_type)whose calendar monthslies in the inclusive interval[t - window, t - 1], divide the sum ofdelinquent_90dpdby the count of records in that interval. Becausewindowspans calendar months rather than row positions, missing months reduce the denominator; if zero records exist in[t - window, t - 1]for that segment, setrolling_ratetoNone.target_encoding: Letbadandnbe the delinquent count and total record count for(msa, property_type)across all calendar monthss < t. Defineprioras the overall delinquency rate ofmsaacross all monthss < t; ifmsaitself has zero observations beforet, fall back to the dataset-wide delinquency rate across all monthss < t(orNonewhen no observations exist anywhere beforet). Whenn == 0, settarget_encodingtoprior; whenn > 0, compute the smoothed rate(bad + smoothing * prior) / (n + smoothing).ewm_intensity: Across all earlier observations of the sameloan_idat monthss < t, weight each past flagdelinquent_sbyw_s = 0.5 ** ((t - s) / half_life)and returnsum(w_s * delinquent_s) / sum(w_s). If the loan has no observations prior tot, setewm_intensitytoNone.
Return a list of dictionaries — one per input tuple, sorted ascending by (loan_id, month) regardless of input order — where each dictionary contains the keys "loan_id", "month", "msa", "property_type", "rolling_rate", "target_encoding", and "ewm_intensity". Raise ValueError if any loan_id appears more than once in the same month.
In an interview discussion, also be ready to explain how the vectorized pandas equivalent handles 50 million rows within a 16 GB RAM ceiling, preserves chronological ordering after upstream shuffles or joins, and validates tricky boundary cases with deterministic tests.
Examples
Example 1
Input:
rows = [
("L10", "DEN", 10, "TH", 1, 240000.0),
("L20", "DEN", 10, "TH", 0, 180000.0),
("L30", "DEN", 10, "CONDO", 0, 150000.0),
("L10", "DEN", 11, "TH", 0, 238000.0),
("L40", "SEA", 11, "TH", 1, 310000.0),
("L10", "DEN", 13, "TH", 0, 235000.0),
]
window = 2, half_life = 1.0, smoothing = 2.0
Output (sorted by (loan_id, month)):
[
{"loan_id": "L10", "month": 10, "msa": "DEN", "property_type": "TH",
"rolling_rate": None, "target_encoding": None, "ewm_intensity": None},
{"loan_id": "L10", "month": 11, "msa": "DEN", "property_type": "TH",
"rolling_rate": 0.5, "target_encoding": 5/12, "ewm_intensity": 1.0},
{"loan_id": "L10", "month": 13, "msa": "DEN", "property_type": "TH",
"rolling_rate": 0.0, "target_encoding": 0.3, "ewm_intensity": 1/3},
{"loan_id": "L20", "month": 10, "msa": "DEN", "property_type": "TH",
"rolling_rate": None, "target_encoding": None, "ewm_intensity": None},
{"loan_id": "L30", "month": 10, "msa": "DEN", "property_type": "CONDO",
"rolling_rate": None, "target_encoding": None, "ewm_intensity": None},
{"loan_id": "L40", "month": 11, "msa": "SEA", "property_type": "TH",
"rolling_rate": None, "target_encoding": 1/3, "ewm_intensity": None},
]
Walk-through:
- At month = 10, no earlier calendar months exist, so "L10", "L20", and "L30" all receive (None, None, None).
- At month = 11 for "L10", segment ("DEN", "TH") has 1 delinquency out of 2 rows in [9, 10] (rolling_rate = 0.5), "DEN" overall had 1/3 delinquent before month 11 so (1 + 2 * (1/3)) / (2 + 2) = 5/12, and "L10"'s single prior flag 1 at s = 10 gives ewm_intensity = 1.0. "L40" enters brand-new market "SEA" at month = 11, so its target_encoding falls back to the global pre-month-11 rate 1/3 while its other two features are None.
- At month = 13 for "L10" (after an unobserved month 12), the 2-month calendar window [11, 12] contains only "L10"'s month-11 row (0.0); across all months < 13, ("DEN", "TH") has 1/3 and "DEN" has 1/4, yielding (1 + 2 * 0.25) / (3 + 2) = 0.3; for EWM, s = 10 (y = 1) has weight 0.5**3 = 1/8 and s = 11 (y = 0) has weight 0.5**2 = 1/4, giving (1/8) / (3/8) = 1/3.
Example 2
Input (unsorted rows, default parameters window=12, half_life=6.0, smoothing=10.0):
rows = [
("M9", "BOS", 25, "MF", 0, 400000.0),
("M9", "BOS", 19, "MF", 1, 405000.0),
("M8", "BOS", 19, "MF", 0, 220000.0),
]
Output:
[
{"loan_id": "M8", "month": 19, "msa": "BOS", "property_type": "MF",
"rolling_rate": None, "target_encoding": None, "ewm_intensity": None},
{"loan_id": "M9", "month": 19, "msa": "BOS", "property_type": "MF",
"rolling_rate": None, "target_encoding": None, "ewm_intensity": None},
{"loan_id": "M9", "month": 25, "msa": "BOS", "property_type": "MF",
"rolling_rate": 0.5, "target_encoding": 0.5, "ewm_intensity": 1.0},
]
Walk-through: Even though ("M9", 25) appears first in rows, sorting by (loan_id, month) evaluates month 19 before month 25. At month = 25, the 12-month window [13, 24] captures both month-19 rows (1/2 = 0.5), smoothed target encoding gives (1 + 10 * 0.5) / (2 + 10) = 0.5, and "M9"'s single prior default 6 months earlier has weight 0.5 ** (6 / 6.0) = 0.5, normalizing to 1.0.
Constraints
0 <= len(rows) <= 2 * 10^5in automated tests (algorithm should run inO(N log N)time rather thanO(N^2)).window >= 1,half_life > 0.0, andsmoothing >= 0.0.delinquent_90dpdis0or1;monthcan be any integer.- Each
(loan_id, month)pair must be unique; duplicate(loan_id, month)entries must raiseValueError. - Output floats are compared within a relative/absolute tolerance of
10^-9.
Step-by-step walkthrough
Understand the goal and pin down each feature
In mortgage risk modeling, we work with panel data (repeated monthly snapshots of many loans over time). Each input tuple is
(loan_id, msa, month, property_type, delinquent_90dpd, upb), wheremonthis an integer calendar index such asyear * 12 + calendar_month - 1(so consecutive calendar months always differ by1). Because the test runner executes pure Python standard library code,solution.pycomputes the features directly on row lists, whileexplanation.mdalso gives the exact vectorizedpandasequivalent for large Parquet tables.For every observation at month
tin segment(msa, property_type), we need three past-only features built strictly from months< t(never inspecting monthtor later, returningNonewhenever zero past observations exist):(a) rolling_rate = bad / rows for (msa, property_type) in calendar months [t - window .. t - 1] (b) target_encoding = (bad + k * prior) / (rows + k) for (msa, property_type) over all months < t where prior = MSA rate over months < t (or global rate < t if MSA is new) and target_encoding = prior if the segment itself has 0 rows before t (c) ewm_intensity = sum(w_s * y_s) / sum(w_s) over THIS loan's own past months s < t where w_s = 0.5 ** ((t - s) / half_life)Output: one dictionary per input row, sorted deterministically by
(loan_id, month).Why naive rolling windows leak future data
Imagine making a prediction on the morning of April 1st (
month = t): none of April's missed-payment outcomes exist yet. Four common shortcuts accidentally leak future or misaligned data:- Including month
t(rolling(12).mean()without shifting): the window includes the row's owndelinquent_90dpdtarget label, letting the model cheat. - Excluding only the current row instead of all of month
t: in a housing slump, thousands of loans in the same Metropolitan Statistical Area (MSA) default in the same month. Using other loans' month-tlabels leaks that unknown April shock. - Counting rows instead of calendar months: if a segment had no loans in months
2and3, a 3-row window reaches back to month0instead of stopping at montht - 3:
Observed months for segment: month 0 month 1 (gap: no data) month 4 (t = 4) 3-row window before t = 4: [month 0, month 1] --> stretches 4 calendar months back! 3-month calendar window [1..3]: [month 1] --> strictly months 1, 2, 3 before t = 4- Trusting row order after shuffles or merges:
cumsum()andshift(1)walk rows in their current order. If upstream joins shuffled the table,shift(1)grabs a random month unless you sort by(loan_id, month)first.
- Including month
Aggregate into monthly counters and prefix sums
Features (a) and (b) do not depend on which loan is asking — every loan in
(msa, property_type)at monthtsees the exact same past segment, MSA, and global history. Even with 50 million loan-month rows, there are only a few thousand(msa, property_type)segments and a few hundred months.So we first aggregate rows into
(key, month) -> [delinquent_count, row_count], sort each group's observed months, and build a prefix sum (a running total array where indexistores the sum of the firstiobserved months). Then any range[first, last]is answered in two binary searches (halving the sorted month list to jump straight to the start and end positions):months: [ 0, 1, 4 ] <-- only months with data are stored month bad: 1 2 1 cum_bad: [0, 1, 3, 4 ] <-- sentinel 0 at index 0 Query [first=1, last=3]: lo = bisect_left(months, 1) -> index 1 (month 1) hi = bisect_right(months, 3) -> index 2 (month 4 is > 3) bad in [1..3] = cum_bad[2] - cum_bad[1] = 3 - 1 = 2def add_month(totals: Dict[Any, Dict[int, List[int]]], key: Any, month: int, delinquent: int) -> None: """Add one row to the per-key, per-month [delinquent_count, row_count] counters.""" # totals maps group_key -> {month_index: [delinquent_count, total_rows]} by_month = totals.setdefault(key, {}) if month not in by_month: by_month[month] = [0, 0] by_month[month][0] += delinquent by_month[month][1] += 1 def prefix_sums(by_month: Dict[int, List[int]]) -> Tuple[List[int], List[int], List[int]]: """Build sorted observed months and 1-indexed prefix sums of delinquent and total rows.""" # months holds distinct observed month integers in ascending chronological order months = sorted(by_month) # cum_bad[i] and cum_rows[i] store totals across months[0 .. i-1] (cum_*[0] = 0 sentinel) cum_bad = [0] cum_rows = [0] for month in months: bad_in_month, rows_in_month = by_month[month] cum_bad.append(cum_bad[-1] + bad_in_month) cum_rows.append(cum_rows[-1] + rows_in_month) return months, cum_bad, cum_rows def sums_between(prefix: Tuple[List[int], List[int], List[int]], first: int, last: int) -> Tuple[int, int]: """Return (delinquent_count, row_count) over calendar months in [first, last] inclusive.""" months, cum_bad, cum_rows = prefix # bisect_left finds first month >= first; bisect_right finds first month > last lo = bisect_left(months, first) hi = bisect_right(months, last) return cum_bad[hi] - cum_bad[lo], cum_rows[hi] - cum_rows[lo] def sums_before(prefix: Tuple[List[int], List[int], List[int]], month: int) -> Tuple[int, int]: """Return (delinquent_count, row_count) over all calendar months strictly before `month`.""" months, cum_bad, cum_rows = prefix # Strict '< month' via bisect_left excludes all rows from `month` itself to prevent leakage hi = bisect_left(months, month) return cum_bad[hi], cum_rows[hi] def rate(bad: float, rows: float) -> Optional[float]: """Return bad / rows, or None when there are zero past observations.""" if rows == 0: return None return bad / rowsCompute the strict t-1 rolling rate and smoothed target encoding
Target encoding replaces a category (like
property_typewithin anmsa) with its historical delinquency rate. Raw rates are noisy on small groups: if a segment has 1 past loan and it defaulted, a raw rate of100%is wild overfitting. Additive smoothing (also called empirical Bayes shrinkage) blends the segment's past counts withk = smoothingimaginary rows at a broader prior rate (the MSA's past rate, falling back to the global past rate when an MSA is brand new):Month 10 in MSA DEN: Loan L10 (TH, bad=1), Loan L20 (TH, bad=0), Loan L30 (CONDO, bad=0) At month 11, for Loan L10 in segment (DEN, TH) with smoothing k = 2: segment (DEN, TH) before month 11: past_bad = 1, past_rows = 2 MSA DEN before month 11: msa_bad = 1, msa_rows = 3 -> prior = 1/3 target_encoding = (1 + 2 * (1/3)) / (2 + 2) = (5/3) / 4 = 5/12 = 0.4167Notice that even if another loan defaults at month 11 (such as
L40inSEA),sums_before(..., month=11)stops strictly before month 11 so month-11 labels never leak into month-11 features.win_bad, win_rows = sums_between(segment, month - window, month - 1) rolling_rate = rate(win_bad, win_rows) past_bad, past_rows = sums_before(segment, month) msa_bad, msa_rows = sums_before(msa_prefix[msa], month) all_bad, all_rows = sums_before(all_prefix, month) prior = rate(msa_bad, msa_rows) if msa_rows > 0 else rate(all_bad, all_rows) if past_rows == 0: target_encoding = prior else: target_encoding = (past_bad + smoothing * prior) / (past_rows + smoothing)Compute the calendar-aware exponentially weighted intensity
Feature (c) tracks each individual loan's past delinquency using an exponentially weighted moving average (EWM) with a 6-month half-life (meaning an observation's weight drops by half every 6 calendar months). Instead of rescanning all earlier months for every step, we maintain two running numbers as we walk one loan's sorted history:
weighted_badandweight_sum.When advancing from
last_monthtomonth,elapsed_months = month - last_monthcalendar months have passed, so every old weight shrinks by the exact same factor0.5 ** (elapsed_months / half_life). We readweighted_bad / weight_sumbefore adding the current month's outcome (+ delinquentand+ 1.0) so monthtonly affects months> t:Compare half_life = 1.0 on two histories with flags [1, 0] before the third row: Consecutive (months 0, 1, 2): after m=0 (y=1): weighted_bad = 1.0, weight_sum = 1.0 at m=1 (y=0): decay 0.5^1 -> 0.5 / 0.5 = 1.0; then add y=0 -> bad=0.5, sum=1.5 at m=2 (y=0): decay 0.5^1 -> 0.25 / 0.75 = 1/3 With a 3-month gap (months 0, 3, 4): after m=0 (y=1): weighted_bad = 1.0, weight_sum = 1.0 at m=3 (y=0): decay 0.5^3 -> (1/8) / (1/8) = 1.0; then add y=0 -> bad=1/8, sum=9/8 at m=4 (y=0): decay 0.5^1 -> (1/16) / (9/16) = 1/9 (older default faded much more!)if last_month is not None: elapsed_months = month - last_month decay = 0.5 ** (elapsed_months / half_life) weighted_bad *= decay weight_sum *= decay ewm_intensity = rate(weighted_bad, weight_sum) # Only AFTER reading month t's feature do we add month t's label for future months weighted_bad += delinquent weight_sum += 1.0 last_month = monthSort per loan and trace Example 1 end to end
Sorting
rows_by_loankeys and sorting each loan's(month, msa, property_type, delinquent)list guarantees two things: shuffled inputs produce identical outputs, and duplicate(loan_id, month)pairs appear side by side (month == last_month) so we can immediately raiseValueError.Let's trace Example 1 (
window = 2,half_life = 1.0,smoothing = 2.0), which includes an unobserved month12and a brand-new marketSEA:month 10: L10 (DEN, TH, 1) | L20 (DEN, TH, 0) | L30 (DEN, CONDO, 0) month 11: L10 (DEN, TH, 0) | L40 (SEA, TH, 1) month 13: L10 (DEN, TH, 0) <-- month 12 has zero rows loan@m rolling target_enc ewm reason all@10 None None None no months exist before month 10 L10@11 1/2 5/12 = 0.4167 1.0 (DEN,TH) in [9..10] had 1/2; L10 had y=1 at m=10 L40@11 None 1/3 = 0.3333 None SEA is a new MSA -> falls back to global m=10 rate 1/3 L10@13 0/1 3/10 = 0.3000 1/3 [11..12] has only L10@11 (0/1); DEN <13 has 1/4; EWM weights: m=10 -> 0.5^3=1/8, m=11 -> 0.5^2=2/8 -> 1/3Scale to 50M rows within 16 GB RAM and verify tricky boundaries
In production
pandason 50M rows, three engineering practices keep memory comfortably below 16 GB and prevent subtle regressions:- Compact column types and two-pass Parquet streaming: convert repeated strings (
~50–60 bytes/roweach) into categorical dtypes (integer dictionary codes) and downcast numeric widths (monthasint16,delinquent_90dpdasint8,upbasfloat32). That compresses 50M rows to~14 bytes/row ≈ 0.7 GB. To cap intermediate buffers too, Pass 1 scans Parquet chunks to build the compact(msa, property_type, month)summary arrays (a few megabytes), and Pass 2 processes 16 deterministic loan-hash buckets (crc32(loan_id) % 16, ~3.1M rows per bucket). - Chronological safety without
groupby.apply: sort upfront viadf.sort_values(["loan_id", "month"], kind="stable"), assert strictly increasing months per loan (df.groupby("loan_id", observed=True)["month"].diff().dropna().gt(0).all()), and stick to vectorizedcumsum()+shift(1)instead ofgroupby.apply(which adds heavy Python-loop overhead and can misalign row indices). - Deterministic verification suite: test earliest-month
Noneoutputs, exact hand fractions (5/12,0.3,1/3), unseen-MSA global fallback (1/3), empty rolling windows after long calendar gaps (None, never0.0), calendar decay across missing months, a label-flip invariance check (inverting every label at month 5 leaves all features at months<= 5unchanged), input-shuffle invariance, duplicate(loan_id, month)rejection, and randomized comparisons against an O(N²) oracle.
- Compact column types and two-pass Parquet streaming: convert repeated strings (
Complete solution
from bisect import bisect_left, bisect_right from typing import Any, Dict, List, Optional, Tuple def add_month(totals: Dict[Any, Dict[int, List[int]]], key: Any, month: int, delinquent: int) -> None: """Add one row to the per-key, per-month [delinquent_count, row_count] counters.""" # totals maps group_key -> {month_index: [delinquent_count, total_rows]} by_month = totals.setdefault(key, {}) if month not in by_month: by_month[month] = [0, 0] by_month[month][0] += delinquent by_month[month][1] += 1 def prefix_sums(by_month: Dict[int, List[int]]) -> Tuple[List[int], List[int], List[int]]: """Build sorted observed months and 1-indexed prefix sums of delinquent and total rows.""" # months holds distinct observed month integers in ascending chronological order months = sorted(by_month) # cum_bad[i] and cum_rows[i] store totals across months[0 .. i-1] (cum_*[0] = 0 sentinel) cum_bad = [0] cum_rows = [0] for month in months: bad_in_month, rows_in_month = by_month[month] cum_bad.append(cum_bad[-1] + bad_in_month) cum_rows.append(cum_rows[-1] + rows_in_month) return months, cum_bad, cum_rows def sums_between(prefix: Tuple[List[int], List[int], List[int]], first: int, last: int) -> Tuple[int, int]: """Return (delinquent_count, row_count) over calendar months in [first, last] inclusive.""" months, cum_bad, cum_rows = prefix # bisect_left finds first month >= first; bisect_right finds first month > last lo = bisect_left(months, first) hi = bisect_right(months, last) return cum_bad[hi] - cum_bad[lo], cum_rows[hi] - cum_rows[lo] def sums_before(prefix: Tuple[List[int], List[int], List[int]], month: int) -> Tuple[int, int]: """Return (delinquent_count, row_count) over all calendar months strictly before `month`.""" months, cum_bad, cum_rows = prefix # Strict '< month' via bisect_left excludes all rows from `month` itself to prevent leakage hi = bisect_left(months, month) return cum_bad[hi], cum_rows[hi] def rate(bad: float, rows: float) -> Optional[float]: """Return bad / rows, or None when there are zero past observations.""" if rows == 0: return None return bad / rows def leakage_safe_features(rows: List[Tuple[str, str, int, str, int, float]], window: int = 12, half_life: float = 6.0, smoothing: float = 10.0) -> List[Dict[str, Any]]: """Three leakage-safe features per loan-month; every one uses only months strictly before t. rows[i] = (loan_id, msa, month, property_type, delinquent_90dpd, upb), month an integer index. Output: one dict per row, sorted by (loan_id, month), with rolling_rate delinquency rate of (msa, property_type) over months t - window .. t - 1 target_encoding (bad + smoothing * prior) / (rows + smoothing) for (msa, property_type) over all months < t; prior = the MSA's rate before t, else the global rate ewm_intensity the loan's past delinquency, weighted by 0.5 ** ((t - s) / half_life) A feature is None when there is no past data for it. """ # Phase 1: Single pass to count monthly outcomes at 3 levels (segment, MSA, global) # and collect each loan's observations as [(month, msa, property_type, delinquent), ...] segment_totals: Dict[Tuple[str, str], Dict[int, List[int]]] = {} msa_totals: Dict[str, Dict[int, List[int]]] = {} all_totals: Dict[str, Dict[int, List[int]]] = {} rows_by_loan: Dict[str, List[Tuple[int, str, str, int]]] = {} for loan_id, msa, month, property_type, delinquent, _upb in rows: add_month(segment_totals, (msa, property_type), month, delinquent) add_month(msa_totals, msa, month, delinquent) add_month(all_totals, "all", month, delinquent) rows_by_loan.setdefault(loan_id, []).append((month, msa, property_type, delinquent)) # Phase 2: Precompute prefix sums for every group so range lookups take O(log T) time segment_prefix = {} for key, by_month in segment_totals.items(): segment_prefix[key] = prefix_sums(by_month) msa_prefix = {} for key, by_month in msa_totals.items(): msa_prefix[key] = prefix_sums(by_month) all_prefix = prefix_sums(all_totals["all"]) if rows else ([], [0], [0]) # Phase 3: Process loans in sorted order and sort each loan's history by month # so shuffled input rows always produce the exact same time-ordered features out: List[Dict[str, Any]] = [] for loan_id in sorted(rows_by_loan): history = sorted(rows_by_loan[loan_id]) # Running EWM state for this loan over months strictly before the current step weighted_bad = 0.0 weight_sum = 0.0 last_month: Optional[int] = None for month, msa, property_type, delinquent in history: # Two rows for the same loan in the same month make "previous history" ambiguous if month == last_month: raise ValueError(f"duplicate row for loan {loan_id} in month {month}") segment = segment_prefix[(msa, property_type)] # (a) Strict t-1 calendar rolling rate over [month - window, month - 1] win_bad, win_rows = sums_between(segment, month - window, month - 1) rolling_rate = rate(win_bad, win_rows) # (b) Past-only target encoding shrunk toward MSA prior (or global prior if new MSA) past_bad, past_rows = sums_before(segment, month) msa_bad, msa_rows = sums_before(msa_prefix[msa], month) all_bad, all_rows = sums_before(all_prefix, month) prior = rate(msa_bad, msa_rows) if msa_rows > 0 else rate(all_bad, all_rows) if past_rows == 0: target_encoding = prior else: # When past_rows > 0, msa_rows >= past_rows > 0, so `prior` is guaranteed non-None target_encoding = (past_bad + smoothing * prior) / (past_rows + smoothing) # (c) Decay past weights across elapsed calendar months (month - last_month) if last_month is not None: elapsed_months = month - last_month decay = 0.5 ** (elapsed_months / half_life) weighted_bad *= decay weight_sum *= decay ewm_intensity = rate(weighted_bad, weight_sum) # Only AFTER reading month t's feature do we add month t's label for future months weighted_bad += delinquent weight_sum += 1.0 last_month = month out.append({ "loan_id": loan_id, "month": month, "msa": msa, "property_type": property_type, "rolling_rate": rolling_rate, "target_encoding": target_encoding, "ewm_intensity": ewm_intensity, }) return out✅ Submit now — all tests should pass.
Intuition & how it works
Think of mortgage feature engineering like making a credit decision on the morning of April 1st: you have filing cabinets for January, February, and March, while April's cabinet is completely empty because nobody knows yet who will miss April's payment. Any feature that accidentally peeks inside April's cabinet — whether at this borrower's April flag or at a neighbor's April flag in the same city — causes data leakage (using information during training that will not exist at prediction time). Our dataset is panel data, meaning repeated monthly snapshots of many loans across Metropolitan Statistical Areas (MSAs) and property types.
The obvious approach is either rescanning all earlier rows for each row, or calling .rolling(12).mean() directly on the full 50M-row table. Rescanning every row against all 50M rows takes O(N^2) time — quadrillions of checks — while naive row-based rolling windows include the current month's label, treat 12 rows as 12 months even across missing months, and break silently whenever rows are not sorted by time. Instead, we aggregate segment and MSA counts once per calendar month into prefix sums (running cumulative totals that let us look up any month interval by subtracting two numbers), and walk each loan's sorted history once while decaying its running delinquency sum.
Walk through Example 1 in MSA DEN with window = 2, smoothing = 2.0, and half_life = 1.0 month:
- Month 10: Loan L10 (TH, delinquent 1), Loan L20 (TH, current 0), Loan L30 (CONDO, current 0). Nothing happened before Month 10, so all three features are None for every row. Loan L10 records weighted_bad = 1.0, weight_sum = 1.0 for future months.
- Month 11, Loan L10 (TH, current 0): Strictly before Month 11, segment (DEN, TH) has 1 bad out of 2 rows in [9, 10], so rolling_rate = 1/2 = 0.5. For target encoding (replacing a category with its smoothed past delinquency rate), MSA DEN had 1/3 bad overall at Month 10, so (1 + 2 * (1/3)) / (2 + 2) = 5/12. For exponentially weighted moving average (EWM) (a weighted average where older months decay by 0.5 each half-life), L10's Month-10 state decays by 0.5 to 0.5 / 0.5 = 1.0, and only after reading 1.0 do we add Month 11's 0 (weighted_bad = 0.5, weight_sum = 1.5). Meanwhile, Loan L40 enters unseen MSA SEA at Month 11, falling back to the global Month-10 rate 1/3.
- Month 13, Loan L10 (TH, current 0, after skipping Month 12): The 2-month calendar window [11, 12] holds only L10@11 (rolling_rate = 0.0), (DEN, TH) < 13 has 1/3 with DEN < 13 at 1/4 (target_encoding = (1 + 0.5) / 5 = 0.3), and L10's running EWM decays across the 2-month step 13 - 11 = 2 (decay = 0.25) to 0.125 / 0.375 = 1/3.
Complexity
Let N be the number of loan-month rows, L the number of loans, S the number of (msa, property_type) segments, G the number of MSAs, and T the number of distinct calendar months.
- Time — O(N log N): Counting monthly totals takes one linear O(N) pass over the rows. Sorting each group's observed months and sorting all loans and their per-loan histories takes O(N log N) comparisons in total. Then for each of the
Nrows, we run five binary searches (halving a sorted list of at mostTmonths to find range endpoints in O(log T) steps, whereT <= N) and O(1) arithmetic for the per-loan EWM update. - Space — O(N + S * T): Grouping the input rows by loan and building the
N-row output list takes O(N) memory, while the monthly counters and prefix-sum arrays store at mostS * T + G * T + Tnumbers (a few megabytes for thousands of segments across decades of monthly data). - Aggregate-then-join trade-off: Computing rolling and expanding totals on the
S * Tsummary grid instead of running rolling windows directly overN = 50Mrows avoids allocating multi-gigabyte per-row rolling buffers and reduces group-level work from 50M rows to a tiny segment-by-month table.
Edge cases
- First month of the panel or of a new loan: Zero past history yields
None(NaNin pandas), never0.0. Returning0.0would falsely tell the model "we observed past loans and zero defaulted" when nothing was observed at all. - Missing calendar months: Because prefix-sum lookups search by integer calendar month (
t - windowtot - 1) and EWM decays bymonth - last_month, gaps shrink the number of observations inside the window (returningNoneif all12preceding months were empty) instead of reaching back into stale years. - Single-observation or unseen groups: A brand-new
(msa, property_type)segment falls back to its MSA's past rate; a brand-new MSA falls back to the global past rate; additive smoothing keeps a 1-loan history from jumping straight to0.0or1.0. smoothing = 0.0: The formula cleanly reduces to the raw past segment ratepast_bad / past_rowswheneverpast_rows > 0, and still usespriorwhenpast_rows == 0.- Long gaps in a single loan's EWM: During a gap with no new rows,
weighted_badandweight_sumdecay by the exact same factordecay, so their normalized ratio stays flat until a new observation arrives and adds1.0to the denominator. If business logic requires risk intensity to decay toward zero during reporting silence, use the unnormalizedweighted_badsum instead. - Loans migrating across MSAs: Features (a) and (b) reflect the market
(msa, property_type)listed on that month's row, while feature (c) followsloan_idacross the move. - Duplicate
(loan_id, month)rows: Rejected immediately withValueError, because simultaneous rows for the same loan in one month make "past vs current" order undefined.
Common mistakes
- Calling
rolling(12).mean()without excluding montht: Includes the target label inside its own feature, creating severe target leakage. - Leave-one-row-out instead of leave-one-month-out for target encoding: Leaving out only row
istill averages over thousands of peer loans in monthtwhose outcomes are unknown at prediction time. - Averaging 12 monthly rates instead of summing numerators and denominators: Taking the unweighted mean of 12 monthly percentages gives a 2-loan month the same weight as a 20,000-loan month; always sum delinquent counts and row counts across the window first, then divide.
- Row-based EWM (
ewm(halflife=6)without calendar spacing): Treats a 6-month reporting gap as a single step of decay. - Using
groupby.applyor runningshift/cumsumon unsorted frames: After joins or shuffles, row order is arbitrary unless you explicitly sort by["loan_id", "month"];groupby.applyalso adds heavy Python-loop overhead and can misalign results if indices are reset. - Keeping string
objectcolumns at 50M rows: Each Python string object uses roughly 50–60 bytes plus an 8-byte pointer (~3 GB per string column at 50M rows), blowing through a 16 GB RAM budget.
Alternative approaches
Vectorized pandas implementation + 16 GB RAM architecture. Below is the exact pandas equivalent, verified against leakage_safe_features across random panels with missing months, loan migrations, and shuffled rows:
import numpy as np
import pandas as pd
def past_sums(df, keys, months, window):
"""Per (key, month t): defaults and rows in t-window..t-1 (win_*) and in all months < t (past_*)."""
agg = df.groupby(keys + ["month"], observed=True)["delinquent_90dpd"].agg(["sum", "count"])
out = {}
for col, name in (("sum", "bad"), ("count", "n")):
# Dense key x calendar-month grid where missing months have 0 defaults and 0 rows
wide = agg[col].unstack("month", fill_value=0).reindex(columns=months, fill_value=0)
cum = wide.cumsum(axis=1)
before_t = cum.shift(1, axis=1, fill_value=0) # strictly < t
before_window = cum.shift(window + 1, axis=1, fill_value=0) # strictly < t - window
out["past_" + name] = before_t.stack()
out["win_" + name] = (before_t - before_window).stack()
return pd.DataFrame(out)
def lookup(table, df, cols):
"""Align summary `table` (indexed by `cols`) with the rows of `df`."""
return table.reindex(pd.MultiIndex.from_frame(df[cols])).reset_index(drop=True)
def leakage_safe_features_pd(df, window=12, half_life=6.0, smoothing=10.0):
if df.empty:
return df.assign(rolling_rate=np.nan, target_encoding=np.nan, ewm_intensity=np.nan)
df = df.sort_values(["loan_id", "month"], kind="stable").reset_index(drop=True)
if df.duplicated(["loan_id", "month"]).any():
raise ValueError("duplicate loan-month rows")
months = np.arange(df["month"].min(), df["month"].max() + 1)
seg = lookup(past_sums(df, ["msa", "property_type"], months, window), df, ["msa", "property_type", "month"])
msa = lookup(past_sums(df, ["msa"], months, window), df, ["msa", "month"])
total = df.groupby("month")["delinquent_90dpd"].agg(["sum", "count"]).reindex(months, fill_value=0)
total_before = total.cumsum().shift(1, fill_value=0).reindex(df["month"]).reset_index(drop=True)
# (a) Strict t-1 rolling rate; 0 rows in window -> NaN
df["rolling_rate"] = seg["win_bad"] / seg["win_n"].where(seg["win_n"] > 0)
# (b) Past-only target encoding shrunk toward MSA (else global) past rate
prior = (msa["past_bad"] / msa["past_n"]).where(msa["past_n"] > 0,
total_before["sum"] / total_before["count"])
smoothed = (seg["past_bad"] + smoothing * prior) / (seg["past_n"] + smoothing)
df["target_encoding"] = smoothed.where(seg["past_n"] > 0, prior)
# (c) Factor out 0.5^((t - first)/h) so weights become 2^((s - first)/h), independent of t
loan = df["loan_id"]
first = df.groupby(loan, observed=True)["month"].transform("min")
weight = np.exp2((df["month"] - first) / half_life)
cum_weighted = (weight * df["delinquent_90dpd"]).groupby(loan, observed=True).cumsum()
cum_weight = weight.groupby(loan, observed=True).cumsum()
df["ewm_intensity"] = (cum_weighted.groupby(loan, observed=True).shift(1)
/ cum_weight.groupby(loan, observed=True).shift(1))
return df
Why the np.exp2 trick works: every weight 0.5 ** ((t - s) / h) equals 0.5 ** ((t - first) / h) * 2 ** ((s - first) / h). Because 0.5 ** ((t - first) / h) does not depend on s, it cancels between the numerator and denominator, turning the time-aware EWM into a ratio of two per-loan cumsum() columns shifted by 1 row (safe whenever (loan age in months) / half_life < 1000, which is 500 years for half_life = 6).
To fit 50M rows comfortably under 16 GB RAM, use categorical dtypes (storing repeated strings as compact integer codes) and downcasting (choosing the smallest integer/float width that holds each column's range):
column compact dtype bytes/row
loan_id int32 / dictionary code 4
msa category (int16 codes) 2
month int16 month index 2
property_type category (int8 codes) 1
delinquent_90dpd int8 1
upb float32 4
total 14 bytes/row -> ~0.7 GB for 50M rows
At 50M rows, each temporary float64 Series still costs 400 MB, so run two passes over Parquet: Pass 1 reads only [msa, property_type, month, delinquent_90dpd] in row-group chunks to build the tiny S * T and G * T numpy lookup arrays, and Pass 2 streams 16 deterministic loan buckets (zlib.crc32(loan_id.encode()) % 16, ~3.1M rows per bucket), computing lookups via direct integer array indexing table[seg_code, month - min_month] and per-loan EWM in ~2 GB peak RAM.
Follow-up questions
- What safeguards prevent row-order bugs when upstream joins or concatenations scramble panel timestamps? Sort explicitly with
df.sort_values(["loan_id", "month"], kind="stable")immediately before any order-dependent step (cumsum,shift,ewm), and enforce an invariant check(df.groupby("loan_id", observed=True)["month"].diff().dropna() > 0).all()to catch both out-of-order rows and duplicate loan-months. Prefer index-preserving operations (transform,cumsum,shift) overgroupby.apply, and always join feature tables back on explicit["loan_id", "month"]keys rather than row position. - How does the design change if delinquency rates must be weighted by unpaid principal balance rather than loan count? Replace each
[delinquent_count, row_count]pair with[sum(upb * delinquent_90dpd), sum(upb)]over the exact same strictly-past month windows (< tand[t - window, t - 1]), usingfloat64accumulators so large segment balances do not lose precision (float32only has ~7 significant decimal digits). Because every UPB value in those sums comes from months< t, it is already known before monthtbegins and introduces zero leakage. - How can you tune the additive smoothing constant without leaking future default behavior into model selection? Treat
smoothingas the count of virtual observations at the MSA prior and tune it (for example over{1, 5, 10, 50, 100}) using blocked, expanding-window time-series cross-validation where validation folds always sit strictly in the future of training folds. Alternatively, estimate it via empirical Bayes (fitting the variance between segment rates and MSA rates) strictly inside each training cutofftrather than once across the full multi-year dataset.
Follow-up questions
- What safeguards prevent row-order bugs when upstream joins or concatenations scramble panel timestamps?
- How does the design change if delinquency rates must be weighted by unpaid principal balance rather than loan count?
- How can you tune the additive smoothing constant without leaking future default behavior into model selection?
Similar questions
- End-to-End Production ML Project Walkthrough
- Expanding-Window Panel Splitter with Embargo and Region Holdout
- Calibrated Verification for High-Stakes Enterprise RAG
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages