File size: 7,869 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
#!/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()