A backtest can quietly end up with three different defects: picking the wrong side of the scores, charging half the trading cost, and pairing predictions with the wrong labels. All three can hide behind a reasonable-looking summary statistic.
Here is a small regression fixture for Python 3.10 or later. It uses synthetic returns to give each of those defects a concrete expected outcome. The objective is to catch wiring errors before adding more dates, models, and portfolio constraints.
Write the expected behaviors down first
- Score direction. The top two of A must be S08 and S07 in that order. B must pick S10 and S09.
- Transaction notional. A keeps the old book and trades zero. B sells 100% and buys 100%, paying 16 bp at an 8 bp rate.
- Monotone change. Moving S10's return from 80 bp to 31 bp preserves every realized rank. B still gets both winners, but its net moves from 39 to 14.5 bp. A stays at 17.5 bp.
- Two kinds of ties. Spearman uses average ranks. Portfolio selection uses a deterministic stock-ID tie-break when forced to pick exactly K names. A constant label vector produces an undefined Rank IC.
- Universe mismatch. Same-length mappings with different stock IDs must raise before correlation or selection results are compared.
Disclosure: This article was created using AI-generated text and code. The checks shown here exercise a synthetic fixture.
from fractions import Fraction from math import isclose, sqrt Stock = str Weights = dict[Stock, Fraction] def average_ranks(values: dict[Stock, int]) -> dict[Stock, Fraction]: ordered = sorted(values, key=values.__getitem__) ranks = {} start = 0 while start < len(ordered): end = start + 1 while end < len(ordered) and values[ordered[end]] == values[ordered[start]]: end += 1 mean_rank = Fraction(start + 1 + end, 2) for stock in ordered[start:end]: ranks[stock] = mean_rank start = end return ranks def rank_ic(scores: dict[Stock, int], returns: dict[Stock, int]) -> float | None: if scores.keys() != returns.keys(): raise ValueError("Align scores and returns on the same stock IDs") n = len(scores) if n < 2: return None x, y = average_ranks(scores), average_ranks(returns) midpoint = Fraction(n + 1, 2) numerator = sum((x[s] - midpoint) * (y[s] - midpoint) for s in scores) x_variation = sum((x[s] - midpoint) ** 2 for s in scores) y_variation = sum((y[s] - midpoint) ** 2 for s in scores) if not x_variation or not y_variation: return None return numerator / sqrt(x_variation * y_variation) def top_k(scores: dict[Stock, int], k: int) -> Weights: if not 1 <= k <= len(scores): raise ValueError("Invalid position count") order = sorted(scores, key=lambda stock: (-scores[stock], stock)) return {stock: Fraction(1, k) for stock in order[:k]} def evaluate( before: Weights, target: Weights, returns: dict[Stock, int], rate_bp: int ) -> tuple[Fraction, Fraction, Fraction]: gross = sum(weight * returns[stock] for stock, weight in target.items()) traded = sum(abs(target.get(s, 0) - before.get(s, 0)) for s in before.keys() | target.keys()) return gross, traded, gross - rate_bp * traded ids = [f"S{i:02}" for i in range(1, 11)] returns = dict(zip(ids, [-90, -20, -10, 0, 5, 10, 15, 20, 30, 80], strict=True)) scores_a = dict(zip(ids, [1, 2, 3, 4, 5, 6, 9, 10, 7, 8], strict=True)) scores_b = dict(zip(ids, [6, 5, 4, 3, 2, 1, 7, 8, 9, 10], strict=True)) before = {"S07": Fraction(1, 2), "S08": Fraction(1, 2)} target_a, target_b = top_k(scores_a, 2), top_k(scores_b, 2) compressed = returns | {"S10": 31} assert [*target_a] == ["S08", "S07"] assert [*target_b] == ["S10", "S09"] assert rank_ic(scores_a, returns) > rank_ic(scores_b, returns) assert isclose(rank_ic(scores_a, returns), 149 / 165) assert isclose(rank_ic(scores_b, returns), 19 / 33) for model in (scores_a, scores_b): assert rank_ic(model, returns) == rank_ic(model, compressed) base_a, base_b = (evaluate(before, w, returns, 8) for w in (target_a, target_b)) stress_a, stress_b = (evaluate(before, w, compressed, 8) for w in (target_a, target_b)) assert base_a == stress_a == (Fraction(35, 2), 0, Fraction(35, 2)) assert base_b == (55, 2, 39) assert stress_b == (Fraction(61, 2), 2, Fraction(29, 2)) assert base_b[2] - base_a[2] == Fraction(43, 2) assert stress_b[2] - stress_a[2] == -3 tied = {"A": 3, "B": 3, "C": 1} assert average_ranks(tied) == {"A": Fraction(5, 2), "B": Fraction(5, 2), "C": 1} assert set(top_k(dict(reversed(list(tied.items()))), 1)) == {"A"} assert rank_ic(tied, {"A": 5, "B": 5, "C": 2}) == 1 assert rank_ic(tied, {"A": 0, "B": 0, "C": 0}) is None try: rank_ic(tied, {"A": 5, "B": 1, "D": 0}) except ValueError: pass else: raise AssertionError("Scoring and label IDs differed but evaluation continued") print("Portfolio, ties, and universe alignment tests passed.") Interpret what would fail
The expected Rank ICs round to 0.9030 for A and 0.5758 for B. The expected net ordering is B above A in the base case and A above B in the compressed case. That is why the tests pin both the statistic and the portfolio result.
Reverse the sort and the holding assertions fail immediately. Compute the cost from the one-way turnover and B comes out at 47 bp instead of 39 in the base case. Incorrect positional joins can silently turn the last test into a correlation for unrelated names. Returning 0 for the constant label vector invents a measurement and can shift the average if there are enough affected dates.
A narrower mistake is to use the post-period rank to fill missing score ranks. On an actual decision timestamp, the forward return has yet to occur. A production test for this failure can freeze the entire set of eligible names, score records and timestamps before loading any realized returns, then verify that two different label snapshots produce the same target holdings.
For KAEL AI model evaluation, the useful contract is that every comparison can be traced from ranking to target weights to the trades used in the net calculation. This fixture prices changes against a fixed starting notional and assumes full fills. The next test for a rolling harness would carry a strategy's own drifted or partially filled portfolio into the next decision, since using the other model's old book can make systematic cost errors look like model differences.

