"""The design's own markup, rendered from state. Every visible control here is the element the design uses -- a real `" ) def segment(label, action, *, active=False, first=False): """A full-width segmented control cell (`4px 6px`, styrene, uppercase).""" bg = "var(--accent-amber)" if active else "transparent" fg = "var(--stone-950)" if active else "var(--text-secondary)" return ( f'' ) def field_label(text): return ( f'
{esc(text)}
' ) def row(children, gap="4px"): return ( f'
' f'{"".join(children)}
' ) def field(label, children, gap="4px"): return f"
{field_label(label)}{row(children, gap)}
" def note(text, danger=False): color = "var(--fin-down)" if danger else "var(--accent-amber)" return ( f'
{text}
' ) def micro(text): return f'
{esc(text)}
' def panel(title, body, meta=""): m = (f'{esc(meta)}') if meta else "" return ( f'
' f'
' f'" f"{esc(title)}{m}
" f'
{body}
' ) def section(key, number, title, open_, body): """A numbered, collapsible left-panel section.""" glyph = "-" if open_ else "+" inner = ( f'
{body}
' ) if open_ else "" return ( f'
' f'{inner}
' ) # -------------------------------------------------------------------------- # Top bar # -------------------------------------------------------------------------- def nav_tab(label, key, active): """A header navigation tab.""" color = "var(--text-primary)" if active else "var(--text-tertiary)" border = "var(--accent-amber)" if active else "transparent" return ( f'' ) def glossary_tooltip(items): """A `?` in the header that reveals the metrics glossary on hover. Pure CSS -- no JS, and no state to keep in sync. """ rows = "".join( f'
' f'
{esc(t)}
' f'
{esc(d)}
' for t, d in items) return ( f'' f'?' f'' f'Metrics glossary{rows}' ) def login_control(user=None, on_space=True): """Signed-in handle, or a note when there is no OAuth to reach. The sign-in *button* is a real `gr.LoginButton` placed beside this markup: Gradio only mounts `/login/huggingface` when it sees that component in the app, so hand-rolling an anchor points at a route that returns 404. """ if user: return ( f'@{esc(user)}' ) if not on_space: return ( f'SIGN IN · ON SPACE' ) return "" # the real LoginButton renders here def top_bar(context="", status="NO RUN LOADED", tone="idle", elapsed="", tab="compare", glossary=(), user=None, on_space=True): colors = { "ok": ("var(--accent-moss-strong)", "var(--accent-moss-dim)"), "run": ("var(--accent-amber-strong)", "var(--accent-amber-dim)"), "warn": ("var(--fin-down)", "var(--fin-down)"), "idle": ("var(--text-tertiary)", "var(--border-default)"), } color, border = colors.get(tone, colors["idle"]) ctx = ( f'{esc(context)}' ) if context else "" el = ( f'{esc(elapsed)}' ) if elapsed else "" pulse = "animation:bitPulse 2s ease-in-out infinite" if tone == "run" else "" return ( f'
' f"{MARK}" f'/' f'Backtest Lab' f'' f"{ctx}" f'
' f"{el}" f'' f'' f'{esc(status)}' f"{glossary_tooltip(glossary) if glossary else ''}" f"{login_control(user, on_space)}" f'STORE ↗' f"
" ) def footer(): return ( f'" ) # -------------------------------------------------------------------------- # Inputs # -------------------------------------------------------------------------- def number_input(param_key, label, value, *, step="any"): """Label left, boxed value right -- the design's parameter row.""" val = "" if value is None else value return ( f'
' f'' f"{esc(label)}" f'
' ) def toggle(action, label, on, *, warn_when_off=False): """A two-state switch rendered as the design's segmented pair.""" danger = warn_when_off and not on on_bg = "var(--accent-amber)" if on else "transparent" off_bg = "var(--fin-down)" if danger else "transparent" on_fg = "var(--stone-950)" if on else "var(--text-tertiary)" off_fg = "var(--stone-950)" if danger else "var(--text-tertiary)" return ( f'
' f'' f"{esc(label)}" f'
' f'' f'
' ) # -------------------------------------------------------------------------- # Left panel -- Strategy Builder # -------------------------------------------------------------------------- def left_panel(st, *, presets, assets, timeframes, models, preset_params): """The design's 286px aside, rendered from state.""" open_ = st.get("acc", {}) preset_chips = row( [chip(p, emit("strategy", p), active=(p == st["strategy"])) for p in presets]) params = "".join( number_input(k, label, st["params"].get(k, default)) for k, label, default in preset_params) model_block = "" if st.get("needs_signals"): model_block = field( "Forecast model", [chip(m, emit("model", m), active=(m == st.get("model"))) for m in models] or [micro("no models cached")]) strategy_body = ( field_label("Preset") + preset_chips + (f'
{params}
' if params else "") + model_block) universe_body = ( field("Ticker", [chip(a, emit("asset", a), active=(a == st["asset"])) for a in assets]) + field("Timeframe", [chip(t, emit("tf", t), active=(t == st["timeframe"])) for t in timeframes]) + field("Date range", [chip(r, emit("range", r), active=(r == st["range"])) for r in ("1Y", "3Y", "5Y", "Max")]) + (micro(st["coverage"]) if st.get("coverage") else "")) costs_body = ( toggle("costs", "Costs", st["costs_on"], warn_when_off=True) + number_input("commission_bps", "Commission bps / side", st["commission_bps"]) + number_input("slippage_bps", "Slippage bps", st["slippage_bps"]) + field("Slippage model", [segment("Fixed bps", emit("slippage", "fixed"), active=st["slippage_model"] == "fixed", first=True), segment("Volume", emit("slippage", "volume_scaled"), active=st["slippage_model"] == "volume_scaled")], gap="0") + field("Fill", [chip("Next bar open", None, active=True, title="Enforced by the engine; not configurable.")]) + note("Costs on. Turning these off is how strategies lie to you.", danger=not st["costs_on"])) sizing_body = ( field("Sizing", [segment("Fixed %", emit("sizing", "fixed_pct"), active=st["sizing_mode"] == "fixed_pct", first=True), segment("Vol-target", emit("sizing", "vol_target"), active=st["sizing_mode"] == "vol_target")], gap="0") + number_input("size_pct", "Position size", st["size_pct"], step="0.05") + number_input("leverage", "Leverage", st["leverage"], step="0.5") + number_input("sl_pct", "Stop loss %", st["sl_pct"]) + number_input("tp_pct", "Take profit %", st["tp_pct"]) + number_input("trail_pct", "Trailing stop %", st["trail_pct"])) val_modes = [("Walk-forward", "walk_forward"), ("Split", "split"), ("Holdout", "holdout"), ("None", "none")] validation_body = ( field("Mode", [chip(lbl, emit("validation", v), active=st["validation_mode"] == v) for lbl, v in val_modes]) + number_input("train_months", "Train months", st["train_months"]) + number_input("test_months", "Test months", st["test_months"]) + number_input("roll_months", "Roll months", st["roll_months"]) + number_input("holdout_months", "OOS holdout months", st["holdout_months"])) sections = ( section("strategy", "1", "Strategy", open_.get("strategy", True), strategy_body) + section("universe", "2", "Universe & Data", open_.get("universe", True), universe_body) + section("costs", "3", "Costs & Execution", open_.get("costs", False), costs_body) + section("sizing", "4", "Sizing & Risk", open_.get("sizing", False), sizing_body) + section("validation", "5", "Validation", open_.get("validation", False), validation_body)) run_row = ( f'
' f'' f'
') return ( f'") # -------------------------------------------------------------------------- # Stat band # -------------------------------------------------------------------------- def stat_cell(label, value, sub, *, tone_class="", title=""): color = {"up": "var(--fin-up-strong)", "down": "var(--fin-down-strong)"}.get(tone_class, "var(--text-primary)") t = f' title="{esc(title)}"' if title else "" return ( f'' f'
{esc(label)}
' f'
{value}
' f'
{sub}
' ) def stat_band(cells, notes=()): band = ( f'
' f'{"".join(cells)}
' ) return band + "".join(notes) # -------------------------------------------------------------------------- # Tables -- rendered as markup, not as a Gradio Dataframe # -------------------------------------------------------------------------- def table(headers, rows, *, align_right=(), max_height="430px", empty="no rows"): """The design's table treatment: pixel-text header, mono body, 1px rules.""" if not rows: return micro(empty) def cell_style(i, header=False): a = "right" if i in align_right else "left" if header: return (f"padding:5px 8px;text-align:{a};" f"background:var(--bg-raised);color:var(--text-tertiary);" f"border-bottom:1px solid var(--border-default);" f"position:sticky;top:0;white-space:nowrap") return (f"padding:4px 8px;text-align:{a};color:var(--text-secondary);" f"border-bottom:1px solid var(--border-subtle);white-space:nowrap") head = "".join( f'{esc(h)}' for i, h in enumerate(headers)) body = "".join( "" + "".join( f'{c}' for i, c in enumerate(r) ) + "" for r in rows) return ( f'
' f'" f"{head}{body}
" ) def frame_to_rows(df, limit=200): """DataFrame -> list of escaped string rows, ready for `table`.""" if df is None or df.empty: return [], [] sub = df.head(limit) headers = [str(c) for c in sub.columns] rows = [[esc("" if v is None else v) for v in rec] for rec in sub.itertuples(index=False, name=None)] return headers, rows # -------------------------------------------------------------------------- # Compare view controls # -------------------------------------------------------------------------- def compare_controls(st, *, metrics, assets, timeframes, strategies_, models): """How the leaderboard is ranked, filtered and plotted. Rendered as the design's chips rather than dropdowns so the controls read as part of the board rather than a form sitting above it. Filters are multi-select: clicking a chip toggles it, and none selected means all. """ sel = st.get("filters", {}) def toggle_row(label, kind, options, active): chips = [chip(o, emit("filter", f"{kind}={o}"), active=(o in active)) for o in options] return field(label, chips) rank = field("Rank by", [ chip(m, emit("metric", m), active=(m == st["metric"])) for m in metrics]) top = field("Show top", [ chip(str(n), emit("topn", str(n)), active=(int(st["topn"]) == n)) for n in (10, 15, 25, 50)]) minimum = field("Min trades", [ chip(str(n), emit("filter", f"min_trades={n}"), active=int(sel.get("min_trades", 0)) == n) for n in (0, 20, 50)]) flags = field("Show", [ chip("Out-of-sample only", emit("filter", "require_oos=toggle"), active=bool(sel.get("require_oos", True))), chip("Hide baselines", emit("filter", "hide_baselines=toggle"), active=bool(sel.get("hide_baselines", False))), chip("Reset", emit("reset"), active=False), ]) body = ( f'
{rank}{top}{minimum}' f"{flags}
" + toggle_row("Assets", "asset", assets, sel.get("assets", [])) + toggle_row("Timeframes", "tf", timeframes, sel.get("timeframes", [])) + toggle_row("Strategies", "strategy", strategies_, sel.get("strategies", [])) + toggle_row("Models", "model", models, sel.get("models", [])) ) return panel("View", body, meta="CLICK TO FILTER ยท NONE SELECTED = ALL") def chart_controls(st): """Plot options for the Backtest overview.""" return row([ chip("Log scale", emit("logscale"), active=bool(st.get("log_scale"))), chip("Colorblind-safe", emit("cvd"), active=bool(st.get("cvd"))), ], gap="6px")