#!/usr/bin/env python3 """Summarize the three-model masked-entry imputation experiment.""" from __future__ import annotations import argparse import csv import json from pathlib import Path import numpy as np METHOD_LABELS = { "timae": "Ti-MAE-based", "lobgrid_timae": "LOBGrid--Ti-MAE reference", "simlob2026": "SimLOB-based", } WEIGHTS = (0.0, 2.0) SEEDS = (2026, 2027, 2028) METRICS = { "masked_mse": lambda row: row["test_lob_metrics"]["region_mse"], "masked_price_mae": lambda row: row["test_lob_metrics"]["region_raw_price_mae"], "masked_volume_mae": lambda row: row["test_lob_metrics"]["region_raw_volume_mae"], "completed_endpoint_mse": lambda row: row["test_lob_metrics"]["endpoint_mse"], "spread_validity": lambda row: row["test_lob_metrics"]["tick_spread_valid_rate"], "joint_validity": lambda row: row["test_lob_metrics"][ "joint_five_constraint_snapshot_valid_rate" ], "violation_ticks": lambda row: row["test_lob_metrics"][ "mean_price_constraint_violation_ticks" ], } def stock_interval(values: list[float], seed: int = 20260802) -> list[float]: array = np.asarray(values, dtype=np.float64) rng = np.random.default_rng(seed) draws = rng.choice(array, size=(20_000, len(array)), replace=True).mean(axis=1) return [float(value) for value in np.quantile(draws, (0.025, 0.975))] def write_csv(path: Path, rows: list[dict[str, object]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=list(rows[0])) writer.writeheader() writer.writerows(rows) def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--results-dir", type=Path, required=True) parser.add_argument("--output-dir", type=Path, required=True) args = parser.parse_args() rows = [] for path in sorted(args.results_dir.glob("*.json")): row = json.loads(path.read_text(encoding="utf-8")) if row.get("task") == "imputation": rows.append(row) stocks = sorted({row["stock"] for row in rows}) expected = { (stock, method, seed, weight) for stock in stocks for method in METHOD_LABELS for seed in SEEDS for weight in WEIGHTS } keys = { ( row["stock"], row["method"], int(row["seed"]), float(row["structure_weight"]), ) for row in rows } if len(stocks) != 5 or keys != expected or len(rows) != len(expected): raise ValueError( f"imputation matrix contains {len(rows)} cases over {len(stocks)} stocks; " f"expected 90 cases over five stocks" ) index = { ( row["stock"], row["method"], int(row["seed"]), float(row["structure_weight"]), ): row for row in rows } summary_rows: list[dict[str, object]] = [] payload: dict[str, object] = { "design": { "stocks": stocks, "methods": list(METHOD_LABELS), "seeds": list(SEEDS), "structure_weights": list(WEIGHTS), "mask_ratio": 0.2, "mask_unit": "individual price and volume entries", "aggregation": "seeds within stock, followed by five stock means", }, "results": {}, } for method, label in METHOD_LABELS.items(): method_payload: dict[str, object] = {} for weight in WEIGHTS: metric_payload: dict[str, object] = {} flat: dict[str, object] = { "method": method, "model": label, "lambda": weight, } for metric, extractor in METRICS.items(): by_stock = { stock: float( np.mean( [ extractor(index[(stock, method, seed, weight)]) for seed in SEEDS ] ) ) for stock in stocks } values = list(by_stock.values()) absolute = float(np.mean(values)) interval = stock_interval(values) if weight == 0.0: changes = {stock: 0.0 for stock in stocks} else: changes = { stock: float( np.mean( [ extractor(index[(stock, method, seed, weight)]) - extractor(index[(stock, method, seed, 0.0)]) for seed in SEEDS ] ) ) for stock in stocks } change_values = list(changes.values()) change = float(np.mean(change_values)) change_interval = stock_interval(change_values, seed=20260803) metric_payload[metric] = { "mean": absolute, "stock_resampling_interval_95": interval, "stock_means": by_stock, "mean_change_from_lambda_0": change, "change_interval_95": change_interval, "stock_changes": changes, } flat[f"{metric}_mean"] = absolute flat[f"{metric}_change_from_lambda_0"] = change method_payload[str(weight)] = metric_payload summary_rows.append(flat) payload["results"][method] = method_payload case_rows: list[dict[str, object]] = [] for row in sorted( rows, key=lambda item: ( item["method"], item["stock"], int(item["seed"]), float(item["structure_weight"]), ), ): case_rows.append( { "stock": row["stock"], "method": row["method"], "seed": row["seed"], "lambda": row["structure_weight"], "best_epoch": row["best_epoch"], **{name: extractor(row) for name, extractor in METRICS.items()}, } ) args.output_dir.mkdir(parents=True, exist_ok=True) (args.output_dir / "imputation_structural_summary.json").write_text( json.dumps(payload, indent=2), encoding="utf-8" ) write_csv(args.output_dir / "imputation_structural_summary.csv", summary_rows) write_csv(args.output_dir / "imputation_structural_cases.csv", case_rows) lines = [ "# Masked-entry imputation and structural-loss results", "", ( "The experiment masks 20% of individual price and volume entries. " "Three seeds are averaged within each stock before the five stock means." ), "", "| Model | lambda | Masked MSE | Price MAE | Spread valid | Joint valid | Violation ticks |", "|---|---:|---:|---:|---:|---:|---:|", ] for row in summary_rows: lines.append( f"| {row['model']} | {float(row['lambda']):g} | " f"{float(row['masked_mse_mean']):.4f} | " f"{float(row['masked_price_mae_mean']):.4f} | " f"{100 * float(row['spread_validity_mean']):.1f}% | " f"{100 * float(row['joint_validity_mean']):.1f}% | " f"{float(row['violation_ticks_mean']):.3f} |" ) (args.output_dir / "imputation_structural_summary.md").write_text( "\n".join(lines) + "\n", encoding="utf-8" ) if __name__ == "__main__": main()