A forecast blend needs two different datasets. Estimate the weight from rows where both forecasts were available and the outcomes were known by the update cutoff. Evaluate that weight on the full next window, including cases where a missing candidate sends the system back to its anchor model. The Python example below runs both stages and deliberately introduces time and horizon mismatches.
The article and code were drafted with AI assistance. The fixture uses synthetic forecasts, basis points and integer week indices. It runs with the Python standard library.
Match the target before measuring the error
The record key contains an asset, a decision week and a horizon end. Both models use the same benchmark and unit throughout the fixture. Include a target definition or benchmark identifier in real datasets that contain multiple tasks. Keep the forecast's arrival time separate from the decision time. A forecast keyed to Monday may arrive after Monday's decision, and a correctly aligned return may become available after the weight update. Both fields have to pass the cutoff relevant to their use.
The check KAEL AI proposes here is to preserve the original decision record in the replay even when candidate coverage is incomplete. Fit a weight on eligible pairs. At inference, use the anchor if its candidate is missing or late. Then score each anchor decision that has a realized outcome, including those fallbacks. Recording both the pair count and the fallback count shows how much of the result is attributable to the blend.
The fixture uses 16 rows per window by crossing eight balanced error configurations with positive and negative realized returns. A's error is 20 times a sign u. B's error contains a large multiple of u and a smaller orthogonal component. C's stable errors are orthogonal to A's. In the stress window, C's error becomes 20u plus an orthogonal ±15. Its individual RMSE stays at 25 basis points. Integer timestamps make the training cutoff and the evaluation windows easy to see. In live replay, preserve event sequence when two timestamps could be equal.
Fit one weight with a bounded objective
For a row with errors a and b, the candidate moves the error from a to a + w(b−a). Minimizing the mean square gives E[a(a−b)] / E[(b−a)²]. Compute the denominator from differences directly. This avoids subtracting two large, nearly equal quantities in the expanded formula. Clip w to [0, 1] so both weights are nonnegative. When errors agree exactly on every row, select the anchor. With near duplicates and noisier data, the estimate can be unstable even with nonnegative bounds. Choose any shrinkage or stability rule within an earlier validation fold. Bates and Granger, The Combination of Forecasts · Timmermann, Forecast Combinations
Save the following as forecast_blend.py and run python3 forecast_blend.py.
from dataclasses import dataclass, replace
from itertools import product
from math import isclose, sqrt
from statistics import correlation, mean
@dataclass(frozen=True)
class Key:
asset: str
decision: int
horizon_end: int
@dataclass(frozen=True)
class Observation:
value: float
available: int
def forecasts(start, rho_c):
anchor, second, third, labels = {}, {}, {}, {}
for index, (u, v, z, truth_sign) in enumerate(product((-1, 1), repeat=4)):
week = start + index
key = Key('synthetic_asset', week, week + 1)
actual = 40 * truth_sign
error_a = 20 * u
error_b = 22 * (0.95 * u + sqrt(1 - 0.95**2) * v)
error_c = 25 * (rho_c * u + sqrt(1 - rho_c**2) * z)
anchor[key] = Observation(actual + error_a, week)
second[key] = Observation(actual + error_b, week)
third[key] = Observation(actual + error_c, week)
labels[key] = Observation(actual, week + 1)
return anchor, second, third, labels
def paired_errors(anchor, candidate, labels, cutoff):
pairs = []
for key, base in anchor.items():
alt = candidate.get(key)
label = labels.get(key)
if alt is None or label is None:
continue
if base.available > key.decision or alt.available > key.decision:
continue
if key.decision < key.horizon_end <= label.available <= cutoff:
pairs.append((base.value - label.value, alt.value - label.value))
return pairs
def fit_weight(pairs):
if not pairs:
raise ValueError('no eligible paired errors')
# Fit e_a + w * (e_b - e_a) directly to minimize squared error.
disagreement = mean((b - a)**2 for a, b in pairs)
if disagreement == 0:
return 0.0
numerator = mean(a * (a - b) for a, b in pairs)
return min(1.0, max(0.0, numerator / disagreement))
def replay(anchor, candidate, labels, weight, score_at):
errors = {}
fallbacks = 0
for key, base in anchor.items():
label = labels[key]
if base.available > key.decision or not key.horizon_end <= label.available <= score_at:
raise ValueError('anchor forecast or outcome unavailable for replay')
alt = candidate.get(key)
prediction = base.value
if alt is None or alt.available > key.decision:
fallbacks += 1
else:
prediction += weight * (alt.value - base.value)
errors[key] = prediction - label.value
return errors, fallbacks
def rmse(errors):
return sqrt(mean(e*e for e in errors.values()))
def expect_no_pairs(pairs):
try:
fit_weight(pairs)
except ValueError as exc:
assert str(exc) == 'no eligible paired errors'
else:
raise AssertionError('expected matching and mature inputs')
if __name__ == '__main__':
a, b, c, outcomes = forecasts(start=1, rho_c=0)
cutoff = 17
ab = paired_errors(a, b, outcomes, cutoff)
ac = paired_errors(a, c, outcomes, cutoff)
assert len(ab) == len(ac) == 16
weight_b, weight_c = fit_weight(ab), fit_weight(ac)
assert weight_b == 0 and isclose(weight_c, 16/41)
assert fit_weight(paired_errors(a, a, outcomes, cutoff)) == 0
assert isclose(correlation([a[k].value for k in a], [c[k].value for k in a]),
1600 / sqrt(2000 * 2225))
errors_a, errors_c = zip(*ac)
assert abs(correlation(errors_a, errors_c)) < 1e-12
key = next(iter(a))
late_labels = {**outcomes, key: replace(outcomes[key], available=cutoff + 1)}
assert len(paired_errors(a, c, late_labels, cutoff)) == 15
wrong_horizon = replace(key, horizon_end=key.horizon_end + 1)
expect_no_pairs(paired_errors(a, {wrong_horizon: c[key]}, outcomes, cutoff))
stable_a, stable_b, stable_c, stable_y = forecasts(start=18, rho_c=0)
stress_a, _, stress_c, stress_y = forecasts(start=35, rho_c=0.8)
assert max(r.available for r in outcomes.values()) < min(k.decision for k in stable_a)
assert rmse(replay(stable_a, {}, stable_y, 0, 34)[0]) == 20
assert isclose(rmse(replay(stable_b, {}, stable_y, 0, 34)[0]), 22)
assert rmse(replay(stress_c, {}, stress_y, 0, 51)[0]) == 25
assert isclose(rmse(replay(stable_c, {}, stable_y, 0, 34)[0]), 25)
equal_ab = rmse(replay(stable_a, stable_b, stable_y, 0.5, 34)[0])
equal_ac = rmse(replay(stable_a, stable_c, stable_y, 0.5, 34)[0])
stable = rmse(replay(stable_a, stable_c, stable_y, weight_c, 34)[0])
stressed = rmse(replay(stress_a, stress_c, stress_y, weight_c, 51)[0])
assert isclose(equal_ab**2, 430) and isclose(equal_ac**2, 256.25)
assert isclose(stable**2, 400 * 625 / 1025)
assert isclose(stressed**2, 400 + 225 * weight_c**2)
assert isclose(fit_weight(paired_errors(stress_a, stress_c, stress_y, 51)), 0)
first = next(iter(stable_a))
candidate_late = {**stable_c, first: replace(stable_c[first], available=first.decision + 1)}
candidate_missing = {k: v for k, v in stable_c.items() if k != first}
for incomplete in (candidate_late, candidate_missing):
errors, fallbacks = replay(stable_a, incomplete, stable_y, weight_c, 34)
assert len(errors) == 16 and fallbacks == 1
assert errors[first] == stable_a[first].value - stable_y[first].value
print(f'Fitted candidate weights: B {weight_b:.2%}, C {weight_c:.2%}')
print(f'Equal blend RMSE (bp): A+B {equal_ab:.2f}, A+C {equal_ac:.2f}')
print(f'Frozen A+C RMSE (bp): stable {stable:.2f}, stress {stressed:.2f}')
print('Maturity, horizon, duplicate forecast and fallback checks passed.')
Inspect the failure paths
The fitted weight is 0% for B and 39.02% for C. Equal weights give 20.74 basis points for A+B and 16.01 for A+C. The fitted A+C blend goes from 15.62 in the stable window to 20.84 in the stress window. The stress-window optimum computed after realization is zero for C. The replay uses the original fit and therefore exposes the loss from carrying that weight forward.
The tests inject a return whose availability is after the fitting cutoff and verify that one pair disappears. A forecast for a different horizon produces zero pairs and the fitter refuses that sample. Exact duplicate forecasts leave the whole weight on A. In separate evaluation tests, a missing candidate and a late candidate each cause one fallback. Both runs retain all 16 rows, and the affected error equals the anchor's error. Zero is a valid forecast. The fallback is triggered by absence or timing.
The case also checks forecast and residual correlation separately. A and C share the same realized return, so their forecasts are correlated in the stable window even though their errors are orthogonal. In a real experiment, use base forecasts generated without access to their evaluation labels. Establish uniqueness of the record key and pin each forecast to its model version and its target definition before the join.
For rolling validation, record the base model chosen using prior data, the paired rows used to estimate weights and the date at which each fitted weight takes effect. Keep a fixed equal-weight comparator. Aggregate loss differences across successive test dates and report where the candidate missed its decision deadline. Those records make it possible to trace a gain or loss to the weight, the error relationship, or the coverage of the candidate model.
Top comments (0)