bit-forecast-arena / src /ui /shell.py
Bit-Trading-Company's picture
CI deploy local
442b828 verified
Raw
History Blame Contribute Delete
59 kB
"""The Arena's visible layer: the design's own markup, rendered from state.
Gradio is the backend here and nothing else -- one `gr.HTML` sink, a hidden
textbox the click bridge writes into, and a hidden button it clicks. Every
control on the page is the `<button>` the design specifies, carrying a
`data-bit` action, because the design is built from 13 buttons against 2 inputs
and Gradio renders something structurally different for the same concepts.
The one rule to keep when editing: **render from capabilities, never from a
model's name.** `caps["output"] == "ohlcv_paths"` is what decides whether the
ghost-path control exists. There is no branch anywhere below that mentions
Kronos, Chronos or TimesFM.
"""
from __future__ import annotations
import pandas as pd
from bit_ui import icons, palette, sidebar
from bit_ui.markup import a, e
from .. import config, view
from ..view import DASH, count, grade_color, num, pct
from . import chart
from .chrome import emit
STYRENE = ("font-family:var(--font-styrene);text-transform:uppercase;"
"letter-spacing:var(--tracking-wide)")
PANEL = "border:1px solid var(--border-default);background:var(--bg-panel)"
HEAD = ("display:flex;align-items:center;gap:8px;padding:7px 10px;"
"border-bottom:1px solid var(--border-default)")
def bit(action: str, value: str = "") -> str:
"""The full `data-bit` attribute for an action, escaped.
`emit()` returns the attribute *value*, not the attribute. Interpolating it
bare renders `<button run:go>`, which is not a data attribute at all: the
delegated listener never matches it and the control does nothing, with no
error anywhere. This wrapper is the only way actions are attached below.
"""
return f'type="button" data-bit="{a(emit(action, value))}"'
def _panel_title(text: str, right: str = "") -> str:
return (f'<div style="{HEAD}">'
f'<span style="{STYRENE};font-size:var(--text-sm)">{e(text)}</span>'
f'{right}</div>')
# --------------------------------------------------------------------------
# Header
# --------------------------------------------------------------------------
def header(state: dict, data: dict) -> str:
archived = data.get("archived_total")
resolved = data.get("resolved_total")
tally = (f"ARCHIVE: {count(archived)} FORECASTS · {count(resolved)} RESOLVED"
if archived is not None else "ARCHIVE: BUILDING")
# The session line, not a sign-in prompt: the prompt is Gradio's own
# LoginButton, parked in this corner by `#bit-login` in chrome.py.
# Rendering another one here would be two buttons for one action.
signed_in = bool(state.get("signed_in"))
if signed_in:
who = str(state.get("user") or "").strip().upper()
account = (f"ACCOUNT \u00b7 {who} \u00b7 GPU TIER ON YOUR QUOTA" if who
else "ACCOUNT \u00b7 GPU TIER ON YOUR QUOTA")
else:
left = max(0, config.ANON_SESSION_CAP - int(state.get("session_forecasts", 0)))
account = (f"ANONYMOUS SESSION \u00b7 CPU-TIER MODELS \u00b7 "
f"{left} FORECASTS LEFT")
dot = "var(--fin-up)" if signed_in else "var(--mute-orange)"
return (
'<header style="position:sticky;top:0;z-index:20;background:var(--bg-panel);'
'border-bottom:1px solid var(--border-default)">'
'<div style="display:flex;align-items:center;gap:10px;padding:8px 14px;'
'min-height:48px;flex-wrap:wrap">'
'<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto">'
'<span style="display:inline-block;width:6px;height:6px;'
'background:var(--fin-up);animation:bitPulse 2s ease-in-out infinite"></span>'
f'<span style="{STYRENE};font-size:var(--text-sm);color:var(--text-secondary)">Arena</span>'
'</div>'
f'<a href="{a(data.get("store_url", "#"))}" target="_blank" rel="noopener" '
'style="display:flex;align-items:center;gap:8px;padding:3px 8px;'
'border:1px solid var(--accent-amber-dim);color:var(--accent-amber-strong);'
'flex:0 0 auto;text-decoration:none">'
f'<span class="mono-data" style="font-size:var(--text-xs)">{e(tally)}</span></a>'
'<div style="flex:1 1 auto;min-width:180px;max-width:400px">'
f'{palette.search_bar(state.get("q", ""), emit, count_label="")}'
'</div>'
'<span style="display:inline-flex;align-items:center;gap:6px;padding:3px 8px;'
# The right margin is the width the fixed LoginButton occupies,
# so the session line and the sign-in control do not overlap.
'border:1px solid var(--border-default);margin-left:auto;'
'margin-right:268px">'
f'<span style="display:inline-block;width:5px;height:5px;background:{dot}"></span>'
f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-secondary);white-space:nowrap">{e(account)}</span></span>'
'</div>'
'</header>'
)
# --------------------------------------------------------------------------
# Stats and title
# --------------------------------------------------------------------------
def title_row(state: dict, data: dict) -> str:
deep = ""
if state.get("deep_linked"):
deep = ('<span style="display:inline-flex;align-items:center;gap:7px;'
'padding:4px 8px;border:1px solid var(--accent-amber-dim);'
'background:var(--bg-raised)">'
'<span class="pixel-text" style="color:var(--accent-amber-strong)">→</span>'
'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-secondary)">DEEP LINK ?model={e(state["selected"][0])}'
' · PRESELECTED</span></span>')
ran = data.get("resolver_last_ran") or DASH
return (
'<div style="display:flex;align-items:flex-end;gap:12px;flex-wrap:wrap">'
'<div style="display:flex;flex-direction:column;gap:3px;min-width:0">'
f'<h1 style="{STYRENE};font-weight:500;font-size:var(--text-2xl);'
'line-height:var(--leading-tight);margin:0">Forecast Arena</h1>'
'<span style="color:var(--text-secondary);font-size:var(--text-base)">'
'Every model forecasts. Every forecast is remembered.</span></div>'
f'{deep}'
'<span style="display:inline-flex;align-items:center;gap:6px;padding:4px 8px;'
f'border:1px solid var(--border-default);background:var(--bg-panel);margin-left:auto">'
'<span style="display:inline-block;width:5px;height:5px;'
'background:var(--accent-amber);animation:bitPulse 2s ease-in-out infinite"></span>'
'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-secondary);white-space:nowrap">RESOLVER LAST RAN {e(ran)}</span>'
'</span></div>'
)
def stats_bar(stats: list[dict]) -> str:
cells = []
for s in stats:
cells.append(
f'<div style="padding:10px 12px;border-right:1px solid var(--border-subtle);'
f'border-left:2px solid {a(s["mark"])}">'
f'<div style="{STYRENE};font-weight:300;font-size:var(--text-2xs);'
f'letter-spacing:var(--tracking-wider);color:var(--text-tertiary);'
f'white-space:nowrap;overflow:hidden;text-overflow:ellipsis">{e(s["label"])}</div>'
f'<div class="mono-data" style="font-size:var(--text-2xl);line-height:1.15;'
f'white-space:nowrap;color:{a(s["color"])}">{e(s["value"])}</div>'
f'<div style="font-size:var(--text-2xs);color:var(--text-tertiary);'
f'white-space:nowrap;overflow:hidden;text-overflow:ellipsis">{e(s["note"])}</div>'
f'</div>')
return ('<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));'
f'{PANEL}">{"".join(cells)}</div>')
# --------------------------------------------------------------------------
# Model picker
# --------------------------------------------------------------------------
def models_section(state: dict, data: dict) -> str:
mode = state["mode"]
selected = state["selected"]
sel_note = (f"MATCHUP · {len(selected)} OF {view.MAX_MATCHUP} SELECTED"
if mode == "matchup" else "PLAYGROUND · SINGLE MODEL")
tabs = []
for i, (key, label) in enumerate((("playground", "Playground"),
("matchup", "Matchup"))):
on = mode == key
tabs.append(
f'<button {bit("mode", key)} style="padding:4px 12px;'
f'background:{"var(--accent-amber)" if on else "transparent"};'
f'border:1px solid var(--border-default);border-left-width:{"1px" if i == 0 else "0"};'
f'color:{"var(--stone-950)" if on else "var(--text-secondary)"};{STYRENE};'
f'font-size:var(--text-xs);cursor:pointer;transition:background 1s ease">'
f'{e(label)}</button>')
cards = "".join(_model_card(m, m["slug"] in selected, data)
for m in data["models"])
add = (
f'<button {bit("enroll", "focus")} style="text-align:left;display:flex;'
'flex-direction:column;gap:6px;justify-content:center;padding:10px 11px;'
'background:transparent;border:0;border-left:1px dashed var(--border-default);'
'cursor:pointer;color:var(--text-tertiary)">'
'<span class="mono-data" style="font-size:var(--text-lg)">+</span>'
f'<span style="{STYRENE};font-size:var(--text-sm)">Add a fine-tune</span>'
'<span style="font-size:var(--text-2xs);text-wrap:pretty">Any Hub model with a '
'Kronos, Chronos or TimesFM adapter family</span></button>')
return (
f'<section style="{PANEL}">'
'<div style="display:flex;align-items:center;gap:10px;padding:8px 12px;'
'border-bottom:1px solid var(--border-default);flex-wrap:wrap">'
f'<span style="{STYRENE};font-size:var(--text-md)">Models</span>'
f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-tertiary)">{e(sel_note)}</span>'
f'<div style="display:flex;margin-left:auto">{"".join(tabs)}</div></div>'
f'<div class="fa-picker">{cards}{add}</div></section>'
)
def _model_card(model: dict, on: bool, data: dict) -> str:
"""One model card. Rendered from declared capabilities only."""
color = model["color"]
caps = model["caps"]
# The two capability chips the design specifies: what the model emits, and
# what hardware it costs. Both come from the adapter's declaration.
paths = caps.get("output") == "ohlcv_paths"
gpu = caps.get("hardware") == "gpu"
chips = [
("OHLCV paths" if paths else "quantile line",
"var(--accent-amber-strong)" if paths else "var(--text-secondary)",
"var(--accent-amber-dim)" if paths else "var(--border-default)"),
("your GPU quota" if gpu else "CPU · instant",
"var(--mute-orange)" if gpu else "var(--accent-moss-strong)",
"var(--mute-orange)" if gpu else "var(--accent-moss-dim)"),
]
chip_html = "".join(
f'<span class="mono-data fa-tag" style="color:{a(fg)};border-color:{a(bd)}">'
f'{e(label)}</span>' for label, fg, bd in chips)
chk_style = (f'background:{a(color)};color:var(--stone-950);border-color:{a(color)}'
if on else "")
return (
f'<button {bit("pick", model["slug"])} class="fa-card{" on" if on else ""}" '
f'style="border-top-color:{a(color) if on else "transparent"}">'
'<div class="fa-card-top">'
f'<span class="mono-data fa-tag" style="color:{a(color) if on else "var(--text-tertiary)"};'
f'border-color:{a(color) if on else "var(--border-default)"}">{e(model["family"].upper())}</span>'
f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-tertiary)">{e(model["size"])}</span>'
f'<span class="fa-chk" style="{chk_style}">{"✓" if on else ""}</span></div>'
f'<div class="fa-card-name">{e(model["name"])}</div>'
f'<div class="fa-card-caps">{chip_html}</div>'
'<div class="fa-card-cal">'
'<span class="pixel-text" style="color:var(--text-tertiary)">CALIBRATION</span>'
f'<span class="mono-data" style="font-size:var(--text-md);'
f'color:{a(model["grade_color"])};margin-left:auto">{e(model["grade"])}</span>'
f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-tertiary)">{e(model["resolved_label"])}</span></div>'
'</button>')
# --------------------------------------------------------------------------
# Controls
# --------------------------------------------------------------------------
def controls(state: dict, data: dict) -> str:
assets = "".join(
f'<button {bit("asset", slug)} class="fa-pill'
f'{" on" if state["asset"] == slug else ""}">{e(spec.display)}</button>'
for slug, spec in config.ASSETS.items())
tfs = "".join(
f'<button {bit("tf", slug)} class="fa-seg{" first" if i == 0 else ""}'
f'{" on" if state["tf"] == slug else ""}">{e(slug)}</button>'
for i, slug in enumerate(config.TIMEFRAMES))
options = _horizon_options(state["tf"])
hzs = "".join(
f'<button {bit("hz", str(h))} class="fa-seg{" first" if i == 0 else ""}'
f'{" on" if int(state["horizon"]) == h else ""}">{h} steps</button>'
for i, h in enumerate(options))
hours = state["horizon"] * (1 if state["tf"] == "1h" else 24)
hz_note = f"= {hours}H AHEAD"
gear = _gear(state) if state.get("gear") else ""
quota = _quota_banner(data) if data.get("quota_blocked") else ""
run_label = ("▶ Forecast" if state["mode"] == "playground"
else f"▶ Forecast {len(state['selected'])} models")
runtime = data.get("runtime_hint", DASH)
blocked = bool(data.get("quota_blocked"))
return (
f'<section style="{PANEL};display:flex;align-items:center;gap:14px;'
'padding:9px 12px;flex-wrap:wrap">'
'<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">'
'<span class="pixel-text" style="color:var(--text-tertiary)">ASSET</span>'
f'{assets}</div>'
'<div style="width:1px;height:22px;background:var(--border-subtle)"></div>'
'<div style="display:flex;align-items:center;gap:6px">'
'<span class="pixel-text" style="color:var(--text-tertiary)">TIMEFRAME</span>'
f'<div style="display:flex">{tfs}</div></div>'
'<div style="width:1px;height:22px;background:var(--border-subtle)"></div>'
'<div style="display:flex;align-items:center;gap:6px">'
'<span class="pixel-text" style="color:var(--text-tertiary)">HORIZON</span>'
f'<div style="display:flex">{hzs}</div>'
f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-tertiary)">{e(hz_note)}</span></div>'
'<div style="position:relative;margin-left:auto;display:flex;'
'align-items:center;gap:8px">'
f'<button {bit("gear", "toggle")} title="Sampling and seed" '
f'style="width:26px;height:26px;background:'
f'{"var(--bg-raised)" if state.get("gear") else "transparent"};'
f'border:1px solid {"var(--accent-amber)" if state.get("gear") else "var(--border-default)"};'
f'color:{"var(--accent-amber-strong)" if state.get("gear") else "var(--text-tertiary)"};'
'cursor:pointer;display:flex;align-items:center;justify-content:center">'
f'{icons.icon("sliders", size="13px")}</button>'
f'{gear}{quota}'
f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-tertiary);padding:3px 7px;'
f'border:1px solid var(--border-subtle)">{e(runtime)}</span>'
f'<button {bit("run", "go")} '
f'style="padding:6px 14px;background:'
f'{"var(--bg-raised)" if blocked else "var(--accent-amber)"};'
f'border:1px solid {"var(--border-default)" if blocked else "var(--accent-amber)"};'
f'color:{"var(--text-disabled)" if blocked else "var(--stone-950)"};'
f'{STYRENE};font-size:var(--text-xs);'
f'cursor:{"not-allowed" if blocked else "pointer"}">{e(run_label)}</button>'
'</div></section>'
)
def _horizon_options(timeframe: str) -> list[int]:
"""Horizon choices, capped at what the timeframe allows."""
ceiling = config.MAX_HORIZON.get(timeframe, 96)
return [h for h in (12, 24, 48, 96) if h <= ceiling] or [ceiling]
def _gear(state: dict) -> str:
rows = [
("Sampled paths", str(state.get("n_samples", config.DEFAULT_N_SAMPLES))),
("Quantiles", "/".join(f"{q:g}" for q in config.QUANTILE_LEVELS)),
("Seed", str(state.get("seed", 42))),
]
body = "".join(
'<div style="display:flex;align-items:center;gap:8px">'
f'<span style="flex:1 1 auto;{STYRENE};font-weight:300;'
f'font-size:var(--text-xs);color:var(--text-secondary)">{e(label)}</span>'
f'<span class="mono-data" style="font-size:var(--text-xs);'
f'color:var(--text-primary);border:1px solid var(--border-default);'
f'padding:2px 7px">{e(value)}</span></div>'
for label, value in rows)
return (
'<div style="position:absolute;top:32px;right:0;z-index:40;width:230px;'
'background:var(--bg-raised);border:1px solid var(--border-strong);'
'padding:10px 12px;display:flex;flex-direction:column;gap:9px">'
f'<span style="{STYRENE};font-weight:300;font-size:var(--text-xs);'
'color:var(--text-tertiary)">Sampling</span>'
f'{body}'
'<span class="pixel-text" style="color:var(--text-tertiary)">'
'SEED IS ARCHIVED WITH THE FORECAST</span></div>')
def _quota_banner(data: dict) -> str:
return (
'<span style="display:inline-flex;align-items:center;gap:7px;padding:4px 9px;'
'border:1px solid var(--mute-orange);background:var(--bg-raised)">'
'<span class="pixel-text" style="color:var(--mute-orange)">⚠</span>'
f'<span style="font-size:var(--text-xs);color:var(--text-secondary)">'
f'{e(data.get("quota_msg", "GPU-tier model — sign in to use your quota"))}</span>'
f'<a href="{a(data.get("login_url", "#"))}" style="font-family:var(--font-mono);'
'font-size:var(--text-2xs);white-space:nowrap">SIGN IN ↗</a></span>')
# --------------------------------------------------------------------------
# Chart panel
# --------------------------------------------------------------------------
def chart_section(state: dict, data: dict) -> str:
runs = data.get("runs", [])
mode = state["mode"]
primary = runs[0] if runs else None
title = "Matchup" if mode == "matchup" else "Forecast"
who = (f"{len(runs)} MODELS" if mode == "matchup"
else (data["models_by_slug"].get(state["selected"][0], {}).get("name", "")
.upper() if state["selected"] else ""))
meta = f'{state["asset"]} · {state["tf"]} · H+{state["horizon"]} · {who}'
# The capability gate, in one place. `ghost_capable` is true when the
# *selected* model declares OHLCV paths -- not when a result happens to
# carry them.
emits_paths = bool(primary
and primary.capabilities.get("output") == "ohlcv_paths"
and mode == "playground")
# A model can emit paths and still have none to draw: forecasts archived
# before paths were stored keep their quantiles and nothing else. Offering
# a toggle that renders nothing is worse than saying why it is empty.
paths_missing = bool(emits_paths and primary.result.paths is None)
ghost_capable = emits_paths and not paths_missing
ghost_locked = bool(primary
and primary.capabilities.get("output") != "ohlcv_paths"
and mode == "playground")
if ghost_capable:
on = state.get("ghosts", True)
toggle = (
f'<button {bit("ghosts", "toggle")} style="display:inline-flex;'
'align-items:center;gap:6px;padding:3px 8px;background:'
f'{"var(--bg-raised)" if on else "transparent"};'
f'border:1px solid {"var(--accent-amber)" if on else "var(--border-default)"};'
f'color:{"var(--accent-amber-strong)" if on else "var(--text-secondary)"};'
'cursor:pointer">'
f'<span class="mono-data" style="font-size:var(--text-2xs)">{"✓" if on else ""}</span>'
f'<span style="{STYRENE};font-size:var(--text-xs)">Sampled OHLCV paths</span>'
'</button>')
elif paths_missing:
toggle = (
'<span style="display:inline-flex;align-items:center;gap:6px;padding:3px 8px;'
'border:1px dashed var(--border-default);color:var(--text-disabled)" '
'title="This forecast predates path archiving. Run it again to get them.">'
'<span class="mono-data" style="font-size:var(--text-2xs)">✕</span>'
f'<span style="{STYRENE};font-size:var(--text-xs)">'
'Paths not archived — forecast again to see them</span></span>')
elif ghost_locked:
toggle = (
'<span style="display:inline-flex;align-items:center;gap:6px;padding:3px 8px;'
'border:1px dashed var(--border-default);color:var(--text-disabled)">'
'<span class="mono-data" style="font-size:var(--text-2xs)">✕</span>'
f'<span style="{STYRENE};font-size:var(--text-xs)">'
'Quantile line only — no OHLCV paths</span></span>')
else:
toggle = ""
if primary:
frozen = (f'FROZEN {primary.issued_ts.strftime("%Y-%m-%d %H:%M")} UTC · '
f'SEED {primary.result.seed}')
else:
frozen = "NO FORECAST ISSUED YET"
# A forecast rebuilt from the archive has to say how old it is. Showing
# only its issue timestamp reads as current at a glance.
provenance = ""
if primary is not None and getattr(primary, "from_cache", False):
age = view.age_label(primary.issued_ts)
badge = "LAST ARCHIVED"
if getattr(primary, "backfilled", False):
badge = "LAST ARCHIVED · BACKFILL"
provenance = (
'<span style="display:inline-flex;align-items:center;gap:6px;'
'padding:3px 8px;border:1px solid var(--border-default);'
'background:var(--bg-raised)">'
f'<span class="pixel-text" style="color:var(--text-tertiary)">{e(badge)}</span>'
f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--accent-amber-strong)">ISSUED {e(age.upper())}</span></span>')
# How it is actually doing. The point of showing an old forecast is
# that the answer is already partly known.
score = view.live_scorecard(primary)
if score:
err = (f' · {score["median_err"]:.2f}% ERR'
if score["median_err"] is not None else "")
provenance += (
'<span style="display:inline-flex;align-items:center;gap:6px;'
f'padding:3px 8px;border:1px solid {a(score["colour"])}">'
f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:{a(score["colour"])}">{e(score["label"])}{e(err)}</span>'
f'<span class="pixel-text" style="color:var(--text-tertiary)">'
f'{e(score["note"].upper())}</span></span>')
drawing = data.get("chart") or {}
body = _chart_body(drawing) if drawing.get("svg") else _chart_empty(data)
return (
f'<section style="{PANEL}">'
'<div style="display:flex;align-items:center;gap:10px;padding:8px 12px;'
'border-bottom:1px solid var(--border-default);flex-wrap:wrap">'
f'<span style="{STYRENE};font-size:var(--text-md)">{e(title)}</span>'
f'<span class="mono-data" style="font-size:var(--text-xs);'
'color:var(--text-secondary);padding:2px 7px;'
f'border:1px solid var(--border-default)">{e(meta)}</span>'
'<div style="display:flex;align-items:center;gap:8px;margin-left:auto;'
f'flex-wrap:wrap">{provenance}{toggle}'
f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-tertiary)">{e(frozen)}</span></div></div>'
f'{_legend(data)}{body}</section>'
)
def _legend(data: dict) -> str:
runs = data.get("runs", [])
if not runs:
return ""
items = []
for i, run in enumerate(runs):
color = chart.series_color(i)
panel = data["panels"].get(run.model_slug, {})
name = data["models_by_slug"].get(run.model_slug, {}).get("name", run.model_slug)
width = panel.get("width")
band = (f'10 / 50 / 90 · {pct(width, 1)} MEAN WIDTH' if width is not None
else "10 / 50 / 90")
grade = panel.get("grade", "-")
dash = chart.FAN_DASH[i % 3] if len(runs) > 1 else "none"
items.append(
'<div style="display:flex;align-items:center;gap:8px">'
'<svg width="34" height="12" viewBox="0 0 34 12" '
'style="flex:0 0 auto;display:block">'
f'<rect x="0" y="2" width="34" height="8" fill="{a(color)}" opacity="0.16"></rect>'
f'<line x1="0" y1="6" x2="34" y2="6" stroke="{a(color)}" '
f'stroke-width="1.6" stroke-dasharray="{a(dash)}"></line></svg>'
f'<span style="{STYRENE};font-size:var(--text-sm)">{e(name)}</span>'
f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-tertiary)">{e(band)}</span>'
f'<span class="mono-data" style="font-size:var(--text-xs);'
f'color:{a(grade_color(grade))};border:1px solid {a(grade_color(grade))};'
f'padding:1px 5px">{e(grade)}</span>'
f'<span style="font-size:var(--text-2xs);'
f'color:{a(panel.get("verdict_color", "var(--text-tertiary)"))}">'
f'{e(panel.get("verdict_short", ""))}</span></div>')
return ('<div style="display:flex;align-items:center;gap:14px;padding:7px 12px;'
'border-bottom:1px solid var(--border-subtle);background:var(--bg-raised);'
f'flex-wrap:wrap">{"".join(items)}</div>')
def _chart_body(drawing: dict) -> str:
axis = "".join(
f'<span class="mono-data" style="position:absolute;right:6px;top:{a(g["top"])};'
'transform:translateY(-50%);font-size:var(--text-2xs);'
f'color:var(--text-tertiary);white-space:nowrap">{e(g["label"])}</span>'
for g in drawing.get("grid", []))
times = "".join(
f'<span class="mono-data" style="position:absolute;left:{a(t["left"])};'
'transform:translateX(-50%);font-size:var(--text-2xs);'
f'color:var(--text-tertiary);white-space:nowrap">{e(t["label"])}</span>'
for t in drawing.get("time_labels", []))
left = a(drawing.get("now_left", "50%"))
return (
'<div class="fa-chart"><div style="position:relative;flex:1 1 auto;min-width:0">'
f'{drawing["svg"]}'
f'<span class="mono-data" style="position:absolute;left:{left};top:5px;'
'transform:translateX(-100%);padding-right:6px;font-size:var(--text-2xs);'
f'color:var(--accent-amber-strong);white-space:nowrap">'
f'{e(drawing.get("boundary_label", "NOW"))} '
f'{e(drawing.get("now_time", ""))}</span>'
f'<span class="mono-data" style="position:absolute;left:{left};top:5px;'
'padding-left:6px;font-size:var(--text-2xs);color:var(--text-tertiary);'
'white-space:nowrap">FORECAST →</span>'
'<span class="mono-data" style="position:absolute;left:4px;top:76%;'
'font-size:var(--text-2xs);color:var(--text-tertiary)">VOLUME</span>'
'<div style="position:absolute;left:0;right:0;bottom:0;height:16px">'
f'{times}</div></div>'
f'<div class="fa-axis">{axis}</div></div>')
def _chart_empty(data: dict) -> str:
err = data.get("error")
if err:
return _error_state(err)
return (
'<div style="display:flex;flex-direction:column;align-items:center;gap:8px;'
'padding:52px 16px;background:var(--bg-sunken)">'
'<span class="mono-data" style="font-size:var(--text-2xl);'
'color:var(--text-disabled)">▱</span>'
f'<span style="{STYRENE};font-size:var(--text-md);color:var(--text-secondary)">'
'No forecast issued</span>'
'<span style="font-size:var(--text-xs);color:var(--text-tertiary);'
'text-align:center;max-width:340px;text-wrap:pretty">'
'Pick a model and press Forecast. The result is frozen at issue and '
'archived before it is drawn.</span></div>')
def _error_state(err: dict) -> str:
"""The designed failure states: quota, load failure, rejected enrollment."""
kind = err.get("kind", "load_failure")
glyph = {"quota": "⚠", "load_failure": "✕", "enroll": "✕",
"no_data": "∅", "no_gpu": "⚠"}.get(kind, "✕")
color = {"quota": "var(--mute-orange)",
"no_gpu": "var(--mute-orange)"}.get(kind, "var(--fin-down)")
extra = ""
if kind == "quota":
extra = (f'<a href="{a(err.get("login_url", "#"))}" '
'style="font-family:var(--font-mono);font-size:var(--text-2xs)">'
'SIGN IN ↗</a>')
elif kind == "no_gpu":
# Nothing the visitor can do here, so the only honest offer is a Space
# they control with hardware they choose.
extra = (f'<a href="{a(err.get("duplicate_url", "#"))}" target="_blank" '
'rel="noopener" style="font-family:var(--font-mono);'
'font-size:var(--text-2xs)">RUN IT ON YOUR OWN HARDWARE ↗</a>')
elif kind == "load_failure":
# A model that will not load on this hardware is not always a bug in
# the Space: duplicating it gives the user a box they control.
extra = (f'<a href="{a(err.get("duplicate_url", "#"))}" target="_blank" '
'rel="noopener" style="font-family:var(--font-mono);'
'font-size:var(--text-2xs)">DUPLICATE THIS SPACE ↗</a>')
return (
'<div style="display:flex;flex-direction:column;align-items:center;gap:9px;'
'padding:44px 16px;background:var(--bg-sunken)">'
f'<span class="mono-data" style="font-size:var(--text-2xl);color:{a(color)}">'
f'{e(glyph)}</span>'
f'<span style="{STYRENE};font-size:var(--text-md);color:var(--text-secondary)">'
f'{e(err.get("title", "Forecast failed"))}</span>'
'<span style="font-size:var(--text-xs);color:var(--text-tertiary);'
'text-align:center;max-width:420px;text-wrap:pretty">'
f'{e(err.get("message", ""))}</span>'
f'<div style="display:flex;gap:10px;align-items:center">{extra}'
f'<button {bit("dismiss", "error")} style="padding:3px 9px;'
'background:transparent;border:1px solid var(--border-default);'
'color:var(--text-secondary);cursor:pointer;font-family:var(--font-mono);'
'font-size:var(--text-2xs)">DISMISS</button></div></div>')
# --------------------------------------------------------------------------
# Track record
# --------------------------------------------------------------------------
def trackrecord_section(state: dict, data: dict) -> str:
mode = state["mode"]
slugs = state["selected"]
scope = (f'{state["asset"]} · {state["tf"]} · H+{state["horizon"]} · '
f'LAST {view.THUMBS} RESOLVED').upper()
if mode == "matchup" and len(slugs) > 1:
question = "Same stats, side by side — best in row highlighted."
body = _scoreboard(state, data)
else:
primary = slugs[0] if slugs else None
panel = data["panels"].get(primary, {})
name = data["models_by_slug"].get(primary, {}).get("name", primary or "")
question = f"How wrong has {name} been here recently?"
body = _empty_record() if panel.get("empty", True) else _playground_record(panel, data)
return (
f'<section style="{PANEL}">'
'<div style="display:flex;align-items:center;gap:10px;padding:8px 12px;'
'border-bottom:1px solid var(--border-default);'
'border-left:3px solid var(--accent-amber);flex-wrap:wrap">'
f'<span style="{STYRENE};font-size:var(--text-md)">Track record</span>'
f'<span style="color:var(--text-secondary);font-size:var(--text-xs)">'
f'{e(question)}</span>'
f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-tertiary);margin-left:auto">{e(scope)}</span></div>'
f'{body}</section>')
def _empty_record() -> str:
return (
'<div style="display:flex;flex-direction:column;align-items:center;gap:8px;'
'padding:26px 16px">'
'<span class="mono-data" style="font-size:var(--text-2xl);'
'color:var(--text-disabled)">∅</span>'
f'<span style="{STYRENE};font-size:var(--text-md);color:var(--text-secondary)">'
'No history yet</span>'
'<span style="font-size:var(--text-xs);color:var(--text-tertiary);'
'text-align:center;max-width:340px;text-wrap:pretty">Forecasts made here start '
'the record. The first resolved forecast for this model, asset and timeframe '
'appears in this panel.</span>'
f'<button {bit("run", "go")} style="margin-top:2px;padding:4px 9px;'
'background:transparent;border:1px solid var(--border-default);'
'color:var(--text-secondary);cursor:pointer;font-family:var(--font-mono);'
'font-size:var(--text-2xs)">MAKE THE FIRST FORECAST →</button></div>')
def _playground_record(panel: dict, data: dict) -> str:
stats = [
("Empirical 80% coverage", pct(panel.get("coverage")),
f'target 80% · {count(panel.get("resolved"))} resolved',
panel.get("verdict_color", "var(--text-primary)")),
("Median abs error", pct(panel.get("median_err", 0) / 100
if panel.get("median_err") is not None else None, 2),
"at horizon close", "var(--text-primary)"),
("Mean band width", pct(panel.get("width"), 1),
"10→90 span, % of price", "var(--text-primary)"),
("Backfilled share", pct(panel.get("backfilled_share")),
"labelled in the record", "var(--mute-blue)"),
]
stat_html = "".join(
'<div style="padding:9px 12px;border-right:1px solid var(--border-subtle)">'
f'<div style="{STYRENE};font-weight:300;font-size:var(--text-2xs);'
f'letter-spacing:var(--tracking-wider);color:var(--text-tertiary)">{e(label)}</div>'
f'<div class="mono-data" style="font-size:var(--text-xl);line-height:1.2;'
f'color:{a(color)}">{e(value)}</div>'
f'<div style="font-size:var(--text-2xs);color:var(--text-tertiary)">{e(note)}</div>'
'</div>'
for label, value, note, color in stats)
cells = "".join(_thumb(t, data) for t in panel.get("thumbs", []))
vcolor = panel.get("verdict_color", "var(--text-tertiary)")
return (
'<div><div style="display:grid;'
'grid-template-columns:repeat(auto-fit,minmax(168px,1fr));'
f'border-bottom:1px solid var(--border-default)">{stat_html}</div>'
f'<div class="fa-trstrip">{cells}</div>'
'<div style="display:flex;align-items:center;gap:10px;padding:7px 12px;'
'border-top:1px solid var(--border-subtle);background:var(--bg-raised);'
'flex-wrap:wrap">'
f'<span class="mono-data" style="font-size:var(--text-xs);'
f'color:{a(vcolor)};border:1px solid {a(vcolor)};padding:2px 7px">'
f'{e(panel.get("verdict", ""))}</span>'
'<span style="font-size:var(--text-xs);color:var(--text-secondary);'
f'text-wrap:pretty">{e(_verdict_note(panel))}</span>'
f'<a href="{a(data.get("store_url", "#"))}" target="_blank" rel="noopener" '
'style="margin-left:auto;font-family:var(--font-mono);font-size:var(--text-2xs);'
f'white-space:nowrap">ALL {e(count(panel.get("total")))} ARCHIVED ↗</a>'
'</div></div>')
def _verdict_note(panel: dict) -> str:
coverage = panel.get("coverage")
if coverage is None:
return ("Not enough resolved forecasts here to say anything about "
"calibration yet.")
gap = coverage - config.NOMINAL_COVERAGE
if abs(gap) <= 0.05:
return ("Bands hold up on this pair: the realized path stayed inside the "
"80% envelope about as often as it should.")
if gap < 0:
return ("Bands are narrower than the realized error justifies here. "
"Read the median, not the confidence.")
return ("Bands are wider than the realized error justifies here — the model "
"is hedging more than this pair has needed.")
def _thumb(t: dict, data: dict) -> str:
spark = t["spark"]
backfill = ('<span class="pixel-text" style="color:var(--mute-blue);'
'margin-left:auto">BACKFILL</span>' if t["backfilled"] else "")
return (
f'<div class="fa-trcell{" miss" if t["miss"] else ""}">'
'<div style="display:flex;align-items:center;gap:5px">'
f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-tertiary)">{e(t["date"])}</span>'
f'<span class="mono-data" style="font-size:var(--text-xs);'
f'color:{a(t["hit_color"])};margin-left:auto">{e(t["hit"])}</span></div>'
'<svg width="94" height="38" viewBox="0 0 94 38" style="display:block">'
f'<path d="{a(spark["band"])}" fill="var(--accent-amber-strong)" opacity="0.2"></path>'
f'<path d="{a(spark["mid"])}" fill="none" stroke="var(--accent-amber-strong)" '
'stroke-width="1.2" stroke-dasharray="3 2"></path>'
f'<path d="{a(spark["real"])}" fill="none" stroke="var(--text-primary)" '
'stroke-width="1.4"></path></svg>'
'<div style="display:flex;align-items:center;gap:4px">'
f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-secondary)">{e(t["err"])}</span>{backfill}</div></div>')
def _scoreboard(state: dict, data: dict) -> str:
"""The matchup table: same stats, aligned, best in row highlighted."""
slugs = [s for s in state["selected"] if s in data["panels"]]
if not slugs:
return _empty_record()
panels = [data["panels"][s] for s in slugs]
cols = f'1.15fr repeat({len(slugs)},minmax(0,1fr))'
heads = "".join(
'<div style="padding:7px 12px;border-right:1px solid var(--border-subtle);'
f'border-top:3px solid {a(chart.series_color(i))};display:flex;'
'align-items:center;gap:7px">'
f'<span style="{STYRENE};font-size:var(--text-sm);white-space:nowrap;'
'overflow:hidden;text-overflow:ellipsis">'
f'{e(data["models_by_slug"].get(s, {}).get("name", s))}</span>'
f'<span class="mono-data" style="font-size:var(--text-xs);'
f'color:{a(grade_color(p.get("grade", "-")))};'
f'border:1px solid {a(grade_color(p.get("grade", "-")))};'
f'padding:1px 5px;margin-left:auto">{e(p.get("grade", "-"))}</span></div>'
for i, (s, p) in enumerate(zip(slugs, panels)))
# (label, hint, value fn, "best" fn or None). Coverage is scored on
# distance from nominal, not on being highest -- a narrower band is not a
# better one, and the design says so on the page.
rows = [
("80% band coverage", "TARGET 80%",
lambda p: pct(p.get("coverage")),
lambda p: (-abs(p["coverage"] - config.NOMINAL_COVERAGE)
if p.get("coverage") is not None else None)),
("Median abs error", "LOWER BETTER",
lambda p: pct(p["median_err"] / 100 if p.get("median_err") is not None else None, 2),
lambda p: (-p["median_err"] if p.get("median_err") is not None else None)),
("Mean band width", "CONTEXT ONLY",
lambda p: pct(p.get("width"), 1), None),
("Resolved forecasts", "SAMPLE SIZE",
lambda p: count(p.get("resolved")),
lambda p: p.get("resolved")),
("Calibration verdict", "FROM RESOLVED ONLY",
lambda p: p.get("verdict", DASH), None),
]
body = []
for label, hint, value_of, best_of in rows:
best_index = None
if best_of is not None:
scored = [(i, best_of(p)) for i, p in enumerate(panels)]
scored = [(i, v) for i, v in scored if v is not None]
if scored:
best_index = max(scored, key=lambda kv: kv[1])[0]
cells = []
for i, p in enumerate(panels):
is_best = i == best_index
fg = ("var(--accent-moss-strong)" if is_best else "var(--text-primary)")
if label.startswith("Calibration"):
fg = p.get("verdict_color", "var(--text-primary)")
cells.append(
'<div style="padding:7px 12px;border-right:1px solid var(--border-subtle);'
f'background:{"var(--bg-raised)" if is_best else "transparent"};'
'display:flex;align-items:center;gap:7px">'
f'<span class="mono-data" style="font-size:var(--text-md);'
f'color:{a(fg)}">{e(value_of(p))}</span>'
'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-tertiary);margin-left:auto">{"BEST" if is_best else ""}</span>'
'</div>')
body.append(
f'<div style="display:grid;grid-template-columns:{cols};'
'border-bottom:1px solid var(--border-subtle)">'
'<div style="padding:7px 12px;border-right:1px solid var(--border-subtle);'
'display:flex;flex-direction:column;gap:1px">'
f'<span style="{STYRENE};font-weight:300;font-size:var(--text-xs);'
f'color:var(--text-secondary)">{e(label)}</span>'
f'<span class="pixel-text" style="color:var(--text-tertiary)">{e(hint)}</span>'
f'</div>{"".join(cells)}</div>')
return (
f'<div><div style="display:grid;grid-template-columns:{cols};'
'border-bottom:1px solid var(--border-default);background:var(--bg-raised)">'
'<div style="padding:7px 12px;border-right:1px solid var(--border-subtle)">'
'<span class="pixel-text" style="color:var(--text-tertiary)">METRIC</span></div>'
f'{heads}</div>{"".join(body)}'
'<div style="display:flex;align-items:center;gap:10px;padding:7px 12px;'
'background:var(--bg-raised);flex-wrap:wrap">'
'<span class="pixel-text" style="color:var(--accent-amber-strong)">i</span>'
'<span style="font-size:var(--text-xs);color:var(--text-secondary);'
'text-wrap:pretty">Highlighted cell is best in row. Coverage closest to 80% '
'wins — a narrower band is not a better one.</span></div></div>')
# --------------------------------------------------------------------------
# Rail
# --------------------------------------------------------------------------
def rail(state: dict, data: dict) -> str:
return ('<aside class="fa-rail">'
f'{_standings(state, data)}{_volatility(data)}{_log(state, data)}'
f'{_extend(state, data)}{_enroll(state, data)}</aside>')
def _standings(state: dict, data: dict) -> str:
rows = data.get("standings_rows", [])
enrolled = len(data.get("models", []))
tabs = "".join(
f'<button {bit("cls", c)} style="flex:1 1 auto;padding:4px 5px;'
f'background:{"var(--bg-raised)" if state["cls"] == c else "transparent"};'
'border:0;border-right:1px solid var(--border-subtle);'
f'color:{"var(--accent-amber-strong)" if state["cls"] == c else "var(--text-tertiary)"};'
f'{STYRENE};font-size:var(--text-2xs);cursor:pointer">{e(c)}</button>'
for c in ("All", "Crypto", "Equities"))
if rows:
body = "".join(
f'<button {bit("stand", r["slug"])} class="fa-stand'
f'{" on" if r["selected"] else ""}" '
f'style="border-left-color:{a(chart.series_color(0)) if r["selected"] else "transparent"}">'
f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-tertiary);flex:0 0 auto">{e(r["rank"])}</span>'
'<span class="fa-stand-mid">'
f'<span class="mono-data fa-stand-name">{e(r["name"])}</span>'
f'<span class="pixel-text" style="color:var(--text-tertiary)">{e(r["meta"])}</span>'
'</span>'
f'<span class="mono-data" style="font-size:var(--text-md);'
f'color:{a(r["grade_color"])};flex:0 0 auto">{e(r["grade"])}</span></button>'
for r in rows)
else:
body = ('<div style="padding:18px 10px;text-align:center">'
'<span style="font-size:var(--text-xs);color:var(--text-tertiary);'
'text-wrap:pretty">No forecasts have resolved yet. Standings appear '
'once the resolver has outcomes to score.</span></div>')
right = ('<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-tertiary);margin-left:auto">{enrolled} ENROLLED</span>')
return (
f'<div style="{PANEL}">'
f'{_panel_title("Arena standings", right)}'
f'<div style="display:flex;border-bottom:1px solid var(--border-subtle)">{tabs}</div>'
f'{body}'
'<div style="padding:6px 10px;display:flex;align-items:center">'
'<span class="pixel-text" style="color:var(--text-tertiary)">'
'GRADES FROM RESOLVED FORECASTS ONLY</span>'
f'<a href="{a(data.get("standings_url", "#"))}" target="_blank" rel="noopener" '
'style="margin-left:auto;font-family:var(--font-mono);font-size:var(--text-2xs)">'
'FULL TABLE ↗</a></div></div>')
def _volatility(data: dict) -> str:
vol = data.get("volatility") or {}
rows = vol.get("rows", [])
if not rows:
return ""
body = "".join(
'<div style="display:flex;flex-direction:column;gap:4px">'
'<div style="display:flex;align-items:center;gap:8px">'
f'<span style="{STYRENE};font-weight:300;font-size:var(--text-2xs);'
f'color:var(--text-secondary)">{e(r["label"])}</span>'
f'<span class="mono-data" style="font-size:var(--text-xs);'
f'color:{a(r["fg"])};margin-left:auto">{e(r["value"])}</span></div>'
'<div style="height:5px;background:var(--bg-sunken);'
'border:1px solid var(--border-subtle);position:relative;overflow:hidden">'
f'<div style="position:absolute;left:0;top:0;bottom:0;width:{a(r["pct"])};'
f'background:{a(r["fg"])}"></div></div></div>'
for r in rows)
right = ('<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-tertiary);margin-left:auto">{e(vol.get("verdict", ""))}</span>')
return (
f'<div style="{PANEL}">{_panel_title("Volatility read", right)}'
'<div style="padding:10px;display:flex;flex-direction:column;gap:9px">'
f'{body}'
'<span style="font-size:var(--text-2xs);color:var(--text-tertiary);'
f'text-wrap:pretty">{e(vol.get("note", ""))}</span></div></div>')
def _log(state: dict, data: dict) -> str:
entries = state.get("log", [])[:view.LOG_LIMIT]
if entries:
body = "".join(
'<div style="display:flex;align-items:center;gap:8px;padding:6px 10px;'
'border-bottom:1px solid var(--border-subtle)">'
f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-tertiary);flex:0 0 auto">{e(l["time"])}</span>'
'<span class="fa-stand-mid">'
f'<span class="mono-data fa-stand-name">{e(l["name"])}</span>'
f'<span class="pixel-text" style="color:var(--text-tertiary)">{e(l["meta"])}</span>'
'</span>'
f'<button {bit("reopen", l["id"])} style="background:transparent;border:0;'
'color:var(--accent-amber-strong);cursor:pointer;font-family:var(--font-mono);'
'font-size:var(--text-2xs);flex:0 0 auto">RE-OPEN</button></div>'
for l in entries)
else:
body = ('<div style="padding:14px 10px">'
'<span style="font-size:var(--text-xs);color:var(--text-tertiary)">'
'Forecasts you issue this session appear here.</span></div>')
right = ('<span class="mono-data" style="font-size:var(--text-2xs);'
'color:var(--text-tertiary);margin-left:auto">THIS SESSION</span>')
return (
f'<div style="{PANEL}">{_panel_title("Forecast log", right)}{body}'
'<div style="padding:6px 10px">'
'<span class="pixel-text" style="color:var(--text-tertiary)">'
'ARCHIVED IMMUTABLY · SEED + CONFIG SAVED</span></div></div>')
def _extend(state: dict, data: dict) -> str:
cov = data.get("coverage") or {}
pct_label = cov.get("pct_label", DASH)
width = cov.get("pct_width", "0%")
rows = "".join(
'<div style="display:flex;align-items:center;gap:8px">'
f'<span class="pixel-text" style="color:var(--text-tertiary)">{e(label)}</span>'
f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-secondary);margin-left:auto">{e(value)}</span></div>'
for label, value in cov.get("rows", []))
label = "Contribute a backfill run (uses your quota)"
note = state.get("backfill_note")
note_html = (f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--accent-moss-strong);text-wrap:pretty">{e(note)}</span>'
if note else "")
return (
f'<div style="{PANEL}">{_panel_title("Extend the record")}'
'<div style="padding:10px;display:flex;flex-direction:column;gap:8px">'
'<div style="display:flex;align-items:center;gap:8px">'
f'<span style="font-size:var(--text-xs);color:var(--text-secondary)">'
f'{e(cov.get("scope", ""))}</span>'
f'<span class="mono-data" style="font-size:var(--text-md);'
f'color:var(--accent-amber-strong);margin-left:auto">{e(pct_label)}</span></div>'
'<div style="height:6px;background:var(--bg-sunken);'
'border:1px solid var(--border-subtle);position:relative;overflow:hidden">'
f'<div style="position:absolute;left:0;top:0;bottom:0;width:{a(width)};'
'background:var(--accent-amber)"></div></div>'
f'<div style="display:flex;flex-direction:column;gap:3px">{rows}</div>'
f'<button {bit("backfill", "run")} style="width:100%;padding:6px;'
'background:transparent;border:1px solid var(--border-default);'
f'color:var(--text-secondary);cursor:pointer;{STYRENE};'
f'font-size:var(--text-xs)">{e(label)}</button>'
f'{note_html}'
'<span class="pixel-text" style="color:var(--text-tertiary)">'
'BACKFILLED ENTRIES ARE LABELLED IN THE RECORD</span></div></div>')
def _enroll(state: dict, data: dict) -> str:
note = state.get("enroll_note") or "A smoke test runs before a model is enrolled"
ok = state.get("enroll_ok")
color = ("var(--accent-moss-strong)" if ok else
"var(--fin-down)" if ok is False else "var(--text-tertiary)")
families = "".join(
f'<button {bit("family", f)} class="fa-pill'
f'{" on" if state.get("family") == f else ""}" '
f'style="font-size:var(--text-2xs)">{e(f)}</button>'
for f in data.get("families", ()))
return (
f'<div style="{PANEL}">{_panel_title("Enroll a model")}'
'<div style="padding:10px;display:flex;flex-direction:column;gap:8px">'
f'<input value="{a(state.get("hfid", ""))}" '
f'data-bit-input="hfid" placeholder="author/model-name" '
'style="width:100%;padding:5px 7px;background:var(--bg-sunken);'
'border:1px solid var(--border-default);outline:none;'
'font-family:var(--font-mono);font-size:var(--text-xs);'
'color:var(--text-primary)" />'
f'<div style="display:flex;gap:4px;flex-wrap:wrap">{families}</div>'
'<div style="display:flex;align-items:center;gap:7px">'
f'<button {bit("enroll", "run")} style="padding:5px 10px;'
'background:transparent;border:1px solid var(--border-default);'
f'color:var(--text-secondary);cursor:pointer;{STYRENE};'
'font-size:var(--text-xs)">Smoke-test</button></div>'
f'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:{a(color)};text-wrap:pretty">{e(note)}</span>'
'<span style="font-size:var(--text-2xs);color:var(--text-tertiary);'
'text-wrap:pretty">Only models loadable through a vetted adapter family are '
'accepted. No user-supplied code is ever executed.</span></div></div>')
# --------------------------------------------------------------------------
# Footer
# --------------------------------------------------------------------------
def methodology(data: dict) -> str:
return (
'<div style="display:flex;align-items:flex-start;gap:10px;padding:9px 12px;'
'border:1px solid var(--border-subtle);background:var(--bg-panel)">'
'<span class="pixel-text" style="color:var(--accent-amber-strong);'
'flex:0 0 auto;margin-top:2px">i</span>'
'<span style="font-size:var(--text-xs);color:var(--text-secondary);'
'text-wrap:pretty">Forecasts are frozen at issue and never revised; quantiles '
'from N sampled paths where applicable; seeds shown; backfilled entries '
'labelled; grades computed from resolved forecasts only. Nothing here is '
'financial advice.</span>'
f'<a href="{a(data.get("methodology_url", "#"))}" target="_blank" rel="noopener" '
'style="margin-left:auto;font-family:var(--font-mono);font-size:var(--text-2xs);'
'white-space:nowrap;flex:0 0 auto">METHODOLOGY ↗</a></div>')
def footer(data: dict) -> str:
nav = data.get("nav") or {}
products = [i.get("name", "") for i in nav.get("items", [])][:12]
prod_html = "".join(
f'<span style="color:var(--text-secondary);font-size:var(--text-xs)">{e(p)}</span>'
for p in products)
resources = "".join(
f'<a href="{a(url)}" target="_blank" rel="noopener" '
f'style="color:var(--text-secondary);font-size:var(--text-xs)">{e(label)}</a>'
for label, url in data.get("footer_resources", ()))
return (
f'<footer style="{PANEL}">'
'<div class="fa-foot">'
'<div style="padding:14px;border-right:1px solid var(--border-subtle)">'
f'<div style="{STYRENE};font-size:var(--text-2xs);'
'letter-spacing:var(--tracking-wider);color:var(--text-tertiary);'
'margin-bottom:8px">Products</div>'
'<div style="display:grid;grid-template-columns:1fr 1fr;gap:3px 12px">'
f'{prod_html}</div></div>'
'<div style="padding:14px;border-right:1px solid var(--border-subtle)">'
f'<div style="{STYRENE};font-size:var(--text-2xs);'
'letter-spacing:var(--tracking-wider);color:var(--text-tertiary);'
'margin-bottom:8px">Resources</div>'
'<div style="display:flex;flex-direction:column;gap:3px">'
f'{resources}</div></div>'
'<div style="padding:14px;border-right:1px solid var(--border-subtle)">'
f'<div style="{STYRENE};font-size:var(--text-2xs);'
'letter-spacing:var(--tracking-wider);color:var(--text-tertiary);'
'margin-bottom:8px">Method</div>'
'<div style="display:flex;flex-direction:column;gap:3px">'
'<span style="color:var(--text-secondary);font-size:var(--text-xs)">'
'Frozen at issue</span>'
'<span style="color:var(--text-secondary);font-size:var(--text-xs)">'
'Seeded and reproducible</span>'
'<span style="color:var(--text-secondary);font-size:var(--text-xs)">'
'Backfill labelled</span>'
'<span style="color:var(--text-secondary);font-size:var(--text-xs)">'
'Graded on resolved only</span></div></div>'
'<div style="padding:14px;background:var(--bg-raised)">'
'<div style="display:flex;align-items:center;gap:6px;margin-bottom:8px">'
'<span class="pixel-text" style="color:var(--accent-amber-strong)">⚠</span>'
f'<span style="{STYRENE};font-size:var(--text-2xs);'
'letter-spacing:var(--tracking-wider);color:var(--accent-amber-strong)">'
'Disclaimer</span></div>'
'<div class="styrene-text" style="font-size:var(--text-xs);'
'text-transform:uppercase;letter-spacing:var(--tracking-wide);'
'color:var(--text-secondary);line-height:var(--leading-normal);'
'text-wrap:pretty">The Bit Trading Company publishes research tools and '
'educational software. Nothing here is financial advice. Forecasts are model '
'output, not predictions. Past performance does not predict future results.'
'</div></div></div>'
'<div style="display:flex;align-items:center;gap:14px;padding:8px 14px;'
'border-top:1px solid var(--border-subtle);flex-wrap:wrap">'
'<span style="display:inline-block;width:6px;height:6px;background:var(--fin-up);'
'animation:bitPulse 2s ease-in-out infinite"></span>'
'<span class="mono-data" style="font-size:var(--text-2xs);'
f'color:var(--text-tertiary)">{e(data.get("status_line", ""))}</span>'
'<span class="mono-data" style="font-size:var(--text-2xs);'
'color:var(--text-tertiary);margin-left:auto">'
'© 2026 THE BIT TRADING COMPANY</span></div></footer>')
# --------------------------------------------------------------------------
# The page
# --------------------------------------------------------------------------
def page(state: dict, data: dict) -> str:
"""The whole document body, from state. Pure -- no I/O anywhere below."""
return (
'<div class="bit-root" style="background:var(--bg-canvas);'
'color:var(--text-primary);display:flex;align-items:stretch;'
'font-family:var(--font-body);font-size:var(--text-base)">'
f'{sidebar.render(data.get("nav") or {}, active="Forecast Arena", emit=emit)}'
'<div style="flex:1 1 auto;min-width:0;display:flex;flex-direction:column">'
f'{header(state, data)}'
'<main style="flex:1 1 auto;min-width:0;padding:12px;display:flex;'
'flex-direction:column;gap:12px">'
f'{title_row(state, data)}'
f'{stats_bar(data.get("stats", []))}'
f'{models_section(state, data)}'
f'{controls(state, data)}'
'<div class="fa-zones">'
'<div class="fa-main">'
f'{chart_section(state, data)}'
f'{trackrecord_section(state, data)}'
'</div>'
f'{rail(state, data)}'
'</div>'
f'{methodology(data)}'
f'{footer(data)}'
'</main></div></div>')