File size: 10,297 Bytes
3f316da | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | #!/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()
|