Forecasting Ten-Minute Volatility on Unseen Stocks
Optiver realized-volatility project · Final report
Author
Garrett Peuse
Published
November 30, 2026
Show code
# Setup: every number and chart below is read from a saved workflow output.# Nothing is refit here, so the report renders in seconds.import jsonfrom pathlib import Pathimport matplotlib.pyplot as pltimport numpy as npimport polars as plfrom IPython.display import MarkdownPROJECT = Path.cwd().parentINK, MUTED, BLUE, ORANGE, GREEN, GREY, PAPER = ("#1B2A3A", "#5B6B7B", "#2F5D8A", "#D9822B", "#2E7D5B", "#B8C2CC", "#FFFFFF",)plt.rcParams.update({"axes.edgecolor": MUTED, "axes.labelcolor": INK, "xtick.color": INK,"ytick.color": INK, "text.color": INK, "axes.grid": True,"grid.color": "#E6E6E6", "axes.spines.top": False, "axes.spines.right": False,"font.size": 11, "axes.titlesize": 12, "legend.frameon": False,})def rmspe(y, p):"""Root mean squared percentage error, the competition metric."""returnfloat(np.sqrt(np.mean(np.square((y - p) / y))))def read(attempt, name):"""Load one saved output file from a workflow station.""" path = PROJECT /f"workflow_attempt_{attempt}"/"outputs"/ nameif name.endswith(".parquet"):return pl.read_parquet(path)if name.endswith(".csv"):return pl.read_csv(path)return json.loads(path.read_text())# The submitted model's out-of-fold predictions, joined to the naive forecast.oof = read(15, "oof_candidates.parquet").join( pl.read_parquet(PROJECT /"workflow_attempt_3/outputs/features_train.parquet") .select("stock_id", "time_id", "rv_wap"), on=["stock_id", "time_id"],)y = oof["target"].to_numpy()not11 = oof["stock_id"].to_numpy() !=11a15 = read(15, "metrics.json")estimate = read(17, "final_estimate.json")submission = pl.read_csv(PROJECT / estimate["file"])
Summary
Show code
naive = rmspe(y, oof["rv_wap"].to_numpy())tree = rmspe(y, oof["tree_seed0"].to_numpy())blend = rmspe(y, oof["gated_blend"].to_numpy())blend85 = rmspe(y[not11], oof["gated_blend"].to_numpy()[not11])print(f"""We forecast the realized volatility of the next ten minutes for 26 stocks themodels never see in training. The submitted model is a **blend of XGBoosttrees and two neural networks, weighted by the current volatility regime**.| | RMSPE ||---|---:|| Naive forecast (next window = this window) | {naive:.3f} || First submitted model, one XGBoost model | {tree:.3f} || **Submitted blend**, all 86 training stocks | **{blend:.3f}** || Submitted blend, without the one outlier stock | {blend85:.3f} || **Our estimate of the test RMSPE** | **{estimate['estimated_rmspe']:.4f}** |All scores are *out of fold*: every stock is predicted by models that nevertrained on it, the same situation as the test. The prediction file has{submission.height:,} rows, one per test stock and window.""")
We forecast the realized volatility of the next ten minutes for 26 stocks the models never see in training. The submitted model is a blend of XGBoost trees and two neural networks, weighted by the current volatility regime.
RMSPE
Naive forecast (next window = this window)
0.345
First submitted model, one XGBoost model
0.261
Submitted blend, all 86 training stocks
0.244
Submitted blend, without the one outlier stock
0.232
Our estimate of the test RMSPE
0.2333
All scores are out of fold: every stock is predicted by models that never trained on it, the same situation as the test. The prediction file has 99,580 rows, one per test stock and window.
Three findings carry the project:
Model structure mattered more than more features. After the first 38 features, every later feature group moved the error by less than changing the tree’s random seed. Every later gain came from how models were split and combined.
One stock can steer a pooled metric. Stock 11 is 1% of the rows and about 18% of the squared error. It nearly chose our feature list, so every decision after that was also checked stock by stock.
Different model types made useful, different mistakes. Trees and nets blended by volatility regime beat the single model on all five folds and on 83 of 86 stocks.
The problem and how we scored it
The data is ten-minute windows of order-book and trade records for 112 stocks. For each stock and window we predict the realized volatility of the following ten minutes. Three choices sit under every number in this report.
Validation holds out whole stocks. The 26 test stocks never appear in training, so the 86 training stocks are split into five groups and each group is predicted by models fit on the other four. A random split by row would let a model learn each stock’s usual volatility level and look better than it will on new stocks.
The metric is RMSPE, the root mean squared percentage error, so a 10% miss costs the same in a calm window as in a wild one. Trees are trained with weights of 1 / target², which makes their training loss the same percentage error. The nets use RMSPE directly as their loss.
The assignment’s rules are kept throughout. Each feature uses one stock and one window only; stock_id is never a feature; time_id is not treated as a clock.
The path to the final model
Show code
steps = [ ("Naive", "rv_wap"), ("One XGBoost\nmodel", "tree_seed0"), ("Volatility\nspecialists", "specialists"), ("Equal blend,\nfour models", "equal_blend"), ("Regime-weighted\nblend (submitted)", "gated_blend"),]all86 = [rmspe(y, oof[c].to_numpy()) for _, c in steps]no11 = [rmspe(y[not11], oof[c].to_numpy()[not11]) for _, c in steps]fig, ax = plt.subplots()x = np.arange(len(steps))ax.bar(x -0.19, all86, 0.38, color=GREY, label="All 86 stocks")ax.bar(x +0.19, no11, 0.38, color=[ORANGE, BLUE, BLUE, BLUE, GREEN], label="85 stocks, without stock 11")for i in x: ax.text(i -0.19, all86[i] +0.003, f"{all86[i]:.3f}", ha="center", fontsize=9, color=MUTED) ax.text(i +0.19, no11[i] +0.003, f"{no11[i]:.3f}", ha="center", fontsize=9.5, fontweight="bold")ax.set_xticks(x, [s for s, _ in steps])ax.set_ylim(0.18, 0.37)ax.set_ylabel("Out-of-fold RMSPE (lower is better)")ax.legend(loc="upper right")plt.tight_layout()plt.show()
Figure 1: Out-of-fold RMSPE for each step. Grey bars include all 86 training stocks; coloured bars leave out stock 11. Every step after the naive forecast uses the same 38 features.
The largest drop, from 0.345 to 0.261, is the features plus the first XGBoost model. Splitting that model by volatility regime, then blending trees with neural networks, took the error to 0.244 on all 86 stocks.
Features
About 90 features were built and tested, all from the current window’s book and trades. The final model uses the first five groups, 38 columns.
Group
Columns
What it measures
In final model
Volatility
7
Realized volatility of the weighted average price (WAP) and midpoint, over the window and its first and last two minutes; book update count
Yes
Spread
5
Best ask minus best bid as a fraction of price: average, peak, variability, final value, change
Yes
Trades
8
Shares, orders, seconds with a trade, average trade size, trade-price volatility, late versus early volume
Yes
Book size and imbalance
6
Size at the best prices, which side is heavier, and how that changed
Yes
Clock of variance
12
Each minute’s share of the window’s variance, its centre, the heaviest minute
Yes
Price path and path clusters
5 + k-means
Return, range, drawdown, run-up; k-means groups of minute shares
Tested
Decomposition and liquidity
14
WAP move versus midpoint move; spread, imbalance and depth together
Tested
Path regression and reversal
15
Trend and mean reversion on a 5-second price grid
Tested
Burst and sampling clocks
18
The heaviest minute’s aftermath; volatility read every 5, 15 and 30 seconds
Tested
Each tested group was added to the same tree on the same stock folds at three random seeds. Figure 2 compares the change with how far the unchanged model moves when only its seed changes.
Show code
rows = []for attempt, groups in ((10, ("decomposition", "liquidity")), (12, ("regression", "reversal")), (13, ("burst",)), (14, ("sampling",))): t = read(attempt, "stages.csv") base = t.filter(pl.col("stage") =="baseline").select("seed", pl.col("pooled_excluding_stock_11").alias("b"))for g in groups: d = t.filter(pl.col("stage") == g).join(base, on="seed") rows.append((g, (d["pooled_excluding_stock_11"] - d["b"]).to_numpy()))base43 = read(12, "stages.csv").filter(pl.col("stage") =="baseline")["pooled_excluding_stock_11"].to_numpy()noise = base43.max() - base43.min()names = {"decomposition": "WAP vs\nmidpoint", "liquidity": "Joint\nliquidity", "regression": "Path\nregression","reversal": "Reversal", "burst": "Burst\nrecovery", "sampling": "Sampling\nclocks"}fig, ax = plt.subplots(figsize=(8.0, 3.2))ax.axhspan(-noise /2, noise /2, color="#EBD9C5", label=f"Seed-to-seed spread ({noise:.4f})")ax.axhline(0, color=MUTED, lw=1)for i, (g, d) inenumerate(rows): ax.scatter([i] *len(d), d, s=60, color=BLUE, zorder=3, label="One seed"if i ==0elseNone)ax.set_xticks(range(len(rows)), [names[g] for g, _ in rows])ax.set_ylabel("Change in RMSPE\n(below 0 helps)")ax.set_ylim(-0.0035, 0.0035)ax.legend(loc="upper left", ncol=2)plt.tight_layout()plt.show()
Figure 2: Change in RMSPE (85 stocks) when each feature group is added, one dot per seed. The shaded band is the seed-to-seed spread of the unchanged model. No group is consistently below it.
Gains in one seed reversed in another. Once current volatility, spread and the timing of variance are in the model, the rest of the book adds little.
Feature selection
We ran backward elimination by block: drop one feature group, and keep it out if the five-fold mean RMSPE improves. It removed four groups, including spread, and lowered the mean from 0.268 to 0.254. Reading the result stock by stock showed why.
Show code
t = read(7, "by_stock.csv").filter(pl.col("comparison") =="without_spread")s11 = t.filter(pl.col("stock_id") ==11)d = t.filter(pl.col("stock_id") !=11)["delta_rmspe"].to_numpy()fig, axes = plt.subplots(1, 2, figsize=(8.0, 3.0), gridspec_kw={"width_ratios": [2.2, 1]})axes[0].hist(d, bins=np.linspace(-0.001, 0.0065, 31), color=BLUE)axes[0].axvline(0, color=INK)axes[0].set_xlabel("Change in a stock's RMSPE when spread is removed (right = worse)")axes[0].set_ylabel("Stocks")axes[0].set_title(f"{int((d >0).sum())} of {len(d)} ordinary stocks got worse")w, wo =float(s11["rmspe_with"][0]), float(s11["rmspe_without"][0])axes[1].bar([0, 1], [w, wo], color=[GREY, ORANGE], width=0.6)for i, v inenumerate((w, wo)): axes[1].text(i, v +0.02, f"{v:.2f}", ha="center", fontweight="bold")axes[1].set_xticks([0, 1], ["With spread", "Without"])axes[1].set_title("Stock 11 alone")axes[1].set_ylim(0, 1.35)plt.tight_layout()plt.show()
Figure 3: Left: each ordinary stock’s change in RMSPE when the spread features are removed. Right: stock 11, the only stock that improved.
Spread helps almost every stock: a wide spread signals uncertainty, and uncertain markets move more. Stock 11 has a wide spread but a very deep book and windows that barely move, so the same rule overpredicts it badly. Its single large improvement outweighed 66 small losses in the mean. The shorter list also lost on 17 stocks held back from selection (0.2422 against 0.2383), so we kept all 38 columns. From then on, every decision was checked by how many stocks and folds improved, not just the pooled score.
Tuning
XGBoost
Settings were searched in stages on the training stocks only: depth first, then number of trees and learning rate, then the leaf penalties and sampling rates.
Figure 4: Cross-validated RMSPE by tree depth. The five-fold mean (all stocks) is lowest at depth 3; without stock 11 the curve is flat from 3 to 5 and rises after.
The chosen model is depth 3, 200 trees, learning rate 0.1, minimum child weight 5, lambda 1, and 80% row and column sampling. One finding is worth recording: with weights of 1 / target², every row weighs at least about 200, so a minimum-child-weight limit of 1 to 10 could never bind, and that grid returned identical scores. Rescaling the weights to mean 1 in each training fold fixed it. Tuning moved held-out RMSPE from 0.2422 to 0.2417. The model was already close to what the features allow.
Neural networks
Two feed-forward networks were compared, both trained on RMSPE with a softplus output (forecasts stay positive), Adam, and standardized inputs:
Small: one hidden layer of 32 units.
Wide: 128 then 64 units, with dropout 0.2 and weight decay 0.0001.
The number of epochs was set by early stopping on a fifth of the training stocks, never on the stocks being scored. These two nets were picked by hand and trained with a 30-epoch cap. Figure 5 shows what that cap did: same data and settings, only the random seed changed.
Show code
p15 = read(15, "oof_predictions.parquet")p18 = read(18, "oof_nets.parquet")yp = p15["target"].to_numpy()keep = p15["stock_id"].to_numpy() !=11series = [("XGBoost", p15, "tree"), ("Specialists", p15, "specialists"), ("Small net, cap 30", p15, "mlp_small"), ("Small net, cap 80", p18, "mlp_small"), ("Wide net, cap 30", p15, "mlp_wide"), ("Wide net, cap 80", p18, "mlp_wide")]fig, ax = plt.subplots(figsize=(8.0, 3.0))for i, (label, frame, key) inenumerate(series): vals = [rmspe(yp[keep], frame[f"{key}__s{s}"].to_numpy()[keep]) for s inrange(5)] color = ORANGE if"30"in label else (GREEN if"80"in label else BLUE) ax.plot([min(vals), max(vals)], [i, i], color=color, lw=3, alpha=0.4) ax.scatter(vals, [i] *5, s=45, color=color, zorder=3) ax.text(max(vals) +0.0006, i, f"range {max(vals) -min(vals):.4f}", va="center", fontsize=9, color=MUTED)ax.set_yticks(range(len(series)), [s[0] for s in series])ax.invert_yaxis()ax.set_xlabel("RMSPE on 85 stocks, one dot per seed")ax.set_xlim(0.229, 0.272)plt.tight_layout()plt.show()
Figure 5: RMSPE on 85 stocks for five random seeds of each model. With a 30-epoch cap most net fits stopped before early stopping could act, and the wide net’s score depended on the seed. With an 80-epoch cap the same nets are better and the seed spread nearly disappears.
At the 30-epoch cap the wide net moved by 0.026 between seeds. That was mostly undertraining, not seed noise: at 80 epochs the range shrinks to a few thousandths. The submitted blend uses the 30-epoch nets, so every model in it is the average of five seeds, which removes most of that variation.
A structured search
We then searched the network itself, with the 80-epoch cap, on the same 38 columns and the same five stock folds: one, two or three hidden layers of 32, 64 or 128 units; dropout 0, 0.1 or 0.3; learning rate 0.0003, 0.001 or 0.003; plus the two original nets as controls. That is fifteen settings at one seed. The three best on all 86 stocks and both controls were then rerun at two more seeds.
Show code
nt = read(21, "stage_a_table.csv").sort("pooled_85", descending=True)names21 = {"small_control": "Original small net (1 × 32)", "wide_control": "Original wide net (128, 64)","dropout0": "2 × 64, dropout 0", "dropout03": "2 × 64, dropout 0.3","lr0003": "2 × 64, lr 0.0003", "lr003": "2 × 64, lr 0.003"}lab = [names21[c] if c in names21 elsef"{c[1]} × {c.split('_w')[1]}"for c in nt["config"]]col = {1: ORANGE, 2: BLUE, 3: GREEN}colors = [col[d] for d in nt["depth"]]fig, axes = plt.subplots(1, 2, figsize=(8.4, 4.6), sharey=True, gridspec_kw={"width_ratios": [1.5, 1]})yy = np.arange(nt.height)axes[0].scatter(nt["pooled_85"], yy, s=50, color=colors, zorder=3)axes[0].set_xlabel("RMSPE, 85 stocks")axes[1].scatter(nt["stock_11"], yy, s=50, color=colors, zorder=3)axes[1].set_xlabel("RMSPE, stock 11 only")axes[0].set_yticks(yy, lab, fontsize=9)for d, c in col.items(): axes[1].scatter([], [], color=c, label=f"{d} hidden layer{'s'if d >1else''}")axes[1].legend(loc="lower right", fontsize=8.5)plt.tight_layout()plt.show()
Figure 6: Fifteen network settings, seed 0. Left: RMSPE on the 85 ordinary stocks, where thirteen of fifteen fall within about 0.005. Right: RMSPE on stock 11 alone, where one hidden layer is far worse than two or three. Stock 11 is why the 86-stock and 85-stock rankings disagree.
On ordinary stocks the architecture barely matters. Too much regularization (dropout 0.3, or three narrow layers) is worse; everything else is close. A learning rate of 0.001 was best; 0.0003 hit the 80-epoch limit in every fold and may simply be undertrained.
Depth mainly helps stock 11, so a ranking on all 86 stocks and a ranking on the 85 pick different winners. We report that disagreement rather than choosing the population that flatters a result.
The best tested net, 2 × 128, beats the original wide net on 67 of 85 stocks, but on the 85 it only ties the seed-averaged small net. Tuning bought robustness on the unusual stock, not a better forecast for ordinary ones.
With 80 epochs the seed range on the 85 is about 0.001, smaller than the differences between settings.
Show code
best = ft.filter(pl.col("config") =="d2_w128").row(0, named=True)print(f"""The tuned net alone ({best['averaged_86']:.4f} on 86) looks better than thesubmitted blend ({blend:.4f}) only because of stock 11; on the 85 the blend islower ({blend85:.4f} against {best['averaged_85']:.4f}). The submitted file wasnot changed. These scores come from reused development folds, so the chosensetting's number is optimistic. Using tuned nets as blend members is a nextstep.""")
The tuned net alone (0.2395 on 86) looks better than the submitted blend (0.2439) only because of stock 11; on the 85 the blend is lower (0.2319 against 0.2325). The submitted file was not changed. These scores come from reused development folds, so the chosen setting’s number is optimistic. Using tuned nets as blend members is a next step.
What worked
Volatility specialists
Windows were split into thirds by current volatility, with cut points set on the training stocks, and each third got its own XGBoost model. A new window is routed by its own current volatility.
Figure 7: RMSPE on 17 held-out stocks by volatility third. The naive forecast fails in wild windows because volatility mean-reverts; a dedicated wild-window model improves on one model there.
On all 86 stocks the specialists beat one model on all five folds and on 82 of 86 stocks.
The regime-weighted blend
Four members, each averaged over five seeds: one XGBoost model, the specialists, the small net and the wide net. Blend weights are non-negative, sum to one, and are fitted separately in each volatility third to minimize RMSPE. They are cross-fitted: the weights scoring a fold are learned from the other four folds’ out-of-fold predictions. Stock 11 is left out of fitting the weights but kept in every score.
Show code
w = a15["weights_final"]["gated"]members = [("tree", "XGBoost", GREY), ("specialists", "Specialists", BLUE), ("mlp_small", "Small net", GREEN), ("mlp_wide", "Wide net", ORANGE)]fig, ax = plt.subplots(figsize=(8.0, 2.7))bottom = np.zeros(3)for key, label, color in members: v = np.array([w[b][key] for b in ("low", "mid", "high")]) ax.barh(range(3), v, left=bottom, color=color, label=label)for i inrange(3):if v[i] >0.08: ax.text(bottom[i] + v[i] /2, i, f"{v[i]:.2f}", ha="center", va="center", color="white", fontweight="bold") bottom += vax.set_yticks(range(3), ["Calm third", "Middle third", "Wild third"])ax.invert_yaxis()ax.set_xlim(0, 1)ax.set_xlabel("Blend weight")ax.legend(loc="lower center", bbox_to_anchor=(0.5, -0.45), ncol=4)ax.grid(False)plt.tight_layout()plt.show()
Figure 8: Final blend weights in each volatility third. The single XGBoost model gets no weight; the specialists anchor every third, the wide net helps in calm windows and the small net in wild ones.
The blend works because the members make different mistakes: the percentage errors of trees and nets correlate at about 0.92 to 0.96, so averaging cancels part of each.
Figure 9: Each training stock’s out-of-fold RMSPE under the first submitted model and under the blend (log scales). Points below the diagonal improved.
This is not one stock moving the average: almost every stock got a little better.
A stricter check: nested blend weights
The weights that score one fold are learned from the other four folds’ out-of-fold forecasts, but the models that made those forecasts were trained partly on the scored fold. A stricter test refits everything inside each outer training set: five inner stock folds, all four members retrained at all five seeds (500 extra fits), and the weights learned only from those inner forecasts. The outer fold is touched only for scoring.
Show code
n19 = {r["candidate"]: r for r in read(19, "stages.csv").iter_rows(named=True)}rows19 = [("legacy_gated_blend", "Submitted recipe, cross-fitted weights (workflow 15)"), ("nested_gated_blend", "Same recipe, nested weights (workflow 19)"), ("equal_blend", "Equal-weight blend, for reference")]lines = ["| Evaluation | All 86 | 85 stocks | Stock 11 |", "|---|---:|---:|---:|"]for key, label in rows19: r = n19[key] lines.append(f"| {label} | {r['pooled_86']:.4f} | {r['pooled_85']:.4f} | {r['stock_11']:.3f} |")print("\n".join(lines))
The nested score is essentially the same as the one we reported, so the 0.244 is not an artifact of fitting weights on the data that scores them. This check does not remove an older optimism: the recipe itself (which members, thirds of volatility, leaving stock 11 out of the weights) was chosen after looking at these folds.
What did not work
Each idea below was tested as one bounded experiment, with the adoption rule written down before the run: adopt only if the blend improves on the 85 ordinary stocks by more than 0.0005 and on at least four of five folds.
Show code
ref = read(16, "stages.csv").filter(pl.col("candidate") =="a15_gated").row(0, named=True)tests = [ (16, "no11_gated", "Retrain every member without stock 11"), (16, "funnel_on_a15_gated", "Outlier funnel: classify risky windows and shrink their forecasts"), (18, "long_nets_gated", "Train the nets longer (epoch cap 30 → 80)"), (20, "added_gated", "Add path features to one net, as a fifth blend member"), (22, "median", "Median of the four members instead of fitted weights"), (22, "lower", "Lower of the four forecasts"),]lines = ["| Idea | RMSPE, 85 stocks | Change | Folds better | Decision |", "|----------------------------------|--------:|--------:|-------:|----------:|"]lines.append(f"| **Submitted blend** | **{ref['pooled_85']:.5f}** | | | |")for attempt, cand, label in tests: r = read(attempt, "stages.csv").filter(pl.col("candidate") == cand).row(0, named=True) change = r["pooled_85"] - ref["pooled_85"] lines.append(f"| {label} | {r['pooled_85']:.5f} | {change:+.5f} | {r['folds_better_85']} of 5 | Not adopted |")print("\n".join(lines))
Idea
RMSPE, 85 stocks
Change
Folds better
Decision
Submitted blend
0.23188
Retrain every member without stock 11
0.23249
+0.00060
2 of 5
Not adopted
Outlier funnel: classify risky windows and shrink their forecasts
0.23213
+0.00024
2 of 5
Not adopted
Train the nets longer (epoch cap 30 → 80)
0.23143
-0.00045
4 of 5
Not adopted
Add path features to one net, as a fifth blend member
0.23180
-0.00009
5 of 5
Not adopted
Median of the four members instead of fitted weights
0.23315
+0.00126
0 of 5
Not adopted
Lower of the four forecasts
0.25075
+0.01886
0 of 5
Not adopted
The outlier funnel could not tell in advance which windows would be badly overpredicted (classifier AUC about 0.62). Shrinking forecasts helped stock 11 and cost the ordinary stocks.
Longer net training improved the nets alone by a lot (wide net 0.250 to 0.237) but the blend by only 0.0005, because the blend already covered most of those errors.
Adding path features to one net produced a near copy of that net (its errors correlate 0.994 with the original), not a new kind of member. Useful diversity came from different model types, not from more columns.
Simpler combiners (the median, or the lowest of the four forecasts) needed no fitting but were worse on all five folds. Taking the lowest forecast helps stock 11, which is overpredicted, and hurts the ordinary stocks. The fitted weights do real work.
Estimating the test score
Half of the competition rank is how close our estimate is to the real test RMSPE, so the estimate was built as carefully as the model. We drew 26 stocks at random from the training stocks’ out-of-fold errors, the size of the test set, and pooled their RMSPE, 20,000 times.
Show code
# Squared percentage error and row count per training stock, from the blend's out-of-fold rows.st = ( oof.with_columns(((pl.col("target") - pl.col("gated_blend")) / pl.col("target")).pow(2).alias("sq")) .group_by("stock_id").agg(pl.col("sq").sum().alias("sse"), pl.len().alias("rows")) .sort("stock_id"))sse, n, sid = st["sse"].to_numpy(), st["rows"].to_numpy(), st["stock_id"].to_numpy()rng = np.random.default_rng(0)def draws(mask): idx = rng.choice(np.flatnonzero(mask), size=(20000, 26), replace=True)return np.sqrt(sse[idx].sum(axis=1) / n[idx].sum(axis=1))d85, d86 = draws(sid !=11), draws(np.ones_like(sid, dtype=bool))fig, ax = plt.subplots(figsize=(8.0, 3.0))bins = np.linspace(0.20, 0.34, 120)ax.hist(d86, bins=bins, color=ORANGE, alpha=0.55, label="Stock 11 allowed")ax.hist(d85, bins=bins, color=BLUE, alpha=0.8, label="85 ordinary stocks")ax.axvline(estimate["estimated_rmspe"], color=INK, lw=2, label=f"Submitted estimate {estimate['estimated_rmspe']:.4f}")ax.set_xlabel("Pooled RMSPE of 26 stocks")ax.set_ylabel("Draws")ax.legend()plt.tight_layout()plt.show()p05, p50, p95 = np.percentile(d85, [5, 50, 95])print(f"85 ordinary stocks: median {p50:.4f}, 90% of draws between {p05:.3f} and {p95:.3f}")
Figure 10: Pooled RMSPE of 20,000 random sets of 26 training stocks, scored with the blend’s out-of-fold errors. Allowing stock 11 creates the right-hand humps; no test stock has a book like it.
85 ordinary stocks: median 0.2315, 90% of draws between 0.221 and 0.244
Stock 11 was left out of the estimate because its book is about three standardized units from any other stock’s, while the typical gap between nearest stocks is 0.23. The remaining question is whether the 26 test stocks are easier or harder than average. A stock’s error turned out to be predictable from its book profile (depth, spread, volatility and activity, from features only, never test labels): the five most similar training stocks predict a stock’s error 45% better than a constant. The test stocks have thinner books than the training stocks (334 book updates per window against 385), and thinner books are harder. Applying the five-nearest-stock model to the test stocks gives the submitted estimate of 0.2333, slightly above the plain median. Every reasonable method we tried landed between 0.231 and 0.237.
Limitations and next steps
Selection used the same out-of-fold data that scores it. Nested weight fitting gives the same score, but the choice of members, the regime rule, and leaving stock 11 out of the weights (decided after the first run) were made after seeing these scores, so 0.244 may be slightly optimistic.
The network search was partial. Depth and width were crossed at one dropout and learning rate; interactions were not estimated, and the slowest learning rate ran out of epochs.
Stock 11 is unresolved. Its windows with near-zero movement are hard to forecast in percentage terms, and nothing we tried fixed it without hurting other stocks.
With more time: tuned 80-epoch nets as blend members (which means rebuilding the blend and the estimate); sequence models (recurrent or convolutional) on the raw 600-second path instead of summary features; blend weights that vary smoothly with volatility rather than by thirds; stability selection (repeat block removal over resampled stocks and keep what survives); and training that leans toward stocks whose books resemble the test set.
Reproducibility
Each step is a numbered workflow folder with its own code, saved outputs, assumptions and notes. The submission is workflow_attempt_17/outputs/final_submission.csv (the blend built in workflow_attempt_15), and the estimate is workflow_attempt_17/outputs/final_estimate.json. This report reads only those saved outputs.