-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreport.py
More file actions
559 lines (526 loc) · 24.9 KB
/
Copy pathreport.py
File metadata and controls
559 lines (526 loc) · 24.9 KB
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
"""Build the Execution TCA Lab's single static HTML tear-sheet."""
import argparse
from html import escape
from pathlib import Path
from typing import Any, Mapping, Optional
import matplotlib.pyplot as plt
import pandas as pd
import yaml
from exectca.cross_section import (
build_cross_section,
load_cross_section_events,
plot_cross_section_markouts,
plot_cross_section_spread,
)
from exectca.impact_audit import (
audit_parent_costs,
build_depth_walk_sample,
calibrate_depth_model,
plot_impact_audit,
)
from exectca.loaders import check_trade_sign, load_engine_outputs, load_lobster
from exectca.microstructure import (
intraday_patterns,
markout_curve,
plot_effective_vs_realized,
plot_markout_curve,
trade_metrics,
)
from exectca.monitoring import (
controlled_deterioration_demo,
plot_cusum_demo,
widened_impact_batch,
)
from exectca.reproducibility import write_run_manifest
from exectca.tca import (
add_regime_buckets,
parent_execution_metrics,
plot_cost_vs_size,
summarize_cost_by_regime,
)
def build_report(config_path: Path, output_path: Optional[Path] = None) -> Path:
"""Recompute analytics and write the one static tear-sheet."""
config_path = config_path.resolve()
root = config_path.parent.parent
config = yaml.safe_load(config_path.read_text(encoding="utf-8"))
run_directory = root / config["run"]["output_dir"] / config["run"]["id"]
analysis_directory = run_directory / "analysis"
analysis_directory.mkdir(parents=True, exist_ok=True)
output_path = output_path.resolve() if output_path else run_directory / "tearsheet.html"
engine = load_engine_outputs(run_directory)
module_a = _build_module_a(root, config, analysis_directory)
cross_section = _build_cross_section(root, config, analysis_directory)
module_b = _build_module_b(config, engine, analysis_directory)
impact_audit = _build_impact_audit(
root, config, engine, module_b["metrics"], analysis_directory
)
monitoring = _build_monitoring(config, engine, module_b["metrics"], analysis_directory)
html = _render_html(
config,
engine,
module_a,
cross_section,
module_b,
impact_audit,
monitoring,
)
output_path.write_text(html, encoding="utf-8")
write_run_manifest(config_path, run_directory)
return output_path
def _build_module_a(
root: Path,
config: Mapping[str, Any],
output: Path,
) -> Optional[Mapping[str, Any]]:
if config["data"]["label"] != "REAL":
return None
events = load_lobster(
root / config["data"]["message_path"],
root / config["data"]["orderbook_path"],
)
sign_check = check_trade_sign(events)
if not sign_check.passed:
raise ValueError("REAL trade-sign sanity check failed")
horizons = config["analysis"]["markout_horizons_seconds"]
metrics = trade_metrics(events, horizons)
curve = markout_curve(metrics, horizons)
intraday = intraday_patterns(events, config["analysis"]["intraday_bucket_minutes"])
metrics.to_csv(output / "microstructure_trade_metrics_REAL.csv", index=False)
curve.to_csv(output / "markout_curve_REAL.csv", index=False)
intraday.to_csv(output / "intraday_patterns_REAL.csv", index=False)
_save_plot(plot_markout_curve(curve)[0], output / "markout_curve_REAL.png")
_save_plot(
plot_effective_vs_realized(metrics, max(horizons))[0],
output / "effective_vs_realized_REAL.png",
)
figure, axis = plt.subplots(figsize=(7, 4))
axis.plot(intraday["bucket_start_seconds"] / 3_600.0, intraday["mean_spread_bps"])
axis.set(
title=f"REAL {config['data']['symbol']} — intraday quoted spread",
xlabel="US/Eastern hour",
ylabel="Mean spread (bps)",
)
_save_plot(figure, output / "intraday_spread_REAL.png")
return {
"events": events,
"metrics": metrics,
"curve": curve,
"intraday": intraday,
"sign_check": sign_check,
}
def _build_cross_section(
root: Path,
config: Mapping[str, Any],
output: Path,
) -> Optional[Mapping[str, Any]]:
symbol_events = load_cross_section_events(config, root)
if len(symbol_events) < 2:
return None
horizons = config["analysis"]["markout_horizons_seconds"]
summary, curves = build_cross_section(symbol_events, horizons)
summary.to_csv(output / "cross_section_summary_REAL.csv", index=False)
curves.to_csv(output / "cross_section_markouts_REAL.csv", index=False)
_save_plot(plot_cross_section_markouts(curves)[0], output / "cross_section_markouts_REAL.png")
_save_plot(plot_cross_section_spread(summary)[0], output / "cross_section_spread_REAL.png")
return {"summary": summary, "curves": curves}
def _build_module_b(
config: Mapping[str, Any],
engine: Mapping[str, pd.DataFrame],
output: Path,
) -> Mapping[str, Any]:
metrics = parent_execution_metrics(engine["parents"], engine["fills"], engine["quote_snapshots"])
bucketed = add_regime_buckets(
metrics,
config["analysis"]["size_participation_edges"],
config["analysis"]["spread_quantiles"],
config["analysis"]["volatility_quantiles"],
)
regimes = summarize_cost_by_regime(bucketed)
bucketed.to_csv(output / "parent_metrics_SIMULATED.csv", index=False)
regimes.to_csv(output / "cost_by_regime_SIMULATED.csv", index=False)
_save_plot(plot_cost_vs_size(metrics)[0], output / "cost_vs_size_SIMULATED.png")
figure, axis = plt.subplots(figsize=(6, 4))
values = [
metrics["execution_cost_bps"].mean(),
metrics["opportunity_cost_bps"].mean(),
metrics["implementation_shortfall_bps"].mean(),
]
axis.bar(["Execution", "Opportunity", "Total IS"], values)
axis.axhline(0.0, color="black", linewidth=0.8)
axis.set(title="SIMULATED VWAP — implementation shortfall", ylabel="Mean cost (bps)")
_save_plot(figure, output / "is_decomposition_SIMULATED.png")
return {"metrics": metrics, "bucketed": bucketed, "regimes": regimes}
def _build_impact_audit(
root: Path,
config: Mapping[str, Any],
engine: Mapping[str, pd.DataFrame],
parent_metrics: pd.DataFrame,
output: Path,
) -> Optional[Mapping[str, Any]]:
section = config.get("impact_audit") or {}
if not section.get("enabled", False) or config["data"]["label"] != "REAL":
return None
levels = int(section.get("depth_levels", 5))
depth_walks = build_depth_walk_sample(
root / section["depth_message_path"],
root / section["depth_orderbook_path"],
engine["fills"],
levels=levels,
tick_size=float(config["fill_model"]["tick_size"]),
configured_kappa=float(config["fill_model"]["kappa"]),
over_displayed_multiplier=float(config["fill_model"]["over_displayed_multiplier"]),
)
edges = section.get("participation_edges", [0, 0.25, 0.5, 1, 2, 5, 20])
audit = calibrate_depth_model(
depth_walks,
calibration_end_seconds=float(section.get("calibration_end_seconds", 35_700)),
configured_kappa=float(config["fill_model"]["kappa"]),
over_displayed_multiplier=float(config["fill_model"]["over_displayed_multiplier"]),
tick_size=float(config["fill_model"]["tick_size"]),
participation_edges=edges,
minimum_bin_observations=int(section.get("minimum_bin_observations", 3)),
)
parents, portfolio = audit_parent_costs(
parent_metrics,
depth_walks,
accepted_kappa=audit["accepted_kappa"],
candidate_kappa=audit["candidate_kappa"],
tick_size=float(config["fill_model"]["tick_size"]),
)
depth_walks.to_csv(output / "impact_audit_l5_walks_REAL_vs_SIMULATED.csv", index=False)
audit["validation"].to_csv(output / "impact_audit_l5_holdout_REAL_vs_SIMULATED.csv", index=False)
audit["curve"].to_csv(output / "impact_audit_curve_REAL_vs_SIMULATED.csv", index=False)
audit["summary"].to_csv(output / "impact_audit_summary_REAL_vs_SIMULATED.csv", index=False)
parents.to_csv(output / "parent_impact_audit_SIMULATED.csv", index=False)
portfolio.to_csv(output / "portfolio_impact_audit_SIMULATED.csv", index=False)
audit["support"].to_csv(output / "impact_audit_l5_support_SIMULATED.csv", index=False)
figure, _ = plot_impact_audit(audit["curve"], audit["support"])
_save_plot(figure, output / "impact_realism_audit_REAL_vs_SIMULATED.png")
audit["parents"] = parents
audit["portfolio"] = portfolio
audit["depth_walks"] = depth_walks
audit["depth_levels"] = levels
return audit
def _build_monitoring(
config: Mapping[str, Any],
engine: Mapping[str, pd.DataFrame],
baseline_metrics: pd.DataFrame,
output: Path,
) -> Mapping[str, Any]:
multiplier = config["monitoring"]["deterioration_impact_multiplier"]
stressed_parents, stressed_fills = widened_impact_batch(
engine["parents"],
engine["fills"],
multiplier,
config["fill_model"]["tick_size"],
)
stressed_metrics = parent_execution_metrics(
stressed_parents,
stressed_fills,
engine["quote_snapshots"],
)
order = ["start_seconds", "requested_size", "side"]
baseline_ordered = baseline_metrics.sort_values(order).reset_index(drop=True)
stressed_ordered = stressed_metrics.sort_values(order).reset_index(drop=True)
trace = controlled_deterioration_demo(
baseline_ordered["implementation_shortfall_bps"],
stressed_ordered["implementation_shortfall_bps"],
config["monitoring"]["slack_bps"],
config["monitoring"]["threshold_bps"],
)
stressed_ordered.to_csv(output / "widened_impact_metrics_SIMULATED.csv", index=False)
trace.to_csv(output / "cusum_controlled_demo_SIMULATED.csv", index=False)
_save_plot(plot_cusum_demo(trace)[0], output / "cusum_controlled_demo_SIMULATED.png")
return {
"baseline": baseline_ordered,
"stressed": stressed_ordered,
"trace": trace,
"multiplier": multiplier,
}
def _render_html(
config: Mapping[str, Any],
engine: Mapping[str, pd.DataFrame],
module_a: Optional[Mapping[str, Any]],
cross_section: Optional[Mapping[str, Any]],
module_b: Mapping[str, Any],
impact_audit: Optional[Mapping[str, Any]],
monitoring: Mapping[str, Any],
) -> str:
metrics = module_b["metrics"]
size_curve = (
metrics.groupby("requested_size", as_index=False)
.agg(
mean_is_bps=("implementation_shortfall_bps", "mean"),
mean_slippage_bps=("vwap_slippage_bps", "mean"),
mean_participation=("size_participation", "mean"),
)
.sort_values("requested_size")
)
baseline_mean = monitoring["baseline"]["implementation_shortfall_bps"].mean()
stressed_mean = monitoring["stressed"]["implementation_shortfall_bps"].mean()
alarms = monitoring["trace"].loc[monitoring["trace"]["new_alarm"]]
first_alarm = None if alarms.empty else alarms.iloc[0]
findings = []
if module_a is not None:
max_horizon = module_a["curve"].iloc[-1]
findings.append(
f"REAL visible trades paid {module_a['metrics']['effective_spread_bps'].mean():.3f} bps "
f"effective spread on average; by {max_horizon.horizon_seconds:g}s, signed markout "
f"was {max_horizon.markout_bps:.3f} bps and realized spread was "
f"{max_horizon.realized_spread_bps:.3f} bps."
)
if cross_section is not None:
cs = cross_section["summary"]
lo = cs.loc[cs["mean_effective_spread_bps"].idxmin()]
hi = cs.loc[cs["mean_effective_spread_bps"].idxmax()]
worst_adverse = cs.loc[cs["adverse_selection_bps"].idxmax()]
findings.append(
f"Across {len(cs)} REAL names on {config['data']['date']}, mean effective spread ranged "
f"from {lo['mean_effective_spread_bps']:.3f} bps ({lo['symbol']}) to "
f"{hi['mean_effective_spread_bps']:.3f} bps ({hi['symbol']}); adverse selection by "
f"{cs['horizon_seconds'].iloc[0]:g}s was largest for {worst_adverse['symbol']} "
f"({worst_adverse['adverse_selection_bps']:.3f} bps)."
)
if impact_audit is not None:
audit_row = impact_audit["summary"].iloc[0]
portfolio_row = impact_audit["portfolio"].iloc[0]
findings.append(
f"REAL L5 depth produced candidate κ={audit_row['l5_candidate_kappa']:.4f} "
f"versus configured κ={audit_row['configured_kappa']:.4f}, but the candidate was "
f"rejected: holdout MAE worsened from {audit_row['configured_mae_bps']:.4f} to "
f"{audit_row['candidate_mae_bps']:.4f} bps. Configured immediate cost still "
f"underpriced supported L5 walks by {-audit_row['configured_bias_bps']:.4f} bps."
)
findings.append(
f"REAL five-level depth fully covered "
f"{100 * audit_row['simulated_share_fraction_fully_supported_l5']:.1f}% of "
f"SIMULATED child shares. Because the candidate failed holdout, accepted portfolio "
f"IS remains {portfolio_row['portfolio_support_adjusted_is_bps']:.3f} bps. "
f"Extrapolating the rejected candidate beyond L5 would show "
f"{portfolio_row['portfolio_rejected_candidate_extrapolation_is_sensitivity_bps']:.3f} "
f"bps and is sensitivity only."
)
findings.append(
f"SIMULATED VWAP mean implementation shortfall was {metrics['implementation_shortfall_bps'].mean():.3f} "
f"bps and mean interval-VWAP slippage was {metrics['vwap_slippage_bps'].mean():.3f} bps."
)
findings.append(
f"The controlled {monitoring['multiplier']:g}x impact batch raised mean simulated IS by "
f"{stressed_mean - baseline_mean:.3f} bps; "
+ (
f"CUSUM first crossed its threshold on stressed parent {int(first_alarm.batch_observation)}."
if first_alarm is not None
else "CUSUM did not cross the configured threshold."
)
)
smallest = size_curve.iloc[0]
largest = size_curve.iloc[-1]
recommendation = (
f"For this simulated schedule, keep participation below roughly 10% or lengthen the "
f"execution window when liquidity is thin: increasing parent size from "
f"{int(smallest.requested_size):,} to {int(largest.requested_size):,} shares raised mean "
f"IS from {smallest.mean_is_bps:.3f} to {largest.mean_is_bps:.3f} bps."
)
if impact_audit is not None:
unsupported = impact_audit["portfolio"].iloc[0][
"unsupported_simulated_share_fraction"
]
recommendation = (
f"Keep κ explicitly uncalibrated: the L5 candidate failed holdout and the configured "
f"model underprices supported walks. Replace the one-parameter curve or split/leave "
f"residual quantity unfilled for the {100 * unsupported:.1f}% of shares beyond L5."
)
module_a_html = _module_a_html(module_a)
cross_section_html = _cross_section_html(cross_section)
impact_audit_html = _impact_audit_html(impact_audit)
summary_rows = [
("Symbol / date", f"{config['data']['symbol']} / {config['data']['date']}"),
("Market source", config["data"]["label"]),
("Market events", f"{len(engine['quote_snapshots']):,}"),
("Simulated parents / fills", f"{len(engine['parents'])} / {len(engine['fills'])}"),
("Fill model", f"VWAP, kappa={config['fill_model']['kappa']}"),
]
summary_html = "".join(
f"<tr><th>{escape(name)}</th><td>{escape(str(value))}</td></tr>" for name, value in summary_rows
)
findings_html = "".join(f"<li>{escape(finding)}</li>" for finding in findings)
label_statement = (
'<span class="REAL">REAL market data</span> is used for microstructure. Parent orders '
'and fills are always <span class="SIMULATED">SIMULATED</span>.'
if module_a is not None
else 'Market input and execution records are <span class="SIMULATED">SIMULATED</span>. '
'REAL microstructure findings are intentionally omitted.'
)
return f"""<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Execution TCA Lab — Tear-sheet</title>
<style>
body{{font:15px/1.5 system-ui,sans-serif;max-width:1100px;margin:32px auto;padding:0 20px;color:#17202a}}
h1,h2{{line-height:1.2}} .grid{{display:grid;grid-template-columns:repeat(auto-fit,minmax(430px,1fr));gap:18px}}
.card{{border:1px solid #d5d8dc;border-radius:8px;padding:18px;background:#fff}} img{{width:100%;height:auto}}
table{{border-collapse:collapse;width:100%}} th,td{{border-bottom:1px solid #e5e7e9;padding:7px;text-align:right}}
th:first-child,td:first-child{{text-align:left}} .REAL{{color:#146b3a;font-weight:700}} .SIMULATED{{color:#9a5b00;font-weight:700}}
.caveat{{background:#fff4d6;border-left:4px solid #d69200;padding:12px}} .recommendation{{background:#eaf2f8;padding:14px}}
</style></head><body>
<h1>Execution TCA Lab — {escape(config['data']['symbol'])} tear-sheet</h1>
<p>{label_statement}</p>
<section class="card"><h2>Data and run summary</h2><table>{summary_html}</table></section>
{module_a_html}
{cross_section_html}
{impact_audit_html}
<h2>Module B — execution quality <span class="SIMULATED">SIMULATED</span></h2>
<div class="grid"><div class="card"><img src="analysis/is_decomposition_SIMULATED.png" alt="IS decomposition"></div>
<div class="card"><img src="analysis/cost_vs_size_SIMULATED.png" alt="Cost by size"></div></div>
<section class="card"><h3>Cost by size</h3>{size_curve.to_html(index=False, float_format=lambda x: f'{x:.4f}', border=0)}</section>
<h2>Monitoring</h2><p class="caveat"><strong>CONTROLLED DEMO:</strong> this is a simulated {monitoring['multiplier']:g}x
fill-impact shift. Production monitoring would operate on rolling live execution cost.</p>
<div class="card"><img src="analysis/cusum_controlled_demo_SIMULATED.png" alt="Controlled CUSUM demo"></div>
<section class="card"><h2>Findings in bps</h2><ol>{findings_html}</ol>
<p class="recommendation"><strong>Recommendation:</strong> {escape(recommendation)}</p></section>
</body></html>"""
def _module_a_html(module_a: Optional[Mapping[str, Any]]) -> str:
if module_a is None:
return """<section class="card"><h2>Module A — unavailable</h2><p class="caveat">The configured market source is
SIMULATED. Microstructure findings are intentionally omitted rather than presented as real.</p></section>"""
curve_table = module_a["curve"].to_html(index=False, float_format=lambda x: f"{x:.4f}", border=0)
return f"""<h2>Module A — microstructure <span class="REAL">REAL</span></h2>
<div class="grid"><div class="card"><img src="analysis/markout_curve_REAL.png" alt="Markout curve"></div>
<div class="card"><img src="analysis/effective_vs_realized_REAL.png" alt="Effective versus realized spread"></div>
<div class="card"><img src="analysis/intraday_spread_REAL.png" alt="Intraday spread"></div>
<div class="card"><h3>Forward metrics</h3>{curve_table}</div></div>"""
def _cross_section_html(cross_section: Optional[Mapping[str, Any]]) -> str:
if cross_section is None:
return ""
display = cross_section["summary"][
[
"symbol",
"events",
"trades",
"mean_price",
"mean_quoted_spread_bps",
"mean_effective_spread_bps",
"adverse_selection_bps",
"markout_bps",
]
]
table = display.to_html(index=False, float_format=lambda x: f"{x:.4f}", border=0)
horizon = cross_section["summary"]["horizon_seconds"].iloc[0]
return f"""<h2>Module A — cross-section across symbols <span class="REAL">REAL</span></h2>
<p>Same trading day, genuine LOBSTER trades only; forward metrics shown at the {horizon:g}s horizon.</p>
<div class="grid"><div class="card"><img src="analysis/cross_section_markouts_REAL.png" alt="Markout by symbol"></div>
<div class="card"><img src="analysis/cross_section_spread_REAL.png" alt="Spread versus adverse selection by symbol"></div>
<div class="card"><h3>Per-symbol microstructure</h3>{table}</div></div>"""
def _impact_audit_html(audit: Optional[Mapping[str, Any]]) -> str:
if audit is None:
return ""
summary = audit["summary"].iloc[0]
portfolio = audit["portfolio"].iloc[0]
summary_display = pd.DataFrame(
[
(
"Calibration / holdout children",
f"{int(summary['calibration_supported_children']):,} / "
f"{int(summary['validation_supported_children']):,}",
),
(
"Configured / L5 candidate / accepted κ",
f"{summary['configured_kappa']:.4f} / "
f"{summary['l5_candidate_kappa']:.4f} / "
f"{summary['accepted_kappa']:.4f}",
),
(
"SIMULATED shares fully covered by L5",
f"{100 * summary['simulated_share_fraction_fully_supported_l5']:.1f}%",
),
(
"REAL L5 holdout walk cost",
f"{summary['mean_l5_walk_cost_bps']:.4f} bps",
),
(
"Configured / candidate holdout bias",
f"{summary['configured_bias_bps']:.4f} / "
f"{summary['candidate_bias_bps']:.4f} bps",
),
(
"Configured / candidate holdout MAE",
f"{summary['configured_mae_bps']:.4f} / "
f"{summary['candidate_mae_bps']:.4f} bps",
),
(
"Candidate accepted",
"YES" if summary["holdout_performance_pass"] else "NO — configured κ retained",
),
(
"L1/L5 top-mid alignment MAE",
f"{summary['top_mid_alignment_mae_ticks']:.4f} ticks",
),
],
columns=["Measure", "Value"],
)
summary_table = summary_display.to_html(index=False, border=0)
curve_columns = [
"participation_bin",
"observations",
"l5_walk_cost_bps",
"configured_cost_bps",
"candidate_cost_bps",
"configured_bias_bps",
"candidate_bias_bps",
]
curve_table = audit["curve"][curve_columns].to_html(
index=False, float_format=lambda value: f"{value:.4f}", border=0
)
portfolio_display = pd.DataFrame(
[
("Raw portfolio IS", f"{portfolio['portfolio_raw_is_bps']:.4f} bps"),
(
"Within-support adjusted IS",
f"{portfolio['portfolio_support_adjusted_is_bps']:.4f} bps",
),
(
"Defensible supported artifact",
f"{portfolio['portfolio_supported_model_artifact_bps']:.4f} bps",
),
(
"Child shares outside REAL support",
f"{100 * portfolio['unsupported_simulated_share_fraction']:.1f}%",
),
(
"Full-extrapolation IS sensitivity",
f"{portfolio['portfolio_rejected_candidate_extrapolation_is_sensitivity_bps']:.4f} bps",
),
(
"Full-extrapolation artifact sensitivity",
f"{portfolio['portfolio_rejected_candidate_extrapolation_artifact_bps']:.4f} bps",
),
],
columns=["Measure", "Value"],
)
portfolio_table = portfolio_display.to_html(index=False, border=0)
return f"""<h2>Impact-realism loop <span class="REAL">REAL</span> audits <span class="SIMULATED">SIMULATED</span></h2>
<p>The simulator's impact term is tested against the executable VWAP obtained by walking the
contemporaneous REAL {audit['depth_levels']}-level book at each child timestamp. κ is fitted on
the first execution window and evaluated on the untouched second window. Module-A forward
markout remains adverse selection; it is not used as a causal impact target.</p>
<p class="caveat"><strong>Support warning:</strong>
{100 * portfolio['unsupported_simulated_share_fraction']:.1f}% of simulated child shares exceed
cumulative L5 displayed depth. Those children retain configured impact. Applying candidate κ
past the fifth level is sensitivity, not calibration. The fitted candidate is accepted only if
it improves second-window MAE; otherwise configured κ remains in the parent results.</p>
<div class="card"><img src="analysis/impact_realism_audit_REAL_vs_SIMULATED.png" alt="Impact realism audit"></div>
<div class="grid"><div class="card"><h3>Holdout audit</h3>{curve_table}</div>
<div class="card"><h3>Calibration summary</h3>{summary_table}</div></div>
<section class="card"><h3>Portfolio effect</h3>{portfolio_table}</section>"""
def _save_plot(figure: plt.Figure, path: Path) -> None:
figure.tight_layout()
figure.savefig(path, dpi=160)
plt.close(figure)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", type=Path, required=True)
parser.add_argument("--output", type=Path)
arguments = parser.parse_args()
report_path = build_report(arguments.config, arguments.output)
print(f"Wrote tear-sheet to {report_path}")
if __name__ == "__main__":
main()