#!/usr/bin/env python3 """Summarize the prespecified minimum-price-increment structural-loss grid.""" 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", } LAMBDAS = (0.0, 0.5, 1.0, 2.0, 4.0) METRICS = { "endpoint_mse": lambda row: row["test_mse"], "raw_price_mae": lambda row: row["test_lob_metrics"]["raw_price_mae"], "raw_volume_mae": lambda row: row["test_lob_metrics"]["raw_volume_mae"], "joint_validity": lambda row: row["test_lob_metrics"]["joint_five_constraint_snapshot_valid_rate"], "bid_validity": lambda row: row["test_lob_metrics"]["tick_bid_order_valid_rate"], "ask_validity": lambda row: row["test_lob_metrics"]["tick_ask_order_valid_rate"], "spread_validity": lambda row: row["test_lob_metrics"]["tick_spread_valid_rate"], "price_validity": lambda row: row["test_lob_metrics"]["tick_price_positive_valid_rate"], "volume_validity": lambda row: row["test_lob_metrics"]["volume_nonnegative_valid_rate"], "violation_ticks": lambda row: row["test_lob_metrics"]["mean_price_constraint_violation_ticks"], "all_positions_joint_validity": lambda row: row["test_lob_metrics"]["all_positions_joint_five_constraint_snapshot_valid_rate"], "all_positions_violation_ticks": lambda row: row["test_lob_metrics"]["all_positions_mean_price_constraint_violation_ticks"], "downstream_macro_f1": lambda row: row["downstream_after_reconstruction"]["test"]["macro_f1"], } def bootstrap(values: list[float], seed: int = 20260801) -> list[float]: array = np.asarray(values, dtype=np.float64) rng = np.random.default_rng(seed) means = rng.choice(array, size=(10000, len(array)), replace=True).mean(axis=1) return [float(value) for value in np.quantile(means, [0.025, 0.975])] def stock_aggregate(rows: list[dict], metric: str) -> dict: by_stock = {} for stock in sorted({row["stock"] for row in rows}): values = [METRICS[metric](row) for row in rows if row["stock"] == stock] if len(values) != 3: raise ValueError(f"{stock} {metric}: expected three seeds") by_stock[stock] = float(np.mean(values)) values = list(by_stock.values()) return { "mean": float(np.mean(values)), "sd_across_stock_means": float(np.std(values, ddof=1)), "stock_resampling_interval_95": bootstrap(values), "stock_means": by_stock, } def paired_change(index: dict, method: str, weight: float, metric: str) -> dict: by_stock = {} for stock in sorted({key[0] for key in index if key[1] == method}): values = [] for seed in (2026, 2027, 2028): treated = METRICS[metric](index[(stock, method, seed, weight)]) reference = METRICS[metric](index[(stock, method, seed, 0.0)]) values.append(float(treated - reference)) by_stock[stock] = float(np.mean(values)) values = list(by_stock.values()) return { "mean_change": float(np.mean(values)), "stock_resampling_interval_95": bootstrap(values), "stock_changes": by_stock, } def write_csv(path: Path, rows: list[dict]) -> None: path.parent.mkdir(parents=True, exist_ok=True) fields = list(rows[0]) with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=fields) writer.writeheader() writer.writerows(rows) def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--results-dir", action="append", required=True) parser.add_argument("--output-dir", required=True) args = parser.parse_args() rows = [] for directory in args.results_dir: for path in sorted(Path(directory).glob("*.json")): row = json.loads(path.read_text(encoding="utf-8")) if row.get("task") == "reconstruction": rows.append(row) keys = [ (row["stock"], row["method"], row["seed"], float(row["structure_weight"])) for row in rows ] expected_cells = 5 * len(METHOD_LABELS) * 3 * len(LAMBDAS) if len(keys) != expected_cells or len(set(keys)) != len(keys): raise ValueError( f"Structural grid has {len(keys)} cases; expected {expected_cells}" ) expected = { (stock, method, seed, weight) for stock in sorted({row["stock"] for row in rows}) for method in METHOD_LABELS for seed in (2026, 2027, 2028) for weight in LAMBDAS } if set(keys) != expected: raise ValueError("Structural grid contains missing or unexpected cells") index = {key: row for key, row in zip(keys, rows)} grid = {} flat_rows = [] for method in METHOD_LABELS: grid[method] = {} for weight in LAMBDAS: selected = [ row for row in rows if row["method"] == method and float(row["structure_weight"]) == weight ] summaries = { metric: stock_aggregate(selected, metric) for metric in METRICS } changes = { metric: paired_change(index, method, weight, metric) for metric in METRICS } grid[method][str(weight)] = { "absolute": summaries, "paired_change_from_lambda_0": changes, } flat_rows.append( { "model": METHOD_LABELS[method], "lambda": weight, "endpoint_mse": summaries["endpoint_mse"]["mean"], "raw_price_mae": summaries["raw_price_mae"]["mean"], "raw_volume_mae": summaries["raw_volume_mae"]["mean"], "joint_validity_percent": 100.0 * summaries["joint_validity"]["mean"], "joint_validity_change_pp": 100.0 * changes["joint_validity"]["mean_change"], "violation_ticks": summaries["violation_ticks"]["mean"], "violation_ticks_change": changes["violation_ticks"]["mean_change"], "downstream_macro_f1": summaries["downstream_macro_f1"]["mean"], "downstream_macro_f1_change": changes["downstream_macro_f1"]["mean_change"], } ) payload = { "design": { "stocks": 5, "model_families": len(METHOD_LABELS), "seeds": [2026, 2027, 2028], "lambda_grid": list(LAMBDAS), "cells": len(keys), "retained_lambda": 2.0, "selection_rule": "lambda=2 is the common cross-model trade-off setting", "primary_unit": "final reconstructed state in each test window", "sensitivity_unit": "all reconstructed positions", "raw_price_tick_size": 0.01, }, "grid": grid, } output_dir = Path(args.output_dir) output_dir.mkdir(parents=True, exist_ok=True) (output_dir / "structural_tick_sensitivity.json").write_text( json.dumps(payload, indent=2), encoding="utf-8", ) write_csv(output_dir / "structural_tick_sensitivity.csv", flat_rows) case_rows = [] for row in sorted( rows, key=lambda item: ( item["method"], item["stock"], int(item["seed"]), float(item["structure_weight"]), ), ): metrics = row["test_lob_metrics"] case_rows.append( { "stock": row["stock"], "method": row["method"], "seed": row["seed"], "lambda": row["structure_weight"], "endpoint_mse": row["test_mse"], "raw_price_mae": metrics["raw_price_mae"], "raw_volume_mae": metrics["raw_volume_mae"], "joint_validity": metrics[ "joint_five_constraint_snapshot_valid_rate" ], "violation_ticks": metrics[ "mean_price_constraint_violation_ticks" ], "bid_validity": metrics["tick_bid_order_valid_rate"], "ask_validity": metrics["tick_ask_order_valid_rate"], "spread_validity": metrics["tick_spread_valid_rate"], "price_validity": metrics["tick_price_positive_valid_rate"], "volume_validity": metrics["volume_nonnegative_valid_rate"], "all_positions_joint_validity": metrics[ "all_positions_joint_five_constraint_snapshot_valid_rate" ], "all_positions_violation_ticks": metrics[ "all_positions_mean_price_constraint_violation_ticks" ], "downstream_macro_f1": row[ "downstream_after_reconstruction" ]["test"]["macro_f1"], } ) write_csv(output_dir / "structural_case_results.csv", case_rows) write_csv( output_dir / "structural_primary_lambda0_lambda2_cases.csv", [row for row in case_rows if float(row["lambda"]) in {0.0, 2.0}], ) lines = [ "# Minimum-price-increment structural-loss sensitivity", "", "The retained setting is λ=2; the full grid is reported without test-set selection.", "", "| model | λ | endpoint MSE | price MAE | joint validity | Δ validity | violation ticks | Δ violation | downstream F1 |", "|---|---:|---:|---:|---:|---:|---:|---:|---:|", ] for row in flat_rows: lines.append( f"| {row['model']} | {row['lambda']:g} | {row['endpoint_mse']:.4f} " f"| {row['raw_price_mae']:.4f} | {row['joint_validity_percent']:.2f}% " f"| {row['joint_validity_change_pp']:+.2f} pp | {row['violation_ticks']:.3f} " f"| {row['violation_ticks_change']:+.3f} | {row['downstream_macro_f1']:.4f} |" ) (output_dir / "structural_tick_sensitivity.md").write_text( "\n".join(lines) + "\n", encoding="utf-8", ) if __name__ == "__main__": main()