File size: 6,460 Bytes
ebcde1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Read-only Streamlit dashboard for a completed microstructure run bundle."""

from __future__ import annotations

import argparse
import json
import os
import sys
from collections.abc import Mapping, Sequence
from pathlib import Path
from typing import Any

import streamlit as st

from microstructure.provenance import sha256_file
from microstructure.reporting import RunBundle, RunBundleError, load_run_bundle

PROJECT_ROOT = Path(__file__).resolve().parents[1]
DEFAULT_RUN_DIR = PROJECT_ROOT / "artifacts" / "runs" / "sample-smoke"


def _argument_run_dir(arguments: Sequence[str]) -> Path:
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("--run-dir")
    parsed, _ = parser.parse_known_args(arguments)
    configured = parsed.run_dir or os.environ.get("MICROSTRUCTURE_RUN_DIR")
    return Path(configured).expanduser() if configured else DEFAULT_RUN_DIR


def _integrity_key(run_dir: Path) -> str:
    checksum_path = run_dir / "checksums.sha256"
    return sha256_file(checksum_path) if checksum_path.is_file() else "missing"


@st.cache_resource(show_spinner=False)
def _cached_bundle(run_dir: str, integrity_key: str) -> RunBundle:
    del integrity_key  # It is part of Streamlit's cache key.
    return load_run_bundle(run_dir)


def _rows(rows: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
    return [dict(row) for row in rows]


def _show_rows(rows: Sequence[Mapping[str, Any]], empty_message: str) -> None:
    if rows:
        st.dataframe(_rows(rows), hide_index=True)
    else:
        st.info(empty_message)


def _show_overview(bundle: RunBundle) -> None:
    st.subheader("Evidence and lineage")
    columns = st.columns(4)
    columns[0].metric("Run", bundle.run_id)
    columns[1].metric("Evidence", bundle.evidence_tier)
    columns[2].metric("Symbols", len(bundle.symbols))
    columns[3].metric(
        "Git state",
        "dirty" if bool(cast_mapping(bundle.provenance.get("git")).get("dirty")) else "clean",
    )
    st.markdown(
        f"**Observed UTC period:** `{bundle.observed_start_utc}` → `{bundle.observed_end_utc}`"
    )
    st.markdown(f"**Instruments:** {', '.join(bundle.symbols)}")
    st.caption(
        "The dashboard reads serialized artifacts only. It does not download data, "
        "train models, or simulate orders."
    )


def cast_mapping(value: Any) -> Mapping[str, Any]:
    return value if isinstance(value, Mapping) else {}


def _show_quality(bundle: RunBundle) -> None:
    st.subheader("Non-mutating validation findings")
    if bundle.quality:
        st.json(dict(bundle.quality), expanded=True)
    else:
        st.info("No quality summary was serialized in this completed run bundle.")
    st.caption("Findings are displayed as recorded; this app does not repair observations.")


def _show_market_state(bundle: RunBundle) -> None:
    st.subheader("Market-state aggregates")
    _show_rows(
        bundle.market_state,
        "No dashboard-safe market-state aggregate was serialized for this run.",
    )
    st.caption(
        "Only bounded aggregates are loaded here; the dashboard never scans external raw data."
    )


def _show_predictions(bundle: RunBundle) -> None:
    st.subheader("Serialized predictive diagnostics")
    _show_rows(
        bundle.predictive_metrics,
        "No predictive metric rows were serialized for this run.",
    )
    st.caption(
        "Predictive metrics do not establish fillability or performance after execution costs."
    )


def _show_execution(bundle: RunBundle) -> None:
    st.subheader("Serialized simulated performance")
    _show_rows(
        bundle.execution_metrics,
        "No execution or simulated-performance rows were serialized for this run.",
    )
    st.markdown("#### Execution sensitivity grid")
    _show_rows(
        bundle.execution_sensitivity,
        "No execution-sensitivity rows were serialized for this run.",
    )
    assumptions = bundle.manifest.get("execution_assumptions")
    if isinstance(assumptions, Mapping) and assumptions:
        st.markdown("#### Recorded execution assumptions")
        st.json(dict(assumptions), expanded=False)
    st.caption(
        "Fees, latency, fills, adverse selection, inventory, and liquidation are model "
        "assumptions—not realized trading outcomes."
    )


def _show_reproducibility(bundle: RunBundle) -> None:
    st.subheader("Frozen provenance")
    st.markdown(f"**Run directory:** `{bundle.root}`")
    st.markdown(f"**Configuration SHA-256:** `{bundle.provenance.get('config_sha256', 'N/A')}`")
    st.markdown("#### Run manifest")
    st.code(json.dumps(bundle.manifest, indent=2, sort_keys=True), language="json")
    st.markdown("#### Provenance")
    st.code(json.dumps(bundle.provenance, indent=2, sort_keys=True), language="json")
    st.caption(
        "The completion marker and checksum manifest were verified before these values loaded."
    )


def render_dashboard(bundle: RunBundle) -> None:
    """Render a verified bundle without changing it."""
    st.title("Order Flow to Price Impact")
    if bundle.evidence_tier in {"SYNTHETIC_SMOKE", "PUBLIC_SAMPLE_PARTIAL"}:
        st.warning(bundle.watermark)
    else:
        st.info(bundle.watermark)

    labels = (
        "Overview",
        "Data Quality",
        "Market State",
        "Predictions",
        "Simulated Performance",
        "Reproducibility & Limitations",
    )
    tabs = st.tabs(labels)
    with tabs[0]:
        _show_overview(bundle)
    with tabs[1]:
        _show_quality(bundle)
    with tabs[2]:
        _show_market_state(bundle)
    with tabs[3]:
        _show_predictions(bundle)
    with tabs[4]:
        _show_execution(bundle)
    with tabs[5]:
        _show_reproducibility(bundle)


def main(arguments: Sequence[str] | None = None) -> None:
    st.set_page_config(page_title="Microstructure Research", layout="wide")
    run_dir = _argument_run_dir(sys.argv[1:] if arguments is None else arguments).resolve()
    try:
        bundle = _cached_bundle(str(run_dir), _integrity_key(run_dir))
    except RunBundleError as error:
        st.title("Order Flow to Price Impact")
        st.error(f"Run bundle is incomplete or invalid: {error}")
        st.caption(
            "Select a directory containing run_manifest.json, provenance.json, "
            "checksums.sha256, and the final _SUCCESS marker."
        )
        st.stop()
    render_dashboard(bundle)


if __name__ == "__main__":
    main()