A stock model can pass chronological validation while using the identity of every issuer it is asked to predict. This Python fixture makes that dependency visible. It trains once, then scores familiar and unseen issuers over the same weeks. One intentionally leaked row comes from an unseen issuer on an otherwise valid training date. Another row has a valid feature date and a label that became available too late. A split auditor should catch both.

The article and code were drafted with AI assistance. All issuers, returns and time indices are synthetic. The script uses the Python standard library. The fixture tests the split, fitted predictions and error calculations.

Put the issuer boundary next to the forecast date

Each row has an issuer ID, a prediction week, a label availability week, a feature x and an outcome y. In this example, the prior week's label becomes available before the next week's forecast. That event ordering is why the training filter accepts outcome_available <= cutoff. When using full timestamps, record the actual time the label becomes observable and resolve any events with equal timestamps in the order they occurred. Use the label's outcome window as well if the validation protocol excludes overlapping returns.

The design choice KAEL AI proposes for this example is to keep the same calendar window for both test cohorts and audit the issuer boundary independently. One test asks whether performance persists over time on a familiar universe. The other asks whether the same fit transfers to companies absent from training. For ticker changes or related share classes, build the grouping key from the stable issuer identity appropriate to the research question. In scikit-learn, GroupKFold addresses group isolation and TimeSeriesSplit addresses time order. The example enforces both with explicit checks. GroupKFold · TimeSeriesSplit

Fit the pooled prediction first

The 32-issuer fixture gives each row a shared contribution of 20x basis points, an issuer effect of ±60 and a disturbance of ±15. Every four weeks, each issuer cycles through all four combinations of x and the disturbance. The known and unseen cohorts each include eight positive and eight negative issuer effects. Generate the full panel so that a date-only split would have earlier rows for the withheld issuers. Exclude them before estimating coefficients or any category-level statistics.

Fit a line to the training rows. When testing an issuer adjustment, group the training residuals and divide their sum by n + 12. With 48 observations, this retains 80% of the fitted mean residual. The lookup for an unknown key returns zero. For the issuer-only baseline, omit x and use shrinkage around the training intercept. An opaque but issuer-specific category provides a deliberate identity proxy. It should reproduce the issuer model's predictions exactly in this fixture.

Save the code as issuer_validation.py and run python3 issuer_validation.py.

from collections import defaultdict from dataclasses import dataclass, replace from math import sqrt from statistics import mean @dataclass(frozen=True) class Row: issuer: int week: int outcome_available: int x: int y: int proxy: str def issuer_effect(issuer): return 60 if issuer % 16 < 8 else -60 def make_rows(): for issuer in range(32): for week in range(1, 73): phase = (week - 1 + issuer) % 4 x = 1 if phase < 2 else -1 disturbance = 15 if phase % 2 == 0 else -15 y = 20 * x + issuer_effect(issuer) + disturbance # An opaque categorical value unique to this synthetic issuer. yield Row(issuer, week, week + 1, x, y, f'key-{1009 + 37 * issuer}') def audit_split(train, familiar, unseen, first_week, held_out): if any(r.week >= first_week or r.outcome_available > first_week for r in train): raise ValueError('training contains a future row or an unavailable label') train_issuers = {r.issuer for r in train} if train_issuers & held_out: raise ValueError('held-out issuer appears in training') if not {r.issuer for r in familiar} <= train_issuers: raise ValueError('familiar cohort includes an issuer absent from training') if not {r.issuer for r in unseen} <= held_out: raise ValueError('unseen cohort includes an issuer outside the holdout') dates = {r.week for r in familiar} if not dates or min(dates) < first_week or dates != {r.week for r in unseen}: raise ValueError('test cohorts do not share a valid date range') def fit(rows, use_x, group_key=None): center_x = mean(r.x for r in rows) center_y = mean(r.y for r in rows) slope = 0 if use_x: cross_product = sum((r.x - center_x) * (r.y - center_y) for r in rows) sum_squares = sum((r.x - center_x)**2 for r in rows) slope = cross_product / sum_squares intercept = center_y - slope * center_x residuals = defaultdict(list) if group_key is not None: for row in rows: base = intercept + slope * row.x residuals[group_key(row)].append(row.y - base) offsets = {key: sum(values) / (len(values) + 12) for key, values in residuals.items()} def predict(row): adjustment = offsets.get(group_key(row), 0) if group_key is not None else 0 return intercept + slope * row.x + adjustment return predict def mse(rows, predict): return mean((row.y - predict(row)) ** 2 for row in rows) def expect_error(action, message): try: action() except ValueError as exc: assert message in str(exc), str(exc) else: raise AssertionError(f'Expected error containing {message!r}') if __name__ == '__main__': rows = list(make_rows()) held_out = set(range(16, 32)) cutoff = 49 # A prior week's outcome is available before the next week's prediction. train = [r for r in rows if r.week < cutoff and r.outcome_available <= cutoff and r.issuer not in held_out] familiar = [r for r in rows if r.week >= cutoff and r.issuer not in held_out] unseen = [r for r in rows if r.week >= cutoff and r.issuer in held_out] audit_split(train, familiar, unseen, cutoff, held_out) assert len(train) == 768 and len(familiar) == len(unseen) == 384 # A date-only split would accept earlier observations from unseen issuers. wrong_issuer = next(r for r in rows if r.issuer in held_out and r.week == 10) expect_error(lambda: audit_split(train + [wrong_issuer], familiar, unseen, cutoff, held_out), 'held-out issuer') late_label = replace(train[47], outcome_available=cutoff + 1) expect_error(lambda: audit_split(train[:47] + [late_label] + train[48:], familiar, unseen, cutoff, held_out), 'unavailable label') stress = [replace(r, y=r.y - 2 * issuer_effect(r.issuer)) for r in familiar] def issuer_key(row): return row.issuer def proxy_key(row): return row.proxy shared = fit(train, use_x=True) combined = fit(train, use_x=True, group_key=issuer_key) proxy = fit(train, use_x=True, group_key=proxy_key) assert all(combined(r) == shared(r) for r in unseen) assert all(proxy(r) == combined(r) for r in familiar + unseen) trials = ( ('Zero prediction', lambda row: 0, (4225, 4225, 4225)), ('Issuer only', fit(train, use_x=False, group_key=issuer_key), (769, 4225, 12289)), ('Shared feature', shared, (3825, 3825, 3825)), ('Shared + issuer', combined, (369, 3825, 11889)), ('Shared + proxy', proxy, (369, 3825, 11889)), ) print('RMSE (bp) Familiar Unseen Reversed') for name, predict, expected in trials: measured = tuple(mse(cohort, predict) for cohort in (familiar, unseen, stress)) assert measured == expected, (name, measured) stable, cold, reversed_ = map(sqrt, measured) print(f'{name:17} {stable:8.2f} {cold:8.2f} {reversed_:9.2f}') print(f'Combined pooled RMSE: {sqrt(mse(familiar + unseen, combined)):.2f} bp') print('Issuer isolation, label availability and fallback checks passed.') 

Interpret the checks

The first injected row has an eligible date and belongs to one of the withheld issuers. The code rejects it even though a chronological split would accept it. The second comes from a familiar name and moves the label's availability to week 50, past the week 49 cutoff. The error specifically identifies unavailable training information. Both tests use the same auditing function that checks the valid split before the model fits.

The known-issuer adjustment reduces RMSE from 61.85 to 19.21 basis points on familiar names. The row-by-row fallback assertion verifies that the combined and shared predictors produce identical values for unseen issuers. Checking equality per row is more informative than matching two aggregate errors. The proxy test checks prediction equality as well. A model can retain an issuer dependency even when the column called issuer is removed.

The stress column keeps all input rows and model parameters fixed and changes only the test labels by reversing the issuer effects. It raises the combined model's error to 109.04 basis points. The shared model retains 61.85. When aggregating these scenarios, average squared errors before taking the square root. The combined model's 45.79 basis point pooled error is computed from all familiar and unseen rows together. Its value would move if the share of unseen issuers changed.

Carry the same checks into a real feature pipeline

Apply the issuer and time constraints before preprocessing. Fit scalers, imputers and target encoders inside training folds. Dated market history can be used to compute features for an unseen issuer at inference if it was already known, with a clear rule for how that history enters the evaluation. Preserve label availability, stable issuer identity and coverage at each fold. If a feature is missing for a newly covered issuer, report that separately from the category lookup's zero adjustment.

Compare model variants on identical rows within each cohort. If the new-coverage group contains systematically different firms, report the gaps in sector, size and liquidity and repeat the holdout across more than one group. Weekly rank statistics and costs belong in separate checks when the score drives a portfolio. This script is small enough to be used as a fixture for validating the dataset split and the unknown-category branch before those evaluations.