NeoSapian commited on
Commit
9bb2c09
·
verified ·
1 Parent(s): 969c5b9

Create index.html

Browse files
Files changed (1) hide show
  1. index.html +506 -0
index.html ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>jev-fin-0.8b · typed finance decisions</title>
7
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E📊%3C/text%3E%3C/svg%3E">
8
+ <style>
9
+ :root{--bg:#f4f6fb;--panel:#fff;--panel2:#f8f9fd;--bd:#e4e8f2;--tx:#0f172a;--mut:#64748b;--acc:#6366f1;--acc2:#14b8a6;--sky:#0ea5e9;
10
+ --good:#10b981;--bad:#f43f5e;--warn:#f59e0b;--shadow:0 1px 2px rgba(15,23,42,.05),0 8px 24px rgba(15,23,42,.06);--r:18px;color-scheme:light}
11
+ [data-theme=dark]{--bg:#0a0f1f;--panel:#121935;--panel2:#0e1430;--bd:#243055;--tx:#e9edff;--mut:#93a0c9;--shadow:0 1px 2px rgba(0,0,0,.4),0 10px 30px rgba(0,0,0,.35);color-scheme:dark}
12
+ *{box-sizing:border-box}html{scroll-behavior:smooth}
13
+ body{margin:0;background:var(--bg);color:var(--tx);font:15px/1.55 ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;-webkit-font-smoothing:antialiased}
14
+ body::before{content:"";position:fixed;inset:0;z-index:-1;background:radial-gradient(900px 500px at 8% -10%,rgba(99,102,241,.16),transparent 60%),radial-gradient(800px 480px at 100% 0,rgba(20,184,166,.14),transparent 60%)}
15
+ .wrap{max-width:1160px;margin:0 auto;padding:0 20px}
16
+ /* nav */
17
+ nav{position:sticky;top:0;z-index:20;backdrop-filter:blur(14px);background:color-mix(in srgb,var(--bg) 80%,transparent);border-bottom:1px solid var(--bd)}
18
+ nav .wrap{display:flex;align-items:center;gap:14px;height:60px}
19
+ .logo{font-weight:800;letter-spacing:-.02em;font-size:1.05rem;display:flex;align-items:center;gap:8px;white-space:nowrap}
20
+ .logo i{width:30px;height:30px;border-radius:9px;background:linear-gradient(135deg,var(--acc),var(--acc2));display:grid;place-items:center;font-style:normal;color:#fff;font-size:1rem}
21
+ .tabs{display:flex;gap:4px;margin-left:10px;overflow-x:auto}
22
+ .tab{border:0;background:transparent;color:var(--mut);font:inherit;font-weight:600;padding:8px 14px;border-radius:10px;cursor:pointer;white-space:nowrap;transition:.15s}
23
+ .tab:hover{color:var(--tx);background:var(--panel2)}.tab.on{color:var(--tx);background:var(--panel);box-shadow:var(--shadow)}
24
+ .sp{flex:1}
25
+ .status{display:flex;align-items:center;gap:7px;font-size:.8rem;color:var(--mut);padding:5px 11px;border:1px solid var(--bd);border-radius:999px;background:var(--panel);white-space:nowrap}
26
+ .dot{width:8px;height:8px;border-radius:50%;background:var(--warn);box-shadow:0 0 0 0 rgba(245,158,11,.6);animation:pulse 1.6s infinite}.dot.ok{background:var(--good);animation:none}.dot.err{background:var(--bad);animation:none}
27
+ @keyframes pulse{70%{box-shadow:0 0 0 8px rgba(245,158,11,0)}100%{box-shadow:0 0 0 0 rgba(245,158,11,0)}}
28
+ .icon{border:1px solid var(--bd);background:var(--panel);color:var(--tx);width:36px;height:36px;border-radius:10px;cursor:pointer;font-size:1rem}
29
+ /* hero */
30
+ .hero{margin:26px 0 22px;border-radius:26px;padding:34px 34px 28px;color:#fff;position:relative;overflow:hidden;background:linear-gradient(120deg,#4338ca 0%,#0ea5e9 58%,#14b8a6 100%);box-shadow:var(--shadow)}
31
+ .hero::after{content:"";position:absolute;right:-80px;top:-80px;width:320px;height:320px;border-radius:50%;background:radial-gradient(circle,rgba(255,255,255,.28),transparent 65%)}
32
+ .hero h1{margin:0 0 8px;font-size:clamp(1.7rem,3.4vw,2.5rem);letter-spacing:-.03em;line-height:1.1}
33
+ .hero p{margin:0;max-width:720px;font-size:1.04rem;opacity:.95}
34
+ .steps{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:10px;margin-top:20px;position:relative;z-index:1}
35
+ .step{background:rgba(255,255,255,.14);border:1px solid rgba(255,255,255,.28);border-radius:14px;padding:11px 14px;font-size:.88rem}
36
+ .step b{display:block;margin-bottom:1px}
37
+ /* generic */
38
+ .panel{background:var(--panel);border:1px solid var(--bd);border-radius:var(--r);box-shadow:var(--shadow);padding:20px}
39
+ h2{margin:0 0 4px;font-size:1.15rem;letter-spacing:-.01em}.sub{color:var(--mut);font-size:.9rem;margin:0 0 14px}
40
+ label.l{display:block;font-size:.74rem;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--mut);margin:14px 0 6px}
41
+ .inp,textarea.inp{width:100%;font:inherit;color:var(--tx);background:var(--panel2);border:1px solid var(--bd);border-radius:12px;padding:10px 12px;outline:none;transition:.15s;resize:vertical}
42
+ .inp:focus{border-color:var(--acc);box-shadow:0 0 0 3px color-mix(in srgb,var(--acc) 22%,transparent)}
43
+ textarea.mono,.mono{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.86rem}
44
+ .btn{border:0;font:inherit;font-weight:700;cursor:pointer;border-radius:12px;padding:10px 18px;transition:.15s;display:inline-flex;align-items:center;gap:8px}
45
+ .btn.pri{color:#fff;background:linear-gradient(135deg,var(--acc),var(--sky));box-shadow:0 6px 18px rgba(99,102,241,.35)}.btn.pri:hover{transform:translateY(-1px)}
46
+ .btn.pri:disabled{opacity:.6;cursor:wait;transform:none}
47
+ .btn.ghost{background:var(--panel2);color:var(--tx);border:1px solid var(--bd)}.btn.ghost:hover{border-color:var(--acc)}
48
+ .btn.sm{padding:6px 12px;font-size:.84rem;border-radius:10px}
49
+ .spin{width:15px;height:15px;border-radius:50%;border:2px solid rgba(255,255,255,.4);border-top-color:#fff;animation:rot .7s linear infinite;display:none}.loading .spin{display:inline-block}
50
+ @keyframes rot{to{transform:rotate(360deg)}}
51
+ .chips{display:flex;flex-wrap:wrap;gap:8px}
52
+ .chip{border:1px solid var(--bd);background:var(--panel2);color:var(--tx);font:inherit;font-size:.86rem;font-weight:600;padding:7px 13px;border-radius:999px;cursor:pointer;transition:.15s}
53
+ .chip:hover{border-color:var(--acc);transform:translateY(-1px)}.chip.on{background:linear-gradient(135deg,var(--acc),var(--sky));color:#fff;border-color:transparent}
54
+ .tag{display:inline-block;font-size:.66rem;font-weight:800;letter-spacing:.07em;text-transform:uppercase;padding:3px 9px;border-radius:999px;color:#fff;white-space:nowrap}
55
+ .pill{display:inline-block;color:#fff;font-weight:700;font-size:.84rem;padding:3px 12px;border-radius:999px;margin:0 8px 6px 0}
56
+ .mini{display:inline-block;font-size:.76rem;padding:2px 9px;border-radius:999px;border:1px solid var(--bd);color:var(--mut);margin:0 6px 6px 0}
57
+ .mini.up{color:var(--good);border-color:color-mix(in srgb,var(--good) 45%,transparent)}.mini.down{color:var(--bad);border-color:color-mix(in srgb,var(--bad) 45%,transparent)}.mini.warn{color:#b45309;border-color:color-mix(in srgb,var(--warn) 55%,transparent)}
58
+ [data-theme=dark] .mini.warn{color:#fbbf24}
59
+ /* playground layout */
60
+ .grid2{display:grid;grid-template-columns:minmax(0,1.05fr) minmax(0,.95fr);gap:20px;align-items:start}
61
+ @media(max-width:900px){.grid2{grid-template-columns:1fr}}
62
+ .sticky{position:sticky;top:76px}@media(max-width:900px){.sticky{position:static}}
63
+ .qcard{border:1px solid var(--bd);background:var(--panel2);border-radius:16px;padding:14px;margin-top:12px;transition:.2s}
64
+ .qcard.off{opacity:.5}
65
+ .qtop{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:10px}
66
+ .qnum{font-weight:800;color:var(--acc)}
67
+ .seg{display:inline-flex;background:var(--panel);border:1px solid var(--bd);border-radius:11px;padding:3px}
68
+ .seg button{border:0;background:transparent;color:var(--mut);font:inherit;font-size:.82rem;font-weight:700;padding:5px 11px;border-radius:8px;cursor:pointer}
69
+ .seg button.on{background:linear-gradient(135deg,var(--acc),var(--sky));color:#fff}
70
+ .switch{position:relative;width:40px;height:22px;display:inline-block}.switch input{display:none}
71
+ .switch span{position:absolute;inset:0;background:var(--bd);border-radius:99px;cursor:pointer;transition:.2s}
72
+ .switch span::before{content:"";position:absolute;left:3px;top:3px;width:16px;height:16px;background:#fff;border-radius:50%;transition:.2s;box-shadow:0 1px 3px rgba(0,0,0,.3)}
73
+ .switch input:checked+span{background:var(--good)}.switch input:checked+span::before{transform:translateX(18px)}
74
+ .x{margin-left:auto;border:0;background:transparent;color:var(--mut);cursor:pointer;font-size:1rem;padding:4px 8px;border-radius:8px}.x:hover{color:var(--bad);background:color-mix(in srgb,var(--bad) 12%,transparent)}
75
+ .hint{font-size:.78rem;color:var(--mut);margin-top:5px}
76
+ .actions{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-top:16px}
77
+ .tog{display:flex;align-items:center;gap:8px;font-size:.88rem;color:var(--mut)}
78
+ kbd{font:inherit;font-size:.72rem;border:1px solid var(--bd);border-bottom-width:2px;border-radius:6px;padding:1px 6px;color:var(--mut)}
79
+ details{margin-top:14px;border:1px solid var(--bd);border-radius:12px;background:var(--panel2)}summary{cursor:pointer;padding:10px 14px;font-weight:600;font-size:.9rem}
80
+ details pre{margin:0;padding:0 14px 14px;overflow:auto;font-size:.8rem;white-space:pre-wrap;color:var(--mut)}
81
+ /* result cards */
82
+ .sumline{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:12px;color:var(--mut);font-size:.84rem}
83
+ .rcard{background:var(--panel2);border:1px solid var(--bd);border-radius:16px;padding:16px 18px;margin-bottom:12px;animation:in .4s ease-out both}
84
+ @keyframes in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}
85
+ @keyframes grow{from{width:0}}@keyframes grow-h{from{height:0}}
86
+ .rhead{display:flex;align-items:flex-start;gap:10px;margin-bottom:12px}.rq{font-weight:600;line-height:1.35}
87
+ .flex{display:flex;gap:18px;align-items:center;flex-wrap:wrap}.gr1{flex:1;min-width:200px}
88
+ .ring{width:104px;height:104px;border-radius:50%;flex:none;position:relative;display:grid;place-items:center;background:conic-gradient(var(--c) calc(var(--p)*1%),var(--bd) 0)}
89
+ .ring::before{content:"";position:absolute;inset:10px;border-radius:50%;background:var(--panel2)}.ring b{position:relative;font-size:1.3rem;font-weight:800}
90
+ .row{display:grid;grid-template-columns:minmax(80px,170px) 1fr 58px;gap:10px;align-items:center;margin:7px 0;font-size:.9rem}.row.top{font-weight:700}
91
+ .track{height:12px;border-radius:99px;background:var(--bd);overflow:hidden}.track i{display:block;height:100%;border-radius:99px;animation:grow .9s cubic-bezier(.2,.8,.2,1)}
92
+ .row b{text-align:right;font-variant-numeric:tabular-nums;color:var(--mut);font-weight:600}
93
+ .ans{font-size:1.05rem;margin-bottom:8px}.ans strong{font-size:1.2rem}
94
+ .scale{position:relative;height:10px;border-radius:99px;background:linear-gradient(90deg,#6366f1,#14b8a6);margin:16px 4px 8px}
95
+ .marker{position:absolute;top:-6px;width:4px;height:22px;border-radius:3px;background:var(--tx);transform:translateX(-2px);box-shadow:0 0 0 3px var(--panel2);transition:left .8s cubic-bezier(.2,.8,.2,1)}
96
+ .cols{display:grid;gap:8px;margin-top:10px}.col{text-align:center;font-size:.8rem}.cw{height:84px;display:flex;align-items:flex-end}
97
+ .cb{width:100%;border-radius:8px 8px 3px 3px;min-height:3px;animation:grow-h .9s cubic-bezier(.2,.8,.2,1)}
98
+ .col .p{font-weight:700;margin-top:3px;font-variant-numeric:tabular-nums}.col .n{color:var(--mut)}
99
+ .check{margin-top:10px;font-size:.84rem;padding:7px 11px;border-radius:10px}
100
+ .check.ok{background:color-mix(in srgb,var(--good) 15%,transparent);color:#059669}.check.bad{background:color-mix(in srgb,var(--warn) 16%,transparent);color:#b45309}
101
+ [data-theme=dark] .check.ok{color:#34d399}[data-theme=dark] .check.bad{color:#fbbf24}
102
+ .note{margin-top:8px;font-size:.82rem;color:var(--mut)}
103
+ .empty{padding:40px 20px;text-align:center;color:var(--mut);border:2px dashed var(--bd);border-radius:16px}
104
+ .err{padding:14px 16px;border-radius:14px;background:color-mix(in srgb,var(--bad) 12%,transparent);color:var(--bad);border:1px solid color-mix(in srgb,var(--bad) 40%,transparent);font-size:.9rem}
105
+ .skel{height:120px;border-radius:16px;margin-bottom:12px;background:linear-gradient(90deg,var(--panel2),var(--bd),var(--panel2));background-size:200% 100%;animation:sk 1.2s infinite}
106
+ @keyframes sk{to{background-position:-200% 0}}
107
+ /* portfolio */
108
+ .tbl{width:100%;border-collapse:separate;border-spacing:0 6px}
109
+ .tbl th{font-size:.7rem;text-transform:uppercase;letter-spacing:.06em;color:var(--mut);text-align:left;padding:0 6px}
110
+ .tbl td{padding:0 4px}.tbl .inp{padding:7px 9px;border-radius:9px}
111
+ .hold{display:grid;grid-template-columns:62px 1fr 150px;gap:10px;align-items:center;margin:8px 0;font-size:.86rem}
112
+ .ht{position:relative;height:14px;border-radius:99px;background:var(--bd)}.hf{height:100%;border-radius:99px;animation:grow .9s cubic-bezier(.2,.8,.2,1)}
113
+ .tg{position:absolute;top:-4px;bottom:-4px;width:3px;border-radius:2px;background:var(--tx)}
114
+ .hold .v{text-align:right;color:var(--mut);font-variant-numeric:tabular-nums}
115
+ /* about */
116
+ .flow{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px;margin-bottom:6px}
117
+ .flow>div{background:var(--panel2);border:1px solid var(--bd);border-radius:14px;padding:14px;font-size:.88rem;position:relative}
118
+ .flow b{display:block;margin-bottom:3px;color:var(--acc)}
119
+ .two{display:grid;grid-template-columns:1fr 1fr;gap:20px}@media(max-width:800px){.two{grid-template-columns:1fr}}
120
+ ul.t{margin:6px 0 0;padding-left:18px;color:var(--mut)}ul.t li{margin:5px 0}ul.t b{color:var(--tx)}
121
+ table.m{width:100%;border-collapse:collapse;font-size:.86rem}table.m th,table.m td{padding:8px 10px;border-bottom:1px solid var(--bd);text-align:right}
122
+ table.m th:first-child,table.m td:first-child{text-align:left}table.m th{font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;color:var(--mut)}
123
+ .abar{display:inline-block;vertical-align:middle;height:7px;border-radius:9px;background:linear-gradient(90deg,var(--acc),var(--acc2));margin-right:8px}
124
+ pre.code{background:var(--panel2);border:1px solid var(--bd);border-radius:12px;padding:14px;overflow:auto;font-size:.8rem;margin:8px 0 0}
125
+ footer{color:var(--mut);font-size:.8rem;text-align:center;padding:26px 0 40px}
126
+ .hide{display:none!important}
127
+ </style>
128
+ </head>
129
+ <body>
130
+ <nav><div class="wrap">
131
+ <div class="logo"><i>📊</i> jev-fin-0.8b</div>
132
+ <div class="tabs" id="tabs">
133
+ <button class="tab on" data-tab="play">Playground</button>
134
+ <button class="tab" data-tab="port">Portfolio lab</button>
135
+ <button class="tab" data-tab="about">About &amp; API</button>
136
+ </div>
137
+ <div class="sp"></div>
138
+ <div class="status"><span class="dot" id="dot"></span><span id="stxt">Warming up model…</span></div>
139
+ <button class="icon" id="theme" title="Toggle theme">🌓</button>
140
+ </div></nav>
141
+
142
+ <main class="wrap">
143
+ <section class="hero">
144
+ <h1>Typed decisions for finance,<br>with calibrated probabilities.</h1>
145
+ <p>A small model that <b>doesn’t write text</b>. Give it a text or JSON state and a typed question: yes/no, pick one, or an ordered scale.
146
+ It answers with probabilities in a single forward pass. Fast, checkable, easy to plug into agents.</p>
147
+ <div class="steps">
148
+ <div class="step"><b>1 · Pick a scenario</b>news, Fed text, tweets, financials, loans, macro</div>
149
+ <div class="step"><b>2 · Shape the questions</b>yes/no, pick one, or an ordered scale</div>
150
+ <div class="step"><b>3 · Read the odds</b>rings, bars and scales, with change vs your last run</div>
151
+ </div>
152
+ </section>
153
+
154
+ <!-- PLAYGROUND -->
155
+ <section id="view-play">
156
+ <div class="grid2">
157
+ <div class="panel">
158
+ <h2>Setup</h2><p class="sub">Start from a scenario, then edit anything.</p>
159
+ <div class="chips" id="presets"></div>
160
+ <label class="l" for="state">State: text or JSON the model reads</label>
161
+ <textarea class="inp" id="state" rows="5"></textarea>
162
+ <div id="qs"></div>
163
+ <div class="actions">
164
+ <button class="btn ghost sm" id="addq">+ Add question</button>
165
+ <label class="tog"><span class="switch"><input type="checkbox" id="debias" checked><span></span></span>Debias (reverse-order average)</label>
166
+ <div class="sp"></div>
167
+ <button class="btn pri" id="go"><span class="spin"></span>▶ Analyze <kbd>Ctrl ↵</kbd></button>
168
+ </div>
169
+ </div>
170
+ <div class="sticky">
171
+ <div class="panel">
172
+ <h2>Results</h2><p class="sub">Probabilities are temperature-calibrated on held-out data.</p>
173
+ <div id="out"><div class="empty">Pick a scenario on the left, or write your own state and questions, then press <b>Analyze</b>.</div></div>
174
+ <details id="pdet" class="hide"><summary>🔍 What the model actually sees</summary><pre id="prompts"></pre></details>
175
+ <details id="rdet" class="hide"><summary>{ } Raw output</summary><pre id="raw"></pre></details>
176
+ </div>
177
+ </div>
178
+ </div>
179
+ </section>
180
+
181
+ <!-- PORTFOLIO -->
182
+ <section id="view-port" class="hide">
183
+ <div class="grid2">
184
+ <div class="panel">
185
+ <h2>Holdings</h2><p class="sub">Edit the table, then analyze. Every answer is checked against the exact calculation.</p>
186
+ <table class="tbl"><thead><tr><th>Ticker</th><th>Sector</th><th>Weight %</th><th>Target %</th><th>Vol %</th><th></th></tr></thead><tbody id="pfrows"></tbody></table>
187
+ <div class="actions">
188
+ <button class="btn ghost sm" id="pfadd">+ Row</button>
189
+ <button class="btn ghost sm" id="pfrand">🎲 Random</button>
190
+ <button class="btn ghost sm" id="pfnorm">⚖️ Normalise to 100%</button>
191
+ <div class="sp"></div>
192
+ <button class="btn pri" id="pfgo"><span class="spin"></span>▶ Analyze</button>
193
+ </div>
194
+ <div class="hint" style="margin-top:10px">Tip: change one weight and analyze again. Each card shows how the odds moved.</div>
195
+ </div>
196
+ <div class="sticky"><div class="panel"><h2>Risk read-out</h2><p class="sub">Model answer vs exact calculation.</p>
197
+ <div id="pfout"><div class="empty">Press <b>Analyze</b> to read the portfolio.</div></div></div></div>
198
+ </div>
199
+ </section>
200
+
201
+ <!-- ABOUT -->
202
+ <section id="view-about" class="hide">
203
+ <div class="panel" style="margin-bottom:20px"><h2>How it works</h2><p class="sub">No text generation. One forward pass, read at the option letters.</p>
204
+ <div class="flow">
205
+ <div><b>1 · State + question</b>Your text or JSON plus a typed question with options.</div>
206
+ <div><b>2 · Lettered prompt</b>Options become A, B, C… (shuffled and averaged in debias mode).</div>
207
+ <div><b>3 · One forward pass</b>Only the logits of the letter tokens are read.</div>
208
+ <div><b>4 · Calibrated odds</b>Softmax with a temperature fitted on held-out data.</div>
209
+ </div></div>
210
+ <div class="two">
211
+ <div class="panel"><h2>Writing good questions</h2>
212
+ <ul class="t">
213
+ <li><b>Yes / No</b> returns P(Yes). Phrase it so “Yes” is meaningful.</li>
214
+ <li><b>Pick one</b> works best with a short description per choice (<span class="mono">name: description</span>).</li>
215
+ <li><b>Ordered scale</b>: list levels from lowest to highest. You also get a 0–1 score.</li>
216
+ <li>For numeric JSON states, put thresholds in the question text, like the examples do.</li>
217
+ <li><b>Debias</b> asks twice with options reversed and averages. Slower, but removes position bias.</li>
218
+ </ul>
219
+ <h2 style="margin-top:18px">Limits</h2>
220
+ <ul class="t">
221
+ <li>It classifies the state you give it. It does <b>not</b> predict returns.</li>
222
+ <li>Arithmetic answers come from rule-labelled synthetic data. The Portfolio lab shows the exact result beside the model’s.</li>
223
+ <li>Calibration is measured in-distribution; expect worse on unfamiliar questions.</li>
224
+ <li>Not financial advice. Part of the training data is non-commercial, so use is <b>non-commercial only</b>.</li>
225
+ </ul></div>
226
+ <div class="panel"><h2>Call it from code</h2><p class="sub">The page uses the same endpoint.</p>
227
+ <pre class="code mono">from gradio_client import Client
228
+ import json
229
+ c = Client("&lt;your-space&gt;")
230
+ out = c.predict(
231
+ "Acme cut guidance and the CFO resigned.",
232
+ json.dumps({"neg": {"type": "noul",
233
+ "instructions": "Is this news negative?"}}),
234
+ True, # debias
235
+ api_name="/decide")
236
+ print(json.loads(out)["result"])</pre>
237
+ <h2 style="margin-top:18px">Or load the model directly</h2>
238
+ <pre class="code mono">clf = JevClassifier("siyah1/jev-fin-0.8b")
239
+ clf.decide(state, questions)</pre></div>
240
+ </div>
241
+ <div class="panel" style="margin-top:20px"><h2>Held-out test metrics</h2>
242
+ <p class="sub">Read live from the model repo. ECE = expected calibration error (lower is better). Compare accuracy with each source’s majority baseline before trusting a slice.</p>
243
+ <div style="overflow:auto"><table class="m" id="metrics"><tbody><tr><td>Loading…</td></tr></tbody></table></div></div>
244
+ </section>
245
+ <footer>jev-fin-0.8b · not financial advice · non-commercial use only</footer>
246
+ </main>
247
+
248
+ <script>
249
+ "use strict";
250
+ const $=(s,r=document)=>r.querySelector(s), $$=(s,r=document)=>[...r.querySelectorAll(s)];
251
+ const esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
252
+ const pct=p=>(p*100).toFixed(1)+'%', pct0=p=>Math.round(p*100)+'%';
253
+ const GOOD='#10b981',BAD='#f43f5e',WARN='#f59e0b',MUTED='#94a3b8';
254
+ const TCOL={noul:'#6366f1',choice:'#0ea5e9',score:'#14b8a6'}, TNAME={noul:'Yes / No',choice:'Pick one',score:'Ordered scale'};
255
+ const LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
256
+ const J=JSON.stringify;
257
+
258
+ /* ---------- API ---------- */
259
+ async function decide(state, questions, debias){
260
+ const r=await fetch('/g/gradio_api/call/decide',{method:'POST',headers:{'Content-Type':'application/json'},
261
+ body:J({data:[state,J(questions),debias]})});
262
+ if(!r.ok) throw new Error('Server returned '+r.status);
263
+ const {event_id}=await r.json();
264
+ const s=await fetch('/g/gradio_api/call/decide/'+event_id);
265
+ if(!s.ok||!s.body) throw new Error('Stream failed ('+s.status+')');
266
+ const reader=s.body.getReader(), dec=new TextDecoder(); let buf='', ev='', result=null;
267
+ for(;;){
268
+ const {done,value}=await reader.read(); if(done) break;
269
+ buf+=dec.decode(value,{stream:true});
270
+ let i; while((i=buf.indexOf('\n'))>=0){
271
+ const line=buf.slice(0,i).replace(/\r$/,''); buf=buf.slice(i+1);
272
+ if(line.startsWith('event:')) ev=line.slice(6).trim();
273
+ else if(line.startsWith('data:')){
274
+ const d=line.slice(5).trim();
275
+ if(ev==='complete'){ result=JSON.parse(d); }
276
+ else if(ev==='error'){ throw new Error(d&&d!=='null'?d:'The model call failed (are you out of GPU quota?)'); }
277
+ }
278
+ }
279
+ if(result) break;
280
+ }
281
+ if(!result) throw new Error('No response from the model');
282
+ const p=JSON.parse(result[0]);
283
+ if(!p.ok) throw new Error(p.error||'Model error');
284
+ return p;
285
+ }
286
+
287
+ /* ---------- question specs (mirrors the training prompt) ---------- */
288
+ function parseLines(text){
289
+ const out=[]; for(const raw of (text||'').split('\n')){const line=raw.trim(); if(!line) continue;
290
+ const i=line.indexOf(':'); const k=(i<0?line:line.slice(0,i)).trim(); const v=(i<0?'':line.slice(i+1).trim())||k; out.push([k,v]);}
291
+ return out;
292
+ }
293
+ function makeSpec(type,q,opts){
294
+ q=q.trim(); const spec={type,instructions:q};
295
+ if(type==='noul') return {spec,base:['No','Yes'],text:q};
296
+ const items=parseLines(opts);
297
+ if(items.length<2||items.length>26) throw new Error('needs 2–26 options, one per line');
298
+ const desc=items.some(([k,v])=>k!==v), lines=items.map(([k,v])=>`- ${k}: ${v}`).join('\n');
299
+ if(type==='choice'){spec.criteria=Object.fromEntries(items);return {spec,base:items.map(x=>x[0]),text:q+'\n'+lines};}
300
+ spec.levels=desc?Object.fromEntries(items):items.map(x=>x[0]);
301
+ return {spec,base:items.map(x=>x[0]),text:q+(desc?'\n'+lines:'')};
302
+ }
303
+ function buildPrompt(state,q,options,type){
304
+ const st=state.length>1600?state.slice(0,1600)+' ...':state;
305
+ return `<state>\n${st}\n</state>\n<question type="${type}">\n${q}\n</question>\n<options>\n${options.map((o,i)=>`${LETTERS[i]}. ${o}`).join('\n')}\n</options>\nAnswer:`;
306
+ }
307
+
308
+ /* ---------- result cards ---------- */
309
+ function bars(items){
310
+ const mx=Math.max(...items.map(i=>i[1]));
311
+ return items.map(([l,p,c])=>`<div class="row${p===mx?' top':''}"><span>${esc(l)}</span><div class="track"><i style="width:${(p*100).toFixed(1)}%;background:${c}"></i></div><b>${pct(p)}</b></div>`).join('');
312
+ }
313
+ function deltaChip(r,prev){
314
+ if(!prev||prev.type!==r.type) return '';
315
+ if(r.type==='noul'){const d=(r.noul-prev.p)*100;
316
+ if(Math.abs(d)<0.05) return '<span class="mini">no change vs previous run</span>';
317
+ return `<span class="mini ${d>0?'up':'down'}">${d>0?'▲':'▼'} ${d>0?'+':''}${d.toFixed(1)} pp vs previous run</span>`;}
318
+ const label=r.type==='choice'?r.choice:r.level;
319
+ if(label!==prev.label) return `<span class="mini warn">answer changed: ${esc(prev.label)} → ${esc(label)}</span>`;
320
+ const d=(r.confidence-prev.conf)*100; return `<span class="mini">same answer, confidence ${d>=0?'+':''}${d.toFixed(1)} pp</span>`;
321
+ }
322
+ function card(title,r,prev,note,check,delay){
323
+ const t=r.type, dl=deltaChip(r,prev); let body='';
324
+ if(t==='noul'){const p=r.noul; const [v,c]=p>=.65?['Likely YES',GOOD]:p<=.35?['Likely NO',BAD]:['Uncertain',WARN];
325
+ body=`<div class="flex"><div class="ring" style="--p:${(p*100).toFixed(1)};--c:${c}"><b>${pct0(p)}</b></div><div class="gr1"><span class="pill" style="background:${c}">${v}</span>${dl}${bars([['Yes',p,GOOD],['No',1-p,BAD]])}</div></div>`;
326
+ }else if(t==='choice'){
327
+ const ps=Object.entries(r.probabilities).sort((a,b)=>b[1]-a[1]); const low=r.confidence<.5?'<span class="mini warn">low confidence</span>':'';
328
+ body=`<div class="ans">Answer: <strong>${esc(r.choice)}</strong> <span class="mini">confidence ${pct0(r.confidence)}</span>${low}${dl}</div>`+bars(ps.map(([n,p],i)=>[n,p,i===0?TCOL.choice:MUTED]));
329
+ }else{
330
+ const lv=Object.entries(r.probabilities), mx=Math.max(...lv.map(x=>x[1])); const low=r.confidence<.5?'<span class="mini warn">low confidence</span>':'';
331
+ const cols=lv.map(([n,p])=>`<div class="col"><div class="cw"><div class="cb" style="height:${(Math.max(p,.02)*100).toFixed(0)}%;background:${p===mx?TCOL.score:MUTED}"></div></div><div class="p">${pct0(p)}</div><div class="n">${esc(n)}</div></div>`).join('');
332
+ body=`<div class="ans">Level: <strong>${esc(r.level)}</strong> <span class="mini">score ${r.score.toFixed(2)} (0 = lowest, 1 = highest)</span>${low}${dl}</div><div class="scale"><div class="marker" style="left:${(r.score*100).toFixed(1)}%"></div></div><div class="cols" style="grid-template-columns:repeat(${lv.length},1fr)">${cols}</div>`;
333
+ }
334
+ let extra=note?`<div class="note">${esc(note)}</div>`:'';
335
+ if(check) extra+=check[1]?`<div class="check ok">✅ Matches the exact calculation (${esc(check[0])})</div>`:`<div class="check bad">⚠️ Exact calculation says <b>${esc(check[0])}</b>. Check arithmetic-heavy answers with code.</div>`;
336
+ return `<div class="rcard" style="animation-delay:${(delay||0)*70}ms"><div class="rhead"><span class="tag" style="background:${TCOL[t]}">${TNAME[t]}</span><span class="rq">${esc(title)}</span></div>${body}${extra}</div>`;
337
+ }
338
+ const snap=r=>r.type==='noul'?{type:'noul',p:r.noul}:{type:r.type,label:r.choice||r.level,conf:r.confidence};
339
+ const sumline=(dt,dev,n)=>`<div class="sumline"><span class="mini">⏱ ${dt.toFixed(1)}s</span><span class="mini">🖥 ${esc(dev)}</span><span class="mini">${n} question${n===1?'':'s'}</span><span class="mini">calibrated</span></div>`;
340
+ const skeleton=n=>Array.from({length:n},()=>'<div class="skel"></div>').join('');
341
+ const errBox=m=>`<div class="err"><b>Something went wrong.</b><br>${esc(m)}</div>`;
342
+ function busy(btn,on){btn.classList.toggle('loading',on);btn.disabled=on;}
343
+
344
+ /* ---------- presets ---------- */
345
+ const NEWS='Acme Corp cut full-year guidance and the CFO resigned effective immediately.';
346
+ const PRESETS=[
347
+ {name:'📰 News shock',state:NEWS,qs:[
348
+ {type:'noul',q:'Is this news negative for the stock?',opts:''},
349
+ {type:'choice',q:'Which topic does this belong to?',opts:'earnings: results or guidance\npersonnel: executive changes\nm&a: mergers and deals'},
350
+ {type:'score',q:'How negative is this news?',opts:'mild\nmoderate\nsevere'}]},
351
+ {name:'🏦 Fed statement',state:'The Committee decided to raise the target range for the federal funds rate by 75 basis points and anticipates that ongoing increases will be appropriate to bring inflation back to 2 percent.',qs:[
352
+ {type:'score',q:'What is the monetary-policy stance of this FOMC statement?',opts:'dovish\nneutral\nhawkish'},
353
+ {type:'noul',q:'Does this statement signal tighter (hawkish) monetary policy?',opts:''},
354
+ {type:'noul',q:'Does this statement signal easier (dovish) monetary policy?',opts:''}]},
355
+ {name:'🐦 Finance tweet',state:'$AMZN - Morgan Stanley upgrades to Overweight, raises price target to $210 ahead of Q3 earnings',qs:[
356
+ {type:'score',q:'What is the market sentiment of this finance tweet?',opts:'Bearish\nNeutral\nBullish'},
357
+ {type:'choice',q:'Which topic does this financial news tweet belong to?',opts:'Analyst Update\nEarnings\nCompany | Product News\nStock Movement\nM&A | Investments'},
358
+ {type:'noul',q:'Does this text express a positive (bullish) outlook?',opts:''}]},
359
+ {name:'🏢 Company health',state:J({company:{revenue_musd:820.0,ebit_musd:96.0,interest_expense_musd:41.0,net_income_musd:38.5,total_assets_musd:1100.0,total_liabilities_musd:780.0,equity_musd:320.0,current_assets_musd:210.0,current_liabilities_musd:260.0}}),qs:[
360
+ {type:'noul',q:'Is the current ratio (current_assets_musd / current_liabilities_musd) below 1.0?',opts:''},
361
+ {type:'score',q:'Rate liquidity by current ratio = current_assets_musd / current_liabilities_musd (weak: below 1.0, adequate: 1.0 to below 1.5, strong: 1.5 to below 2.5, very strong: 2.5 or above).',opts:'weak\nadequate\nstrong\nvery strong'},
362
+ {type:'choice',q:'Classify leverage by debt-to-equity = total_liabilities_musd / equity_musd (conservative: below 0.5, moderate: 0.5 to below 1.5, aggressive: 1.5 or above).',opts:'conservative\nmoderate\naggressive'}]},
363
+ {name:'🏠 Loan application',state:J({loan_application:{annual_income:72000,monthly_debt_payments:1450,requested_monthly_payment:1300,credit_score:655,loan_to_value_pct:88.0}}),qs:[
364
+ {type:'noul',q:'Is the back-end debt-to-income ratio, (monthly_debt_payments + requested_monthly_payment) / (annual_income / 12), above 43%?',opts:''},
365
+ {type:'score',q:'Rate the credit tier by credit_score (poor: below 580, fair: 580 to 669, good: 670 to 739, very good: 740 to 799, exceptional: 800 or above).',opts:'poor\nfair\ngood\nvery good\nexceptional'},
366
+ {type:'choice',q:'Apply in order: decline if back-end DTI (as above) is over 50%; otherwise manual review if credit_score < 620 or loan_to_value_pct > 95; otherwise approve.',opts:'approve\nmanual review\ndecline'}]},
367
+ {name:'📉 Macro snapshot',state:J({macro:{fed_funds_pct:5.25,cpi_yoy_pct:4.8,unemployment_pct:4.1,yield_3m_pct:5.3,yield_2y_pct:4.9,yield_10y_pct:4.2}}),qs:[
368
+ {type:'noul',q:'Is the 2y/10y yield curve inverted (yield_2y_pct above yield_10y_pct)?',opts:''},
369
+ {type:'score',q:'Rate the real policy rate = fed_funds_pct - cpi_yoy_pct (deeply negative: below -2, negative: -2 to below 0, mildly positive: 0 to below 2, restrictive: 2 or above).',opts:'deeply negative\nnegative\nmildly positive\nrestrictive'},
370
+ {type:'choice',q:'Which regime fits? stagflation: cpi_yoy_pct >= 4 and unemployment_pct >= 6; overheating: cpi_yoy_pct >= 4 and unemployment_pct < 6; slack: cpi_yoy_pct < 4 and unemployment_pct >= 6; goldilocks: cpi_yoy_pct < 4 and unemployment_pct < 6.',opts:'stagflation\noverheating\nslack\ngoldilocks'}]}
371
+ ];
372
+ const HINT={noul:'',choice:'One per line. Optional description after a colon, e.g. personnel: executive changes',score:'Lowest to highest, one per line. Order matters.'};
373
+ const PH={choice:'earnings: results or guidance\npersonnel: executive changes',score:'mild\nmoderate\nsevere'};
374
+
375
+ /* ---------- playground ---------- */
376
+ let Q=[], prevPlay={}, MAXQ=6;
377
+ function renderQs(){
378
+ $('#qs').innerHTML=Q.map((x,i)=>`<div class="qcard${x.on?'':' off'}" data-i="${i}">
379
+ <div class="qtop"><span class="qnum">Q${i+1}</span>
380
+ <div class="seg">${['noul','choice','score'].map(t=>`<button data-t="${t}" class="${x.type===t?'on':''}">${TNAME[t]}</button>`).join('')}</div>
381
+ <label class="switch" title="Use this question"><input type="checkbox" class="en" ${x.on?'checked':''}><span></span></label>
382
+ <button class="x" title="Remove">✕</button></div>
383
+ <input class="inp qq" placeholder="Ask something about the state…" value="${esc(x.q)}">
384
+ <div class="${x.type==='noul'?'hide':''}"><textarea class="inp mono oo" rows="3" placeholder="${esc(PH[x.type]||'')}" style="margin-top:8px">${esc(x.opts)}</textarea><div class="hint">${esc(HINT[x.type])}</div></div></div>`).join('');
385
+ $('#addq').disabled=Q.length>=MAXQ;
386
+ }
387
+ $('#qs').addEventListener('input',e=>{const c=e.target.closest('.qcard'); if(!c) return; const x=Q[+c.dataset.i];
388
+ if(e.target.classList.contains('qq')) x.q=e.target.value; else if(e.target.classList.contains('oo')) x.opts=e.target.value;
389
+ else if(e.target.classList.contains('en')){x.on=e.target.checked;c.classList.toggle('off',!x.on);}});
390
+ $('#qs').addEventListener('click',e=>{const c=e.target.closest('.qcard'); if(!c) return; const i=+c.dataset.i;
391
+ const b=e.target.closest('.seg button'); if(b){Q[i].type=b.dataset.t;renderQs();return;}
392
+ if(e.target.closest('.x')){Q.splice(i,1);if(!Q.length)Q.push({on:true,type:'noul',q:'',opts:''});renderQs();}});
393
+ $('#addq').onclick=()=>{if(Q.length<MAXQ){Q.push({on:true,type:'noul',q:'',opts:''});renderQs();}};
394
+ function loadPreset(i,run){
395
+ const p=PRESETS[i]; $('#state').value=p.state; Q=p.qs.map(x=>({on:true,...x})); renderQs();
396
+ $$('#presets .chip').forEach((c,j)=>c.classList.toggle('on',j===i)); if(run) analyze();
397
+ }
398
+ $('#presets').innerHTML=PRESETS.map((p,i)=>`<button class="chip" data-i="${i}">${esc(p.name)}</button>`).join('');
399
+ $('#presets').addEventListener('click',e=>{const b=e.target.closest('.chip'); if(b) loadPreset(+b.dataset.i,true);});
400
+
401
+ async function analyze(){
402
+ const state=$('#state').value, out=$('#out'), btn=$('#go');
403
+ if(!state.trim()){out.innerHTML=errBox('Enter a state: some text or JSON for the model to read.');return;}
404
+ const qs={}, info={}, prompts=[];
405
+ try{
406
+ Q.forEach((x,i)=>{ if(!x.on||!x.q.trim()) return; let m; try{m=makeSpec(x.type,x.q,x.opts);}catch(err){throw new Error(`Question ${i+1}: ${err.message}`);}
407
+ qs['q'+(i+1)]=m.spec; info['q'+(i+1)]=x.q.trim(); prompts.push(`# ---- question ${i+1} ----\n`+buildPrompt(state,m.text,m.base,x.type)); });
408
+ if(!Object.keys(qs).length) throw new Error('Switch on at least one question and fill in its text.');
409
+ }catch(err){out.innerHTML=errBox(err.message);return;}
410
+ busy(btn,true); out.innerHTML=skeleton(Object.keys(qs).length); const t0=performance.now();
411
+ try{
412
+ const p=await decide(state,qs,$('#debias').checked), dt=(performance.now()-t0)/1000;
413
+ const keys=Object.keys(qs); out.innerHTML=sumline(dt,p.device,keys.length)+keys.map((k,i)=>card(info[k],p.result[k],prevPlay[info[k]],'',null,i)).join('');
414
+ const np={}; keys.forEach(k=>np[info[k]]=snap(p.result[k])); prevPlay=np;
415
+ $('#prompts').textContent=prompts.join('\n\n'); $('#raw').textContent=J(p.result,null,2); $('#pdet').classList.remove('hide'); $('#rdet').classList.remove('hide');
416
+ }catch(err){out.innerHTML=errBox(err.message);}
417
+ busy(btn,false);
418
+ }
419
+ $('#go').onclick=analyze;
420
+ document.addEventListener('keydown',e=>{if((e.ctrlKey||e.metaKey)&&e.key==='Enter'){ ($('#view-port').classList.contains('hide')?analyze:analyzePortfolio)(); }});
421
+
422
+ /* ---------- portfolio lab ---------- */
423
+ const UNIV={AAPL:'Technology',MSFT:'Technology',NVDA:'Technology',GOOGL:'Communication',META:'Communication',AMZN:'Consumer Discretionary',TSLA:'Consumer Discretionary',JPM:'Financials',BAC:'Financials',V:'Financials',JNJ:'Health Care',PFE:'Health Care',LLY:'Health Care',XOM:'Energy',CVX:'Energy',KO:'Consumer Staples',PG:'Consumer Staples',WMT:'Consumer Staples',CAT:'Industrials',BA:'Industrials',NEE:'Utilities',AMT:'Real Estate',LIN:'Materials',TLT:'Bonds',AGG:'Bonds',GLD:'Commodities',SPY:'Broad Market ETF',QQQ:'Broad Market ETF'};
424
+ const VOL={Technology:[22,45],Communication:[20,38],'Consumer Discretionary':[20,50],Financials:[18,35],'Health Care':[14,30],Energy:[22,40],'Consumer Staples':[10,20],Industrials:[16,32],Utilities:[12,22],'Real Estate':[16,30],Materials:[18,36],Bonds:[5,15],Commodities:[12,22],'Broad Market ETF':[13,24]};
425
+ let PF=[['NVDA','Technology',38,30,40],['AAPL','Technology',22,25,28],['JPM','Financials',15,15,24],['XOM','Energy',10,12,28],['AGG','Bonds',15,18,6]], prevPf={};
426
+ const PFQ=[
427
+ {type:'noul',q:'Is any single holding larger than 30% of the portfolio (weight_pct)?'},
428
+ {type:'noul',q:'Does any single sector account for more than 50% of total portfolio weight?'},
429
+ {type:'noul',q:'Has any holding drifted more than 5 percentage points away from its target_pct?'},
430
+ {type:'score',q:'Rate the portfolio risk using the weight-averaged annual_vol_pct (low: below 12, medium: 12-20, high: 20-30, very high: above 30).',levels:['low','medium','high','very high']},
431
+ {type:'choice',q:'How diversified is this portfolio by the Herfindahl index, i.e. sum of squared weights (below 0.15 well diversified, 0.15-0.30 moderately concentrated, above 0.30 highly concentrated)?',criteria:{'well diversified':'HHI below 0.15','moderately concentrated':'HHI 0.15 to 0.30','highly concentrated':'HHI above 0.30'}}];
432
+ function renderPF(){
433
+ $('#pfrows').innerHTML=PF.map((r,i)=>`<tr data-i="${i}"><td style="width:92px"><input class="inp" data-c="0" value="${esc(r[0])}"></td><td><input class="inp" data-c="1" value="${esc(r[1])}"></td>
434
+ ${[2,3,4].map(c=>`<td style="width:82px"><input class="inp" type="number" step="0.1" data-c="${c}" value="${r[c]}"></td>`).join('')}<td style="width:30px"><button class="x" style="margin:0">✕</button></td></tr>`).join('');
435
+ }
436
+ $('#pfrows').addEventListener('input',e=>{const tr=e.target.closest('tr'); if(!tr) return; const c=+e.target.dataset.c; PF[+tr.dataset.i][c]=c<2?e.target.value:e.target.value===''?NaN:parseFloat(e.target.value);});
437
+ $('#pfrows').addEventListener('click',e=>{const b=e.target.closest('.x'); if(b){PF.splice(+b.closest('tr').dataset.i,1);renderPF();}});
438
+ $('#pfadd').onclick=()=>{PF.push(['','',10,10,20]);renderPF();};
439
+ $('#pfnorm').onclick=()=>{const t=PF.reduce((s,r)=>s+(r[2]||0),0); if(t>0){PF.forEach(r=>r[2]=Math.round(r[2]/t*1000)/10);renderPF();}};
440
+ $('#pfrand').onclick=()=>{
441
+ const keys=Object.keys(UNIV), n=4+Math.floor(Math.random()*6), pick=[]; while(pick.length<n){const k=keys[Math.floor(Math.random()*keys.length)]; if(!pick.includes(k)) pick.push(k);}
442
+ const a=[.7,1.5,4][Math.floor(Math.random()*3)], g=()=>{let s=0;for(let i=0;i<Math.max(1,Math.round(a*3));i++)s+=-Math.log(Math.random()+1e-9);return s/Math.max(1,Math.round(a*3))+1e-3;};
443
+ const w=pick.map(g), t=w.reduce((x,y)=>x+y,0); const gauss=()=>Math.sqrt(-2*Math.log(Math.random()+1e-9))*Math.cos(2*Math.PI*Math.random());
444
+ PF=pick.map((k,i)=>{const wi=Math.round(w[i]/t*1000)/10, [lo,hi]=VOL[UNIV[k]]; return [k,UNIV[k],wi,Math.max(0,Math.round((wi+gauss()*4)*10)/10),Math.round((lo+Math.random()*(hi-lo))*10)/10];});
445
+ renderPF();
446
+ };
447
+ function holdings(){
448
+ const h=[]; for(const r of PF){const tk=String(r[0]).trim(); if(!tk) continue;
449
+ if([2,3,4].some(c=>typeof r[c]!=='number'||isNaN(r[c]))) throw new Error(`Row ${tk}: weight, target and vol must be numbers.`);
450
+ h.push({ticker:tk,sector:String(r[1]).trim()||'Unknown',weight_pct:Math.round(r[2]*10)/10,target_pct:Math.round(Math.max(r[3],0)*10)/10,annual_vol_pct:Math.round(r[4]*10)/10});}
451
+ if(!h.length) throw new Error('Add at least one holding.'); return h;
452
+ }
453
+ function exactPF(h){
454
+ const W=h.map(x=>x.weight_pct), tw=W.reduce((a,b)=>a+b,0)||1, sec={}; h.forEach(x=>sec[x.sector]=(sec[x.sector]||0)+x.weight_pct);
455
+ const wavol=h.reduce((s,x)=>s+x.weight_pct*x.annual_vol_pct,0)/tw, hhi=W.reduce((s,w)=>s+(w/tw)**2,0);
456
+ const ts=Object.keys(sec).reduce((a,b)=>sec[a]>=sec[b]?a:b), drift=Math.max(...h.map(x=>Math.abs(x.weight_pct-x.target_pct))), big=h.reduce((a,b)=>a.weight_pct>=b.weight_pct?a:b);
457
+ return [[Math.max(...W)>30?'Yes':'No',`largest holding: ${big.ticker} at ${big.weight_pct}%`],[sec[ts]>50?'Yes':'No',`largest sector: ${ts} at ${sec[ts].toFixed(1)}%`],
458
+ [drift>5?'Yes':'No',`max drift: ${drift.toFixed(1)} percentage points`],[wavol<12?'low':wavol<20?'medium':wavol<30?'high':'very high',`weighted volatility: ${wavol.toFixed(1)}%`],
459
+ [hhi<.15?'well diversified':hhi<.30?'moderately concentrated':'highly concentrated',`HHI: ${hhi.toFixed(3)}`]];
460
+ }
461
+ const PAL=['#6366f1','#14b8a6','#f59e0b','#ec4899','#0ea5e9','#84cc16','#a855f7','#f97316','#64748b','#22c55e'];
462
+ function chart(h){
463
+ const secs=[...new Set(h.map(x=>x.sector))].sort(), col=Object.fromEntries(secs.map((s,i)=>[s,PAL[i%PAL.length]])), sc=Math.max(...h.map(x=>Math.max(x.weight_pct,x.target_pct)))||1;
464
+ return `<div class="rcard"><div class="rhead"><span class="rq">Holdings: bar = weight, black marker = target</span></div>`+h.map(x=>`<div class="hold"><b>${esc(x.ticker)}</b><div class="ht"><div class="hf" style="width:${x.weight_pct/sc*100}%;background:${col[x.sector]}"></div><div class="tg" style="left:${x.target_pct/sc*100}%"></div></div><span class="v">${x.weight_pct}% <span style="opacity:.7">(target ${x.target_pct}%)</span></span></div>`).join('')+`<div style="margin-top:8px">${secs.map(s=>`<span class="mini"><span style="color:${col[s]}">●</span> ${esc(s)}</span>`).join('')}</div></div>`;
465
+ }
466
+ async function analyzePortfolio(){
467
+ const out=$('#pfout'), btn=$('#pfgo'); let h; try{h=holdings();}catch(err){out.innerHTML=errBox(err.message);return;}
468
+ const tw=h.reduce((s,x)=>s+x.weight_pct,0), warn=[]; if(Math.abs(tw-100)>1) warn.push(`weights sum to ${tw.toFixed(1)}% (the model saw portfolios summing to about 100%)`); if(h.length<3||h.length>12) warn.push(`${h.length} holdings (training used 3 to 12)`);
469
+ const qs={}; PFQ.forEach((x,i)=>{const s={type:x.type,instructions:x.q}; if(x.levels) s.levels=x.levels; if(x.criteria) s.criteria=x.criteria; qs['q'+i]=s;});
470
+ busy(btn,true); out.innerHTML=skeleton(4); const t0=performance.now();
471
+ try{
472
+ const p=await decide(J({portfolio:h}),qs,true), dt=(performance.now()-t0)/1000, truth=exactPF(h), np={};
473
+ const cards=PFQ.map((x,i)=>{const r=p.result['q'+i]; const ans=x.type==='noul'?(r.noul>=.5?'Yes':'No'):x.type==='choice'?r.choice:r.level;
474
+ const short=x.q.split(' (')[0].split(', i.e.')[0]; np[short]=snap(r); return card(short,r,prevPf[short],truth[i][1],[truth[i][0],ans===truth[i][0]],i);}).join('');
475
+ prevPf=np; out.innerHTML=sumline(dt,p.device,PFQ.length)+(warn.length?`<div class="rcard"><span class="mini warn">heads-up</span> ${esc(warn.join('; '))}. Answers may be less reliable.</div>`:'')+chart(h)+cards;
476
+ }catch(err){out.innerHTML=errBox(err.message);}
477
+ busy(btn,false);
478
+ }
479
+ $('#pfgo').onclick=analyzePortfolio;
480
+
481
+ /* ---------- tabs, theme, status, metrics ---------- */
482
+ $('#tabs').addEventListener('click',e=>{const b=e.target.closest('.tab'); if(!b) return;
483
+ $$('.tab').forEach(t=>t.classList.toggle('on',t===b)); ['play','port','about'].forEach(v=>$('#view-'+v).classList.toggle('hide',v!==b.dataset.tab)); if(b.dataset.tab==='about') loadMetrics();});
484
+ const root=document.documentElement;
485
+ function setTheme(t){root.dataset.theme=t; try{localStorage.setItem('jev-theme',t);}catch(e){}}
486
+ let saved=null; try{saved=localStorage.getItem('jev-theme');}catch(e){}
487
+ setTheme(saved||(window.matchMedia&&matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light'));
488
+ $('#theme').onclick=()=>setTheme(root.dataset.theme==='dark'?'light':'dark');
489
+ async function pollStatus(){
490
+ try{const i=await (await fetch('/api/info')).json(); const dot=$('#dot'), tx=$('#stxt');
491
+ if(i.ready){dot.className='dot ok';tx.textContent='Model ready · '+i.device;return;}
492
+ if(i.error){dot.className='dot err';tx.textContent='Model failed to load';tx.title=i.error;return;}
493
+ tx.textContent='Warming up model…';}catch(e){}
494
+ setTimeout(pollStatus,2500);
495
+ }
496
+ let metricsLoaded=false;
497
+ async function loadMetrics(){
498
+ if(metricsLoaded) return; metricsLoaded=true;
499
+ try{const d=await (await fetch('/api/metrics')).json(); if(!d.rows||!d.rows.length) throw 0;
500
+ $('#metrics').innerHTML='<thead><tr><th>slice</th><th>test rows</th><th>accuracy</th><th>ECE raw</th><th>ECE calibrated</th></tr></thead><tbody>'+d.rows.map(r=>`<tr><td>${esc(r.slice)}</td><td>${r.n}</td><td><span class="abar" style="width:${Math.round(r.acc*60)}px"></span>${(r.acc*100).toFixed(1)}%</td><td>${r.ece_raw.toFixed(3)}</td><td>${r.ece_cal.toFixed(3)}</td></tr>`).join('')+'</tbody>';
501
+ }catch(e){metricsLoaded=false;$('#metrics').innerHTML='<tbody><tr><td>metrics.json is not available (private repo without HF_TOKEN?)</td></tr></tbody>';}
502
+ }
503
+ renderPF(); loadPreset(0,false); pollStatus();
504
+ </script>
505
+ </body>
506
+ </html>