HERCULEAN / play.js
Xueqing's picture
HERCULEAN leaderboard site (from xueqingpeng/herculean docs/ @ 76f5121)
c58bef8 verified
Raw History Blame Contribute Delete
31.3 kB
/* HERCULEAN · Trade with an agent.
Each day the player picks an agent system (architecture × backbone); one of its three recorded runs is drawn
(only among runs that committed that day; HOLD if none did) and its real Trading decision is executed.
Scoring follows analysis/score_runs.py: BUY/SELL/HOLD -> +1/-1/0, held from the open of the day to the next
open (last day: open to close), adjusted prices, no costs. SR = sqrt(252)·mean/std of daily returns. */
(() => {
const H = window.HERC, OH = H.ohlc, HIST = OH.start, N = H.dates.length, $ = id => document.getElementById(id);
const AC = { ReAct: '#2a78d6', 'Claude Code': '#eb6834', Codex: '#1baf7a', Hermes: '#eda100', OpenClaw: '#e87ba4' };
const INI = { ReAct: 'RA', 'Claude Code': 'CC', Codex: 'CX', Hermes: 'HM', OpenClaw: 'OC' };
const MS = { 'Claude Sonnet 5': 'Sonnet 5', 'DeepSeek-V3.2': 'DS-V3.2', 'DeepSeek-V4-Pro': 'DS-V4-Pro', 'Qwen3.5-9B': 'Qwen-9B', 'Qwen3.5-4B': 'Qwen-4B' };
const CO = { MSFT: 'Microsoft', TSLA: 'Tesla', AAPL: 'Apple', NVDA: 'NVIDIA' };
const NAMES = ['Perseus', 'Theseus', 'Atalanta', 'Achilles', 'Odysseus', 'Penelope', 'Jason', 'Medea', 'Orpheus', 'Eurydice',
'Andromeda', 'Cassandra', 'Hector', 'Ajax', 'Electra', 'Antigone', 'Ariadne', 'Bellerophon', 'Castor', 'Pollux', 'Daedalus',
'Icarus', 'Hippolyta', 'Iphigenia', 'Nestor', 'Telemachus', 'Pandora', 'Psyche', 'Calypso', 'Circe', 'Paris', 'Helen'];
const ACT = { B: 'BUY', S: 'SELL', H: 'HOLD' }, POS = { B: 1, S: -1, H: 0 };
const short = m => MS[m] || m, sysName = (a, m) => `${a} · ${short(m)}`;
const pct = (v, d = 2) => (v >= 0 ? '+' : '−') + Math.abs(v * 100).toFixed(d) + '%';
const money = v => '$' + Math.round(v).toLocaleString('en-US');
const cls = v => v > 0 ? 'up' : v < 0 ? 'dn' : '';
const pickRand = a => a[Math.floor(Math.random() * a.length)];
let S; // game state
let arch = 'Hermes', model = 'DeepSeek-V4-Pro', name = pickRand(NAMES), sym = 'MSFT', autoT = null, hover = null;
// per-day returns on the chosen stock (open -> next open; last day open -> close)
const returns = tk => H.dates.map((_, d) => { const b = OH.bars[tk][HIST + d], nx = OH.bars[tk][HIST + d + 1]; return (nx ? nx[0] : b[3]) / b[0] - 1; });
const metrics = (rets) => {
let w = 1, peak = 1, mdd = 0; for (const r of rets) { w *= 1 + r; peak = Math.max(peak, w); mdd = Math.max(mdd, 1 - w / peak); }
const n = rets.length, mu = n ? rets.reduce((p, q) => p + q, 0) / n : 0;
const sd = n > 1 ? Math.sqrt(rets.reduce((p, q) => p + (q - mu) ** 2, 0) / (n - 1)) : 0;
return { cr: w - 1, sr: sd > 0 ? Math.sqrt(252) * mu / sd : 0, mdd };
};
// the 30 systems on this stock: mean wealth over their three runs after each day (missing decision = flat)
function field(tk, ret) {
return H.agents.flatMap(a => H.models.map(m => {
const runs = (H.runs.trading[`${a}|${m}|${tk}`] || []).filter(Boolean), w = new Array(N + 1).fill(0);
runs.forEach(r => { let x = 1; w[0] += 1; for (let d = 0; d < N; d++) { x *= 1 + (POS[r[d]] || 0) * ret[d]; w[d + 1] += x; } });
return { a, m, w: w.map(v => v / (runs.length || 1)) };
}));
}
// where the player stands after day d (CR, ties go to the player)
function standing(d) {
const you = S.eq[d] - 1, all = S.field.map(f => ({ a: f.a, m: f.m, cr: f.w[d] - 1 })).sort((p, q) => q.cr - p.cr);
const rank = 1 + all.filter(f => f.cr > you + 1e-12).length;
return { you, all, rank, n: all.length + 1, top: all[0], bh: S.bh[d] - 1 };
}
// the field on one CR axis, one lane per architecture (dots = backbones); you = the purple line and dot
function strip(st, W, Hs) {
const xs = [...st.all.map(f => f.cr), st.you, st.bh, 0], lo = Math.min(...xs), hi = Math.max(...xs), span = hi - lo || .01, pl = 26, pr = 10;
const X = v => pl + (v - lo) / span * (W - pl - pr), top = 16, axY = Hs - 14, lh = (axY - top - 2) / H.agents.length;
const LY = a => top + (H.agents.indexOf(a) + .5) * lh, r = Math.max(2.8, Math.min(4.6, lh * .36));
let g = '';
H.agents.forEach((a, i) => g += `<line x1="${pl}" x2="${W - pr}" y1="${LY(a)}" y2="${LY(a)}" stroke="rgba(74,38,130,${i % 2 ? .05 : .09})"/>` +
`<text x="${pl - 6}" y="${LY(a) + 3}" text-anchor="end" class="sx" style="fill:${AC[a]};font-weight:600">${INI[a]}</text>`);
g += `<line x1="${pl}" x2="${W - pr}" y1="${axY}" y2="${axY}" stroke="rgba(74,38,130,.18)"/>`;
const lab = [[lo, pct(lo, 1), 'start'], [hi, pct(hi, 1), 'end'], [0, '0%', 'middle'], [st.bh, 'B&H', 'middle']], used = [];
lab.reverse().forEach(([v, t, an]) => { const x = X(v); if (used.some(u => Math.abs(u - x) < 30)) return; used.push(x);
g += `<text x="${x}" y="${Hs - 2}" text-anchor="${an}" class="sx"${t === 'B&H' ? ' style="fill:#4f5a6e"' : ''}>${t}</text>`; });
g += `<line x1="${X(0)}" x2="${X(0)}" y1="${top}" y2="${axY}" stroke="rgba(74,38,130,.14)"/>`;
g += `<line x1="${X(st.bh)}" x2="${X(st.bh)}" y1="${top}" y2="${axY + 2}" stroke="#8a93a3" stroke-dasharray="2 2"/>`;
st.all.forEach(f => g += `<circle cx="${X(f.cr)}" cy="${LY(f.a)}" r="${r}" fill="${AC[f.a]}" opacity=".7"><title>${sysName(f.a, f.m)} · ${pct(f.cr)}</title></circle>`);
const t = st.top;
g += `<circle cx="${X(t.cr)}" cy="${LY(t.a)}" r="${r + 2}" fill="none" stroke="${AC[t.a]}" stroke-width="1.2"/><text x="${Math.min(X(t.cr), W - pr)}" y="${top - 5}" text-anchor="end" class="sx">#1</text>`;
const yx = X(st.you);
g += `<line x1="${yx}" x2="${yx}" y1="${top - 2}" y2="${axY}" stroke="#7800f0" stroke-width="1.6"/><circle cx="${yx}" cy="${top - 2}" r="4" fill="#7800f0" stroke="#fff" stroke-width="1.5"><title>you · ${pct(st.you)}</title></circle>` +
`<text x="${yx + (yx > W - 40 ? -8 : 8)}" y="${top + 1}" text-anchor="${yx > W - 40 ? 'end' : 'start'}" class="sx you">you</text>`;
return `<svg viewBox="0 0 ${W} ${Hs}" width="100%" height="${Hs}" style="overflow:visible">${g}</svg>`;
}
// ranking rows: top 3, then the player's neighbourhood (`around` rows either side)
function rankTable(st, around, compact) {
const rank = st.rank, rows = st.all.map((f, i) => ({ ...f, r: i + 1 + (i + 1 >= rank ? 1 : 0) }));
rows.splice(rank - 1, 0, { you: true, cr: st.you, r: rank });
const keep = new Set([0, 1, 2]); for (let k = -around; k <= around; k++) keep.add(rank - 1 + k);
let tb = '', prev = -1;
rows.forEach((f, i) => { if (!keep.has(i)) return; if (prev >= 0 && i > prev + 1) tb += '<div class="tr gapr">⋯</div>'; prev = i;
tb += `<div class="tr${f.you ? ' me' : ''}"><span class="rk">#${f.r}</span><span class="nm2">${f.you ? `${name} <small>your picks</small>` : `<span class="ini" style="background:${AC[f.a]}${f.a === 'ReAct' ? ';color:#fff' : ''}">${INI[f.a]}</span>${sysName(f.a, f.m)}`}</span>` +
`<span class="${cls(f.cr)}">${pct(f.cr)}</span>${compact ? '' : `<span class="muted">${i === 0 ? '—' : ((f.cr - rows[0].cr) * 100).toFixed(2) + ' pp'}</span>`}</div>`; });
return tb;
}
function newGame(tk) {
sym = tk; stopAuto();
S = { d: 0, ret: returns(tk), log: [], eq: [1], bh: [1], picks: {} }; S.field = field(tk, S.ret);
$('trader').textContent = name; $('ava').textContent = name[0];
$('rev').innerHTML = '<span class="muted">Pick an architecture and a backbone, then trade. One of its 3 runs is drawn at random.</span>';
renderAll();
}
// ---------- one trading day ----------
function step() {
if (!S || S.d >= N) return;
const d = S.d, runs = H.runs.trading[`${arch}|${model}|${sym}`] || ['', '', ''];
const ok = [0, 1, 2].filter(r => runs[r] && runs[r][d] && runs[r][d] !== '-');
const r = ok.length ? pickRand(ok) : Math.floor(Math.random() * 3);
const a = ok.length ? runs[r][d] : 'H', miss = !ok.length;
const pnl = POS[a] * S.ret[d];
S.eq.push(S.eq[d] * (1 + pnl)); S.bh.push(S.bh[d] * (1 + S.ret[d]));
S.log.push({ d, a, arch, model, run: r + 1, pnl, miss });
const k = `${arch}|${model}`; S.picks[k] = (S.picks[k] || 0) + 1;
S.d++;
// the three recorded runs of this system on this day; the drawn one is outlined
const calls = [0, 1, 2].map(i => { const c = runs[i] && runs[i][d]; return !c || c === '-' ? null : c; });
$('rev').innerHTML = `<div class="rv1"><b>${sysName(arch, model)}</b><span class="rv-pnl ${cls(pnl)}">${miss ? 'HOLD · no commit' : pct(pnl)}</span></div>` +
`<div class="rv2"><span class="muted">${H.dates[d].slice(5)} · its 3 runs</span>${calls.map((c, i) => `<span class="rv-run${i === r ? ' drawn' : ''}"><i>r${i + 1}</i>${c ? `<span class="act ${c}">${ACT[c]}</span>` : '<span class="act na">—</span>'}</span>`).join('')}</div>`;
const rv = $('rev'); rv.classList.remove('flash'); void rv.offsetWidth; rv.classList.add('flash');
renderAll(true);
if (S.d >= N) { stopAuto(); setTimeout(endCard, 700); }
}
function stopAuto() { clearInterval(autoT); autoT = null; $('autoBtn').classList.remove('on'); $('autoBtn').textContent = 'Auto ▸▸'; }
// ---------- render ----------
function renderAll(fresh) { renderSide(fresh); draw(fresh); }
function renderSide(fresh) {
const done = S.d >= N, eq = S.eq[S.d], bh = S.bh[S.d], m = metrics(S.log.map(l => l.pnl));
$('dayK').textContent = done ? 'window closed' : `Day ${S.d + 1} · ${H.dates[S.d].slice(5)}`;
$('eqv').textContent = money(1e5 * eq);
$('eqr').innerHTML = `<span class="${cls(eq - 1)}">${pct(eq - 1)}</span> <span class="vs">vs</span> <span class="${cls(bh - 1)}">${pct(bh - 1)}</span>`;
const last = S.log[S.log.length - 1];
const pos = !last ? 'Flat' : { B: 'Long', S: 'Short', H: 'Flat' }[last.a];
$('kv').innerHTML = [['Position', pos], ['Max DD', (m.mdd * 100).toFixed(2) + '%'], ['Sharpe', S.log.length > 1 ? m.sr.toFixed(2) : '—']]
.map(([k, v]) => `<div><small>${k}</small><b>${v}</b></div>`).join('');
// P&L attribution: each picked system's days, win days and summed daily P&L (pp)
const by = {};
S.log.forEach(l => { const k = `${l.arch}|${l.model}`, b = by[k] || (by[k] = { a: l.arch, m: l.model, days: 0, win: 0, pnl: 0 }); b.days++; b.pnl += l.pnl; if (l.pnl > 0) b.win++; });
const ag = Object.values(by).sort((p, q) => q.pnl - p.pnl), amax = Math.max(.002, ...ag.map(b => Math.abs(b.pnl)));
$('attr').innerHTML = `<div class="kick"><span>P&amp;L attribution</span><span>by agent system</span></div>` + (ag.length
? `<div class="at-h"><span>agent system</span><span>days · won</span><span>P&amp;L</span></div><div class="at-body">` + ag.map(b => `<div class="at-r" title="${b.a} · ${b.m}: ${b.days} days, ${b.win} winning, sum of daily P&L ${pct(b.pnl)}">` +
`<span class="at-n"><span class="ini" style="background:${AC[b.a]}${b.a === 'ReAct' ? ';color:#fff' : ''}">${INI[b.a]}</span>${short(b.m)}</span>` +
`<span class="at-d">${b.days} · ${b.win}</span>` +
`<span class="at-bar"><i class="${b.pnl >= 0 ? 'p' : 'n'}" style="width:${Math.abs(b.pnl) / amax * 50}%"></i></span>` +
`<span class="at-v ${cls(b.pnl)}">${pct(b.pnl)}</span></div>`).join('') + '</div>'
: '<p class="st-line muted" style="margin-top:8px;white-space:normal">Which of your picks made or lost money will show here.</p>');
const st = standing(S.d), gap = (st.you - st.top.cr) * 100;
$('stand').innerHTML = `<div class="kick"><span>Standing · ${sym} CR</span><span>mean of 3 runs</span></div>` +
`<div class="st-row"><span class="st-rank">${S.d ? `#${st.rank}<small> / ${st.n}</small>` : '<small>—</small>'}</span>` +
(S.d ? `<span class="st-gap ${st.rank === 1 ? 'up' : 'dn'}">${st.rank === 1 ? '+' + ((st.you - st.all[0].cr) * 100).toFixed(2) + ' pp ahead' : '−' + Math.abs(gap).toFixed(2) + ' pp to #1'}</span>` : '') + '</div>' +
(S.d ? '<div class="st-plot" id="stPlot"></div>' +
`<div class="tb full" id="stList"><div class="tr th"><span>#</span><span>agent system</span><span>CR</span></div>${rankTable(st, 99, true)}</div>`
: `<p class="st-line muted" style="margin-top:10px;white-space:normal">Trade to enter the ranking of the 30 agent systems (CR, mean of 3 runs, up to the same day).</p>`);
const me = document.querySelector('#stList .tr.me'), li = $('stList');
// centre the player's row in the list (positions measured relative to the list itself)
if (me && li) li.scrollTop = Math.max(0, me.getBoundingClientRect().top - li.getBoundingClientRect().top + li.scrollTop - (li.clientHeight - me.offsetHeight) / 2);
lastSt = S.d ? st : null; plotStand(); requestAnimationFrame(plotStand);
$('arch').innerHTML = H.agents.map(a => `<button data-a="${a}" class="${a === arch ? 'sel' : ''}"><span class="ini" style="background:${AC[a]}${a === 'ReAct' ? ';color:#fff' : ''}">${INI[a]}</span>${a}</button>`).join('');
$('model').innerHTML = H.models.map(x => `<button data-m="${x}" class="${x === model ? 'sel' : ''}" title="${x}">${short(x)}</button>`).join('');
$('goBtn').disabled = done; $('autoBtn').disabled = done;
$('log').innerHTML = H.dates.map((dt, d) => {
const l = S.log[d];
if (!l) return `<div class="tile fut${d === S.d ? ' now' : ''}" data-d="${d}"><div class="t1"><span>${dt.slice(5)}</span><span>D${d + 1}</span></div><div class="t2"><span>${d === S.d ? 'today' : ''}</span><span></span></div><div class="t3">·</div></div>`;
return `<div class="tile${fresh && d === S.d - 1 ? ' new' : ''}" data-d="${d}" title="${l.arch} · ${l.model} · run ${l.run}${l.miss ? ' · no commit, scored as HOLD' : ''}"><div class="t1"><span>${dt.slice(5)}</span><span>D${d + 1}</span></div>` +
`<div class="t2"><span class="act ${l.a}">${ACT[l.a]}</span><span class="${cls(l.pnl)}">${pct(l.pnl)}</span></div><div class="t3">${INI[l.arch]} · ${short(l.model)} · r${l.run}${l.miss ? ' · –' : ''}</div></div>`;
}).join('');
const tl = $('log'), cur = tl.children[Math.min(S.d, N - 1)];
if (cur) tl.scrollTo({ left: Math.max(0, cur.offsetLeft - tl.clientWidth + cur.offsetWidth * 2.5), behavior: 'auto' });
}
function head(i) {
const b = OH.bars[sym], cur = b[i], prev = b[i - 1], chg = cur[3] / prev[3] - 1, d = Math.min(S.d, N), done = S.d >= N;
const dt = new Date((done ? H.dates[N - 1] : H.dates[S.d]) + 'T12:00:00Z').toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric', timeZone: 'UTC' });
$('head').innerHTML = `<span class="sym">${sym}</span><span class="co">${CO[sym]}</span><span class="px">${cur[3].toFixed(2)}</span><span class="chg ${cls(chg)}">${pct(chg)}</span>` +
`<span class="ohlc">${OH.dates[i]} · O <b>${cur[0].toFixed(2)}</b> H <b>${cur[1].toFixed(2)}</b> L <b>${cur[2].toFixed(2)}</b> C <b>${cur[3].toFixed(2)}</b> · Vol <b>${cur[4].toFixed(1)}M</b></span>` +
''; void dt; void d; void done;
}
// the standing plot takes whatever height the card has left; redraw when that changes (fonts, resize)
let lastSt = null;
function plotStand() {
const sp = $('stPlot'); if (!sp || !lastSt) return;
sp.innerHTML = ''; sp.innerHTML = strip(lastSt, sp.clientWidth || 328, Math.max(48, Math.min(170, sp.clientHeight)));
}
if (window.ResizeObserver) new ResizeObserver(() => plotStand()).observe($('stand'));
if (document.fonts) { document.fonts.ready.then(() => { plotStand(); S && draw(); }); document.fonts.addEventListener('loadingdone', () => { plotStand(); S && draw(); }); }
let G = null; // geometry for hover
function draw(fresh) {
const svg = $('kline'), W = svg.clientWidth, Hh = svg.clientHeight; if (!W || !Hh) return;
svg.setAttribute('viewBox', `0 0 ${W} ${Hh}`);
const bars = OH.bars[sym], total = HIST + N, L = 6, R = 58, cw = (W - L - R) / total, X = i => L + (i + .5) * cw;
const nShown = HIST + S.d, shown = bars.slice(0, nShown);
const pTop = 20, pH = Hh * .5, aTop = pTop + pH + 10, aH = 13, vTop = aTop + aH + 8, vH = Hh * .08, eTop = vTop + vH + 22, eH = Hh - eTop - 46, tY = Hh - 16;
// price scale from what has been revealed only (no peeking at the future)
let lo = Math.min(...shown.map(b => b[2])), hi = Math.max(...shown.map(b => b[1])); const pad = (hi - lo) * .12;
lo -= pad; hi += pad;
const Y = v => pTop + (1 - (v - lo) / (hi - lo)) * pH, vmax = Math.max(...shown.map(b => b[4]));
let g = '';
for (let t = 0; t <= 4; t++) { const v = lo + t / 4 * (hi - lo); g += `<line class="gl" x1="${L}" x2="${W - R}" y1="${Y(v)}" y2="${Y(v)}"/><text class="ax" x="${W - R + 6}" y="${Y(v) + 3}">${v.toFixed(0)}</text>`; }
const x0 = X(HIST) - cw / 2, xn = X(nShown) - cw / 2;
g += `<rect x="${x0}" y="${pTop}" width="${Math.max(0, xn - x0)}" height="${eTop + eH - pTop}" fill="rgba(120,0,240,.028)"/>`;
if (S.d < N) g += `<rect x="${xn}" y="${pTop}" width="${W - R - xn}" height="${eTop + eH - pTop}" fill="url(#fut)"/>`;
g += `<text class="ax" x="${x0 + 3}" y="${pTop + 10}" fill="#7a1fb4">Jan 2 · window opens</text>`;
// legends inside the panels
g += `<g class="lg"><line x1="${L + 2}" x2="${L + 16}" y1="${pTop - 9}" y2="${pTop - 9}" stroke="#eda100" stroke-width="1.6"/><text x="${L + 20}" y="${pTop - 6}">MA5</text>` +
`<line x1="${L + 52}" x2="${L + 66}" y1="${pTop - 9}" y2="${pTop - 9}" stroke="#7800f0" stroke-width="1.6"/><text x="${L + 70}" y="${pTop - 6}">MA20</text>` +
`<path d="M${L + 110},${pTop - 6} l4,-7 l4,7z" fill="#0f9d58"/><text x="${L + 122}" y="${pTop - 6}">agent BUY</text><path d="M${L + 180},${pTop - 13} l4,7 l4,-7z" fill="#d6304a"/><text x="${L + 192}" y="${pTop - 6}">agent SELL</text></g>`;
// daily decision strip (as in the Trading replay): one cell per window day
g += `<text class="ax" x="${x0 - 6}" y="${aTop + 10}" text-anchor="end">ACTION</text>`;
const AF = { B: '#0f9d58', S: '#d6304a', H: '#d9d7e3' };
for (let d = 0; d < N; d++) {
const l = S.log[d], cx0 = X(HIST + d) - cw / 2 + .6, cwi = Math.max(1, cw - 1.2);
if (l) g += `<rect${fresh && d === S.d - 1 ? ' class="cnew"' : ''} x="${cx0}" y="${aTop}" width="${cwi}" height="${aH}" rx="1.5" fill="${l.miss ? 'url(#miss)' : AF[l.a]}"/>`;
else g += `<rect x="${cx0}" y="${aTop}" width="${cwi}" height="${aH}" rx="1.5" fill="#fff" stroke="${d === S.d ? '#7800f0' : 'rgba(74,38,130,.14)'}" stroke-width="${d === S.d ? 1.4 : .8}"/>`;
}
// moving averages
[[5, '#eda100'], [20, '#7800f0']].forEach(([n, c]) => {
let p = ''; for (let i = n - 1; i < nShown; i++) { const v = bars.slice(i - n + 1, i + 1).reduce((s, b) => s + b[3], 0) / n; p += (p ? 'L' : 'M') + X(i).toFixed(1) + ',' + Y(v).toFixed(1); }
g += `<path d="${p}" fill="none" stroke="${c}" stroke-width="1.2" opacity=".75"/>`;
});
// candles + volume
const w = Math.max(1.5, cw * .62);
shown.forEach((b, i) => {
const [o, h, l, c, v] = b, up = c >= o, col = up ? '#0f9d58' : '#d6304a', nw = fresh && i === nShown - 1 ? ' class="cnew"' : '';
g += `<g${nw}><line x1="${X(i)}" x2="${X(i)}" y1="${Y(h)}" y2="${Y(l)}" stroke="${col}"/><rect x="${X(i) - w / 2}" y="${Y(Math.max(o, c))}" width="${w}" height="${Math.max(1, Math.abs(Y(o) - Y(c)))}" fill="${up ? '#fff' : col}" stroke="${col}"/></g>`;
g += `<rect${nw} x="${X(i) - w / 2}" y="${vTop + vH - v / vmax * vH}" width="${w}" height="${v / vmax * vH}" fill="${col}" opacity=".35"/>`;
});
// the agents' calls
S.log.forEach((l, k) => {
const i = HIST + l.d, b = bars[i], nw = fresh && k === S.log.length - 1 ? ' class="mk"' : '';
if (l.a === 'B') g += `<path${nw} d="M${X(i)},${Y(b[2]) + 5} l4,7 h-8z" fill="#0f9d58"/>`;
if (l.a === 'S') g += `<path${nw} d="M${X(i)},${Y(b[1]) - 5} l4,-7 h-8z" fill="#d6304a"/>`;
});
const lastC = shown[nShown - 1][3], lastUp = lastC >= shown[nShown - 2][3];
g += `<rect x="${W - R + 2}" y="${Y(lastC) - 8}" width="${R - 4}" height="16" rx="4" fill="${lastUp ? '#0f9d58' : '#d6304a'}"/><text x="${W - R + 6}" y="${Y(lastC) + 4}" style="font:600 10px 'JetBrains Mono',monospace" fill="#fff">${lastC.toFixed(2)}</text>`;
// equity panel
const all = [...S.eq, ...S.bh], emin = Math.min(...all), emax = Math.max(...all), ep = Math.max((emax - emin) * .15, .01);
const EY = v => eTop + (1 - (v - emin + ep) / (emax - emin + 2 * ep)) * eH;
const ex = k => k === 0 ? x0 : X(HIST + k - 1) + cw / 2; // equity after day k sits at the right edge of that day
g += `<text class="ax" x="${L}" y="${eTop - 6}">EQUITY</text><line class="gl" x1="${L}" x2="${W - R}" y1="${EY(1)}" y2="${EY(1)}" stroke-dasharray="2 3"/><text class="ax" x="${W - R + 6}" y="${EY(1) + 3}">$100k</text>`;
const line = arr => arr.map((v, k) => (k ? 'L' : 'M') + ex(k).toFixed(1) + ',' + EY(v).toFixed(1)).join('');
if (S.d) {
g += `<path d="${line(S.eq)} L${ex(S.d)},${EY(1)} L${ex(0)},${EY(1)}Z" fill="rgba(120,0,240,.08)"/>`;
g += `<path d="${line(S.bh)}" fill="none" stroke="#8a93a3" stroke-dasharray="4 3" stroke-width="1.2"/><path d="${line(S.eq)}" fill="none" stroke="#0f1528" stroke-width="1.8"/>`;
g += `<circle cx="${ex(S.d)}" cy="${EY(S.eq[S.d])}" r="4" fill="#0f1528" stroke="#fff" stroke-width="2"/>`;
} else g += `<text class="ax" x="${x0 + 3}" y="${EY(1) - 8}">your equity starts here</text>`;
// time bar under the chart: the 61-day window, filled up to today; the Day tag rides on it
const xEnd = X(HIST + N - 1) + cw / 2, cur = Math.min(S.d, N - 1), tx = S.d >= N ? xEnd : X(HIST + S.d);
if (S.d < N) g += `<line x1="${tx}" x2="${tx}" y1="${pTop}" y2="${tY - 9}" stroke="#7800f0" stroke-opacity=".45" stroke-dasharray="3 3"/>`;
g += `<rect x="${x0}" y="${tY - 3}" width="${xEnd - x0}" height="6" rx="3" fill="#eceef4"/>` +
`<rect x="${x0}" y="${tY - 3}" width="${Math.max(0, (S.d >= N ? xEnd : tx - cw / 2) - x0)}" height="6" rx="3" fill="url(#tlg)"/>`;
[20, 40].forEach(k => g += `<line x1="${X(HIST + k) - cw / 2}" x2="${X(HIST + k) - cw / 2}" y1="${tY - 3}" y2="${tY + 3}" stroke="#fff" stroke-width="1.5"/>`);
g += `<text class="ax" x="${x0 - 8}" y="${tY + 3.5}" text-anchor="end">Jan 2</text><text class="ax" x="${xEnd + 8}" y="${tY + 3.5}">Mar 31</text>`;
// date tag riding on the bar: month and day on top, weekday below
const dd = new Date(H.dates[cur] + 'T12:00:00Z'), fmt = o => dd.toLocaleDateString('en-US', { ...o, timeZone: 'UTC' });
const l1 = S.d >= N ? 'Closed' : fmt({ month: 'short', day: 'numeric' }), l2 = S.d >= N ? 'Mar 31' : fmt({ weekday: 'short' });
const tw = Math.max(l1.length * 6.4, l2.length * 5.4) + 16, tcx = Math.min(Math.max(tx, x0 + tw / 2), xEnd - tw / 2);
g += `<g class="ttag"><rect x="${tcx - tw / 2}" y="${tY - 15}" width="${tw}" height="30" rx="9" fill="#4a1a8c" stroke="#fff" stroke-width="2"/>` +
`<text x="${tcx}" y="${tY - 1.5}" text-anchor="middle" class="t1">${l1}</text><text x="${tcx}" y="${tY + 9.5}" text-anchor="middle" class="t2">${l2}</text></g>`;
g += `<g class="lg"><line x1="${L + 60}" x2="${L + 74}" y1="${eTop - 9}" y2="${eTop - 9}" stroke="#0f1528" stroke-width="1.8"/><text x="${L + 78}" y="${eTop - 6}">your equity</text>` +
`<line x1="${L + 146}" x2="${L + 160}" y1="${eTop - 9}" y2="${eTop - 9}" stroke="#8a93a3" stroke-dasharray="3 2" stroke-width="1.3"/><text x="${L + 164}" y="${eTop - 6}">Buy &amp; Hold</text></g>`;
// date axis
g += `<text class="ax" x="${X(0)}" y="${tY + 3.5}">${new Date(OH.dates[0] + 'T12:00:00Z').toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })}</text>`;
g += `<g id="hv"></g>`;
svg.innerHTML = `<defs><pattern id="fut" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="6" height="6" fill="#fcfcfd"/><line x1="0" y1="0" x2="0" y2="6" stroke="rgba(74,38,130,.035)" stroke-width="2"/></pattern><linearGradient id="tlg" x1="0" x2="1"><stop offset="0" stop-color="#b40028"/><stop offset="1" stop-color="#7800f0"/></linearGradient><pattern id="miss" width="4" height="4" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="4" height="4" fill="#eceaf3"/><line x1="0" y1="0" x2="0" y2="4" stroke="#b9b5cf" stroke-width="1.5"/></pattern></defs>` + g;
G = { X, cw, L, R, W, nShown, pTop, bot: eTop + eH, Y, EY, ex };
head(hover != null && hover < nShown ? hover : nShown - 1);
}
// hover crosshair + readout (chart and log tiles)
function showDay(i, cx, cy) {
if (!G || i < 0 || i >= G.nShown) return leave();
hover = i; head(i);
const day = i - HIST, l = day >= 0 ? S.log[day] : null;
$('hv').innerHTML = `<line x1="${G.X(i)}" x2="${G.X(i)}" y1="${G.pTop}" y2="${G.bot}" stroke="#0f1528" stroke-opacity=".3" stroke-dasharray="3 3"/>` +
(l ? `<circle cx="${G.ex(day + 1)}" cy="${G.EY(S.eq[day + 1])}" r="3.5" fill="#7800f0" stroke="#fff" stroke-width="1.5"/>` : '');
document.querySelectorAll('.tile.on').forEach(t => t.classList.remove('on'));
if (day >= 0 && $('log').children[day]) $('log').children[day].classList.add('on');
const tip = $('tip');
if (l && cx != null) { tip.innerHTML = `${sysName(l.arch, l.model)} · run ${l.run} → <b>${ACT[l.a]}</b> · <span style="color:${l.pnl > 0 ? '#5fe0a0' : l.pnl < 0 ? '#ff8a9a' : '#ccc'}">${pct(l.pnl)}</span>`; tip.style.left = cx + 14 + 'px'; tip.style.top = cy - 34 + 'px'; tip.classList.add('on'); }
else tip.classList.remove('on');
}
$('kline').addEventListener('mousemove', e => {
if (!G) return;
const r = e.currentTarget.getBoundingClientRect();
showDay(Math.round((e.clientX - r.left - G.L) / G.cw - .5), e.clientX, e.clientY);
});
$('log').addEventListener('mouseover', e => { const t = e.target.closest('.tile'); if (t && S.log[+t.dataset.d]) showDay(HIST + +t.dataset.d); });
$('log').addEventListener('mouseleave', () => leave());
const leave = () => { hover = null; if ($('hv')) $('hv').innerHTML = ''; document.querySelectorAll('.tile.on').forEach(t => t.classList.remove('on')); $('tip').classList.remove('on'); if (G) head(G.nShown - 1); };
$('kline').addEventListener('mouseleave', leave);
// ---------- picks & buttons ----------
$('arch').addEventListener('click', e => { const b = e.target.closest('button'); if (b) { arch = b.dataset.a; renderSide(); } });
$('model').addEventListener('click', e => { const b = e.target.closest('button'); if (b) { model = b.dataset.m; renderSide(); } });
$('goBtn').addEventListener('click', () => { stopAuto(); step(); });
$('autoBtn').addEventListener('click', () => {
if (autoT) return stopAuto();
$('autoBtn').classList.add('on'); $('autoBtn').textContent = 'Stop ■'; step();
autoT = setInterval(step, 320);
});
$('newBtn').addEventListener('click', startCard);
document.addEventListener('keydown', e => {
if ($('ov').classList.contains('on')) return;
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); stopAuto(); step(); }
});
addEventListener('resize', () => S && draw());
// ---------- overlays ----------
const spark = tk => { // pre-window history only
const c = OH.bars[tk].slice(0, HIST).map(b => b[3]), lo = Math.min(...c), hi = Math.max(...c), up = c[c.length - 1] >= c[0];
const p = c.map((v, i) => `${(i / (c.length - 1) * 100).toFixed(1)},${(30 - (v - lo) / (hi - lo) * 26 - 2).toFixed(1)}`).join(' ');
return `<svg viewBox="0 0 100 32" preserveAspectRatio="none"><polyline points="${p}" fill="none" stroke="${up ? '#0f9d58' : '#d6304a'}" stroke-width="1.5" vector-effect="non-scaling-stroke"/></svg>`;
};
function open(html) { $('ovCard').innerHTML = html; $('ov').classList.add('on'); }
function close() { $('ov').classList.remove('on'); }
function startCard() {
stopAuto();
open(`<div class="kick"><span>HERCULEAN · Trading workflow</span></div>
<h2>Welcome, <em id="nm">${name}</em><button class="reroll" id="reroll" title="Another name">↻</button></h2>
<p>Pick a stock. For each of the 61 trading days (Jan 2 – Mar 31, 2026) you choose which agent system trades; one of its three recorded runs is drawn, and its real decision is executed. Can your picks beat Buy &amp; Hold?</p>
<div class="stocks">${H.tradeAssets.map(t => `<button class="stock${t === sym ? ' sel' : ''}" data-t="${t}"><b>${t}</b><small>${CO[t]}</small>${spark(t)}</button>`).join('')}</div>
<div class="rules"><span><i>30</i>agent systems</span><span><i>3</i>runs each</span><span><i>$100k</i>start</span><span><i>open→open</i>no costs</span></div>
<div class="ov-actions"><button class="go" id="startBtn">Start trading ▶</button>${S && S.d && S.d < N ? '<button class="ghost" id="resume">Resume</button>' : ''}<a class="to-lb" href="./index.html">See the leaderboard</a></div>`);
let tk = sym;
$('ovCard').querySelectorAll('.stock').forEach(b => b.onclick = () => { tk = b.dataset.t; $('ovCard').querySelectorAll('.stock').forEach(x => x.classList.toggle('sel', x === b)); });
$('reroll').onclick = () => { let n; do n = pickRand(NAMES); while (n === name); name = n; $('nm').textContent = n; };
$('startBtn').onclick = () => { close(); newGame(tk); };
if ($('resume')) $('resume').onclick = close;
}
function endCard() {
const m = metrics(S.log.map(l => l.pnl)), bh = metrics(S.ret), st = standing(N), rank = st.rank, top = st.top;
const fav = Object.entries(S.picks).sort((p, q) => q[1] - p[1])[0], [fa, fm] = fav[0].split('|');
const beat = m.cr > bh.cr, gap = (m.cr - top.cr) * 100;
const tb = rankTable(st, 1);
open(`<div class="kick"><span>${sym} · window closed · 61 days</span></div>
<h2>${beat ? `${name} <em>beat</em> Buy &amp; Hold` : `Buy &amp; Hold wins this time, <em>${name}</em>`}</h2>
<div class="res">
<div><small>Final equity</small><b>${money(1e5 * (1 + m.cr))}</b><em>B&amp;H ${money(1e5 * (1 + bh.cr))}</em></div>
<div><small>CR</small><b class="${cls(m.cr)}">${pct(m.cr)}</b><em>B&amp;H ${pct(bh.cr)}</em></div>
<div><small>SR</small><b>${m.sr.toFixed(2)}</b><em>B&amp;H ${bh.sr.toFixed(2)}</em></div>
<div><small>MDD</small><b>${(m.mdd * 100).toFixed(2)}%</b><em>B&amp;H ${(bh.mdd * 100).toFixed(2)}%</em></div>
</div>
<div class="rankline">
<div class="rk-top"><span><span class="big">#${rank}</span>of ${st.n} on ${sym} Trading</span>
<span>${rank === 1 ? 'ahead of #2 by <b>' + ((m.cr - st.all[0].cr) * 100).toFixed(2) + ' pp</b>' : `<b class="dn">${gap.toFixed(2)} pp</b> behind #1`}</span></div>
${strip(st, 580, 96)}
<div class="tb"><div class="tr th"><span>Rank</span><span>Agent system · CR, mean of 3 runs</span><span>CR</span><span>vs #1</span></div>${tb}</div>
<div class="fav">Your most-picked: <b>${sysName(fa, fm)}</b> (${fav[1]} of 61 days)</div>
</div>
<div class="ov-actions"><button class="go" id="again">Play again ▶</button><button class="ghost" id="review">Review chart</button><a class="to-lb" href="./index.html">See the leaderboard</a></div>`);
$('again').onclick = () => { name = pickRand(NAMES.filter(n => n !== name)); startCard(); };
$('review').onclick = close;
}
newGame(sym);
startCard();
window.__play = { step, state: () => S, set: (a, m) => { arch = a; model = m; renderSide(); }, endCard, close }; // for tests
})();