mirror of
https://github.com/theodore-song/polymarket-analyst.git
synced 2026-07-28 00:17:46 +00:00
Polymarket Analyst: client-side analyst + paper-trading agent with category filters
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
.DS_Store
|
||||
.vercel
|
||||
.claude/
|
||||
@@ -0,0 +1,35 @@
|
||||
# 📊 Polymarket Analyst — standalone website
|
||||
|
||||
A **single-file website**. Everything (fetching live Polymarket data, the
|
||||
analysis engine, and the AI paper-trading agent) runs in your browser. The
|
||||
paper portfolio is saved in your browser's local storage. No server, no keys.
|
||||
|
||||
## Just look at it now
|
||||
Double-click **`index.html`** — it opens in your browser and works immediately.
|
||||
On first open it fetches live markets, generates today's suggestions, and the
|
||||
agent makes its first trades. It auto-refreshes once per day; the **Run daily
|
||||
cycle now** button forces a refresh anytime.
|
||||
|
||||
## Put it online (free) so you can reach it from any device
|
||||
|
||||
Pick one — all give you a public URL:
|
||||
|
||||
**Option A — Netlify Drop (easiest, ~30 seconds, no account needed to start)**
|
||||
1. Go to <https://app.netlify.com/drop>
|
||||
2. Drag the whole **`polymarket-site`** folder onto the page.
|
||||
3. You get a live URL like `https://your-name.netlify.app`. Done.
|
||||
|
||||
**Option B — GitHub Pages**
|
||||
1. Create a new GitHub repo and upload `index.html`.
|
||||
2. Repo → Settings → Pages → Branch: `main`, folder: `/root` → Save.
|
||||
3. Your site appears at `https://<you>.github.io/<repo>/`.
|
||||
|
||||
**Option C — Vercel**
|
||||
1. <https://vercel.com> → Add New → Project → import the folder (or `vercel`
|
||||
CLI in this folder) → Deploy.
|
||||
|
||||
## Notes
|
||||
- Paper trading only — no real money, nothing places real orders.
|
||||
- The analysis is a transparent heuristic, **not financial advice**.
|
||||
- Because the portfolio lives in your browser, each browser/device keeps its
|
||||
own portfolio. Clearing site data resets it (so does the **Reset** button).
|
||||
+564
@@ -0,0 +1,564 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Polymarket Analyst & AI Paper Trader</title>
|
||||
<style>
|
||||
:root{
|
||||
--bg:#0c1018;--panel:#151b27;--panel-2:#1d2433;--border:#283044;--text:#e7ecf3;
|
||||
--muted:#8a96ab;--green:#2ec27e;--red:#ff5d6c;--yellow:#ffce5c;--accent:#6c8cff;
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;
|
||||
background:var(--bg);color:var(--text);line-height:1.45}
|
||||
header{display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:16px;
|
||||
padding:22px 28px;border-bottom:1px solid var(--border);
|
||||
background:linear-gradient(180deg,#121826,#0c1018)}
|
||||
.brand h1{margin:0;font-size:24px}
|
||||
.tag{margin:4px 0 0;color:var(--muted);font-size:14px}
|
||||
.actions{display:flex;gap:10px;align-items:center}
|
||||
.btn{border:1px solid var(--border);border-radius:8px;padding:10px 16px;font-size:14px;
|
||||
cursor:pointer;background:var(--panel-2);color:var(--text);transition:.15s}
|
||||
.btn:hover{border-color:var(--accent)}
|
||||
.btn.primary{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:600}
|
||||
.btn.primary:hover{filter:brightness(1.1)}
|
||||
.btn:disabled{opacity:.5;cursor:wait}
|
||||
.btn.ghost{background:transparent}
|
||||
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:14px;padding:22px 28px}
|
||||
.stat{background:var(--panel);border:1px solid var(--border);border-radius:12px;padding:16px 18px}
|
||||
.stat .label{color:var(--muted);font-size:12px;text-transform:uppercase;letter-spacing:.5px}
|
||||
.stat .value{font-size:26px;font-weight:700;margin-top:6px}
|
||||
main{display:grid;grid-template-columns:1fr 1fr;gap:22px;padding:0 28px 28px}
|
||||
@media (max-width:950px){main{grid-template-columns:1fr}}
|
||||
.col h2{font-size:18px;margin:6px 0 14px}
|
||||
.muted{color:var(--muted);font-weight:400;font-size:13px}
|
||||
.card{background:var(--panel);border:1px solid var(--border);border-radius:12px;padding:16px 18px;margin-bottom:16px}
|
||||
.card h3{margin:0 0 12px;font-size:14px;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}
|
||||
.sug{background:var(--panel);border:1px solid var(--border);border-radius:12px;padding:16px;
|
||||
margin-bottom:14px;border-left:4px solid var(--accent)}
|
||||
.sug .q{font-weight:600;font-size:15px}
|
||||
.sug .event{color:var(--muted);font-size:12px;margin:2px 0 10px}
|
||||
.sug-row{display:flex;gap:14px;flex-wrap:wrap;align-items:center;margin-bottom:8px}
|
||||
.pill{font-size:12px;font-weight:700;padding:3px 10px;border-radius:999px}
|
||||
.pill.YES{background:rgba(46,194,126,.15);color:var(--green)}
|
||||
.pill.NO{background:rgba(255,93,108,.15);color:var(--red)}
|
||||
.conv-bar{flex:1;min-width:120px;height:7px;background:var(--panel-2);border-radius:999px;overflow:hidden}
|
||||
.conv-bar>span{display:block;height:100%;background:linear-gradient(90deg,var(--accent),var(--green))}
|
||||
.rationale{font-size:13px;color:#c4cde0;margin:8px 0}
|
||||
.drivers{display:flex;gap:6px;flex-wrap:wrap}
|
||||
.driver{font-size:11px;background:var(--panel-2);border:1px solid var(--border);padding:2px 8px;border-radius:6px;color:var(--muted)}
|
||||
.metrics{display:flex;gap:18px;font-size:12px;color:var(--muted);margin-top:8px;flex-wrap:wrap}
|
||||
.metrics b{color:var(--text)}
|
||||
a.market-link{color:var(--accent);text-decoration:none;font-size:12px}
|
||||
a.market-link:hover{text-decoration:underline}
|
||||
.pos{display:flex;justify-content:space-between;align-items:center;padding:10px 0;border-bottom:1px solid var(--border)}
|
||||
.pos:last-child{border-bottom:none}
|
||||
.pos .pq{font-size:13px;max-width:60%}
|
||||
.pos .sub{color:var(--muted);font-size:11px}
|
||||
.pnl.pos-val{color:var(--green)}
|
||||
.pnl.neg-val{color:var(--red)}
|
||||
.right{text-align:right}
|
||||
.log-item{font-size:12px;padding:7px 0;border-bottom:1px solid var(--border);color:#c4cde0}
|
||||
.log-item:last-child{border-bottom:none}
|
||||
.log-item .badge{font-weight:700;font-size:10px;padding:1px 6px;border-radius:4px;margin-right:6px}
|
||||
.badge.OPEN{background:rgba(108,140,255,.18);color:var(--accent)}
|
||||
.badge.CLOSE{background:rgba(255,206,92,.18);color:var(--yellow)}
|
||||
.log-date{color:var(--muted)}
|
||||
#chart{width:100%;height:200px;display:block}
|
||||
.chart-meta{display:flex;justify-content:space-between;font-size:12px;color:var(--muted);margin-top:8px}
|
||||
.empty{color:var(--muted);font-size:13px;padding:8px 0}
|
||||
footer{padding:18px 28px;border-top:1px solid var(--border);color:var(--muted);font-size:12px}
|
||||
.toast{position:fixed;bottom:22px;right:22px;background:var(--panel-2);border:1px solid var(--accent);
|
||||
padding:12px 18px;border-radius:10px;font-size:14px;opacity:0;transform:translateY(10px);
|
||||
transition:.25s;pointer-events:none;max-width:340px}
|
||||
.toast.show{opacity:1;transform:translateY(0)}
|
||||
.dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--muted);margin-right:6px}
|
||||
.dot.live{background:var(--green)}
|
||||
.filterbar{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:6px}
|
||||
.chip{font-size:13px;padding:6px 13px;border-radius:999px;cursor:pointer;
|
||||
background:var(--panel-2);border:1px solid var(--border);color:var(--muted);transition:.15s;user-select:none}
|
||||
.chip:hover{border-color:var(--accent);color:var(--text)}
|
||||
.chip.active{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:600}
|
||||
.chip .ct{opacity:.7;font-size:11px;margin-left:4px}
|
||||
.cat-badge{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.4px;
|
||||
padding:2px 8px;border-radius:6px;background:rgba(108,140,255,.16);color:var(--accent)}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<div class="brand">
|
||||
<h1>📊 Polymarket Analyst</h1>
|
||||
<p class="tag">Daily AI-driven market analysis & an autonomous paper-trading agent · runs entirely in your browser</p>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<span class="muted"><span class="dot" id="statusDot"></span><span id="statusText">idle</span></span>
|
||||
<button id="runBtn" class="btn primary">Run daily cycle now</button>
|
||||
<button id="resetBtn" class="btn ghost">Reset portfolio</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="stats" id="stats"></section>
|
||||
|
||||
<main>
|
||||
<div class="col">
|
||||
<h2>🤖 Agent Portfolio</h2>
|
||||
<div class="card chart-card">
|
||||
<h3>Equity curve</h3>
|
||||
<svg id="chart" viewBox="0 0 600 200" preserveAspectRatio="none"></svg>
|
||||
<div class="chart-meta" id="chartMeta"></div>
|
||||
</div>
|
||||
<div class="card"><h3>Open positions</h3><div id="positions"></div></div>
|
||||
<div class="card"><h3>Activity log</h3><div id="history"></div></div>
|
||||
</div>
|
||||
<div class="col">
|
||||
<h2>💡 Today's Suggestions <span id="sugDate" class="muted"></span></h2>
|
||||
<div class="filterbar" id="filterbar"></div>
|
||||
<div class="muted" id="focusNote" style="margin-bottom:10px"></div>
|
||||
<div id="suggestions"></div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<p>Paper trading only — no real money. Live prices from Polymarket's public Gamma API.
|
||||
Analysis is a deterministic heuristic, not financial advice. Your portfolio is saved in this
|
||||
browser's local storage.</p>
|
||||
</footer>
|
||||
|
||||
<script>
|
||||
"use strict";
|
||||
/* ============================================================
|
||||
Polymarket Analyst — fully client-side.
|
||||
Fetches live markets, scores them, and runs a paper-trading
|
||||
agent. State persists in localStorage. No backend needed.
|
||||
============================================================ */
|
||||
|
||||
const GAMMA = "https://gamma-api.polymarket.com";
|
||||
const STARTING_BALANCE = 10000;
|
||||
const STORE_KEY = "pma_portfolio_v1";
|
||||
const SUG_KEY = "pma_suggestions_v1";
|
||||
const FOCUS_KEY = "pma_focus_v1";
|
||||
const CATEGORIES = ["All","Politics","Sports","Crypto","Economy","Pop Culture","Other"];
|
||||
const getFocus = () => localStorage.getItem(FOCUS_KEY) || "All";
|
||||
const setFocus = (c) => localStorage.setItem(FOCUS_KEY, c);
|
||||
|
||||
/* ---------- small utils ---------- */
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const fmtUSD = (n) => "$" + Number(n).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});
|
||||
const fmtPct = (n) => (n>=0?"+":"") + Number(n).toFixed(2) + "%";
|
||||
const signClass = (n) => (n>0?"pos-val":n<0?"neg-val":"");
|
||||
const todayStr = () => new Date().toISOString().slice(0,10);
|
||||
const nowIso = () => new Date().toISOString();
|
||||
|
||||
function toast(msg){
|
||||
let t=document.querySelector(".toast");
|
||||
if(!t){t=document.createElement("div");t.className="toast";document.body.appendChild(t);}
|
||||
t.textContent=msg;t.classList.add("show");
|
||||
clearTimeout(t._h);t._h=setTimeout(()=>t.classList.remove("show"),3600);
|
||||
}
|
||||
function setStatus(text,live){
|
||||
$("statusText").textContent=text;
|
||||
$("statusDot").classList.toggle("live",!!live);
|
||||
}
|
||||
|
||||
/* ---------- Polymarket client ---------- */
|
||||
function parseJsonField(v){
|
||||
if(v==null) return [];
|
||||
if(Array.isArray(v)) return v;
|
||||
try{return JSON.parse(v);}catch(e){return [];}
|
||||
}
|
||||
function toNum(v,d=0){const n=Number(v);return Number.isFinite(n)?n:d;}
|
||||
function daysUntil(iso){
|
||||
if(!iso) return null;
|
||||
const dt=new Date(iso);
|
||||
if(isNaN(dt)) return null;
|
||||
return (dt-new Date())/86400000;
|
||||
}
|
||||
/* Map Polymarket tag slugs/labels to a top-level category.
|
||||
Checked in priority order; first match wins. */
|
||||
const CATEGORY_RULES=[
|
||||
["Politics",["politics","election","elections","us-politics","geopolitics","trump",
|
||||
"world-leaders","government","congress","policy","biden","2026-election","democrats","republicans"]],
|
||||
["Crypto",["crypto","bitcoin","ethereum","btc","eth","solana","memecoins","defi","stablecoin","xrp"]],
|
||||
["Sports",["sports","soccer","football","nba","nfl","mlb","nhl","tennis","basketball","baseball",
|
||||
"ufc","boxing","cricket","golf","f1","fifa-world-cup","games","tournament-futures","epl"]],
|
||||
["Economy",["economy","business","fed","inflation","interest-rates","gdp","jobs","recession",
|
||||
"stocks","earnings","financials","tariffs"]],
|
||||
["Pop Culture",["pop-culture","entertainment","movies","music","tv","awards","celebrity","gaming","ai"]],
|
||||
];
|
||||
function classifyCategory(tags){
|
||||
const slugs=tags.map(t=>(t.slug||t.label||"").toLowerCase());
|
||||
for(const [cat,keys] of CATEGORY_RULES){
|
||||
if(slugs.some(s=>keys.includes(s))) return cat;
|
||||
}
|
||||
return "Other";
|
||||
}
|
||||
function normalizeMarket(raw){
|
||||
const outcomes=parseJsonField(raw.outcomes);
|
||||
const prices=parseJsonField(raw.outcomePrices).map(p=>toNum(p));
|
||||
if(outcomes.length!==2||prices.length!==2) return null;
|
||||
if(raw.acceptingOrders===false||raw.closed) return null;
|
||||
const yes=prices[0];
|
||||
if(yes<=0||yes>=1) return null;
|
||||
const events=raw.events||[];
|
||||
const ev=events.length?events[0]:{};
|
||||
const tags=Array.isArray(raw.tags)?raw.tags:[];
|
||||
return {
|
||||
category:classifyCategory(tags),
|
||||
tags:tags.map(t=>t.label).filter(Boolean).slice(0,4),
|
||||
id:String(raw.id),
|
||||
question:(raw.question||"").trim(),
|
||||
event:(ev.title||"").trim(),
|
||||
yes_price:+yes.toFixed(4),
|
||||
no_price:+prices[1].toFixed(4),
|
||||
volume:toNum(raw.volumeNum||raw.volume),
|
||||
volume_24hr:toNum(raw.volume24hr),
|
||||
volume_1wk:toNum(raw.volume1wk),
|
||||
liquidity:toNum(raw.liquidityNum||raw.liquidity),
|
||||
end_date:raw.endDateIso||raw.endDate,
|
||||
days_to_resolution:daysUntil(raw.endDate),
|
||||
image:raw.image||"",
|
||||
url:ev.slug?`https://polymarket.com/event/${ev.slug}`:"",
|
||||
};
|
||||
}
|
||||
async function fetchMarkets(pages=4,perPage=100){
|
||||
// The Gamma API caps each response near 100 markets, so page through a few
|
||||
// to get enough breadth for category filters (crypto/economy/politics).
|
||||
const all=[];
|
||||
for(let i=0;i<pages;i++){
|
||||
const params=new URLSearchParams({closed:"false",active:"true",archived:"false",
|
||||
include_tag:"true",limit:String(perPage),offset:String(i*perPage),
|
||||
order:"volume24hr",ascending:"false"});
|
||||
const r=await fetch(`${GAMMA}/markets?${params}`);
|
||||
if(!r.ok){if(i===0) throw new Error("Polymarket API "+r.status);break;}
|
||||
const raw=await r.json();
|
||||
if(!raw.length) break;
|
||||
all.push(...raw);
|
||||
}
|
||||
return all.map(normalizeMarket).filter(m=>m&&m.question);
|
||||
}
|
||||
async function fetchMarketPrice(id){
|
||||
try{
|
||||
const r=await fetch(`${GAMMA}/markets/${id}`);
|
||||
if(!r.ok) return null;
|
||||
return normalizeMarket(await r.json());
|
||||
}catch(e){return null;}
|
||||
}
|
||||
|
||||
/* ---------- Analysis engine (ported 1:1 from the Python model) ---------- */
|
||||
const W={LIQ:0.25,MOM:0.25,MIS:0.30,TIME:0.20};
|
||||
const MIN_VOLUME=20000;
|
||||
const clamp=(x,a,b)=>Math.max(a,Math.min(b,x));
|
||||
|
||||
function liquiditySignal(m){
|
||||
const vol=Math.min(1,Math.log10(m.volume+1)/6.0);
|
||||
const liq=Math.min(1,Math.log10(m.liquidity+1)/5.3);
|
||||
return 0.6*vol+0.4*liq;
|
||||
}
|
||||
function momentumSignal(m){
|
||||
const dailyAvg=m.volume_1wk?m.volume_1wk/7:0;
|
||||
if(dailyAvg<=0) return m.volume_24hr>0?0.3:0;
|
||||
const ratio=m.volume_24hr/dailyAvg;
|
||||
return clamp((ratio-0.5)/2.0,0,1);
|
||||
}
|
||||
function fairValue(m){
|
||||
const p=m.yes_price,mom=momentumSignal(m),liq=liquiditySignal(m);
|
||||
if(p>0.92) return Math.min(0.995,p+0.04*liq*(1-p)*4);
|
||||
if(p<0.08) return Math.max(0.005,p-0.20*p);
|
||||
const drift=(mom-0.5)*0.06;
|
||||
return clamp(p+drift,0.02,0.98);
|
||||
}
|
||||
function timingSignal(d){
|
||||
if(d==null) return 0.4;
|
||||
if(d<1) return 0.1;
|
||||
if(d<=3) return 0.5;
|
||||
if(d<=90) return 1.0-(d-3)/87.0*0.4;
|
||||
return 0.35;
|
||||
}
|
||||
function analyzeMarket(m){
|
||||
if(m.volume<MIN_VOLUME) return null;
|
||||
const p=m.yes_price, fair=fairValue(m), edgeYes=fair-p, edge=Math.abs(edgeYes);
|
||||
const liq=liquiditySignal(m), mom=momentumSignal(m), timing=timingSignal(m.days_to_resolution);
|
||||
const mis=Math.min(1,edge/0.10);
|
||||
const score=W.LIQ*liq+W.MOM*mom+W.MIS*mis+W.TIME*timing;
|
||||
const conviction=+(score*100).toFixed(1);
|
||||
let side,entry,rationale;
|
||||
if(edgeYes>0.015){side="YES";entry=p;
|
||||
rationale=`Model fair value ${pct(fair)} vs market ${pct(p)} — YES looks underpriced by ~${(edgeYes*100).toFixed(1)}c.`;}
|
||||
else if(edgeYes<-0.015){side="NO";entry=m.no_price;
|
||||
rationale=`Model fair value ${pct(fair)} vs market ${pct(p)} — YES looks overpriced, so NO at ${pct(m.no_price)} has the edge.`;}
|
||||
else{side="HOLD";entry=p;
|
||||
rationale=`Price ${pct(p)} is close to model fair value ${pct(fair)}; no clear edge — watch only.`;}
|
||||
const drivers=[];
|
||||
if(liq>0.6)drivers.push("deep/liquid market");
|
||||
if(mom>0.6)drivers.push("strong fresh volume (24h surge)");
|
||||
if(timing>0.8)drivers.push("resolves in a good window");
|
||||
if(mis>0.4)drivers.push("notable price/value gap");
|
||||
if(!drivers.length)drivers.push("thin signal");
|
||||
return {market_id:m.id,question:m.question,event:m.event,url:m.url,
|
||||
category:m.category,tags:m.tags,
|
||||
yes_price:p,no_price:m.no_price,fair_value:+fair.toFixed(4),edge:+edgeYes.toFixed(4),
|
||||
side,entry_price:+entry.toFixed(4),conviction,volume:m.volume,volume_24hr:m.volume_24hr,
|
||||
days_to_resolution:m.days_to_resolution!=null?+m.days_to_resolution.toFixed(1):null,
|
||||
drivers,rationale};
|
||||
}
|
||||
const pct=(x)=>Math.round(x*100)+"%";
|
||||
function generateSuggestions(markets,perCategory=10){
|
||||
// Keep the top picks *within each category* so every filter chip has its
|
||||
// best ideas, instead of letting high-volume sports crowd everything out.
|
||||
const actionable=markets.map(analyzeMarket).filter(Boolean).filter(a=>a.side!=="HOLD")
|
||||
.sort((a,b)=>b.conviction-a.conviction);
|
||||
const byCat={}; const out=[];
|
||||
for(const a of actionable){
|
||||
const c=a.category||"Other";
|
||||
byCat[c]=(byCat[c]||0)+1;
|
||||
if(byCat[c]<=perCategory) out.push(a);
|
||||
}
|
||||
return out.sort((a,b)=>b.conviction-a.conviction);
|
||||
}
|
||||
|
||||
/* ---------- Portfolio store (localStorage) ---------- */
|
||||
function defaultPortfolio(){
|
||||
return {cash:STARTING_BALANCE,starting_balance:STARTING_BALANCE,
|
||||
positions:[],closed:[],history:[],snapshots:[],last_run:null};
|
||||
}
|
||||
function loadPortfolio(){
|
||||
try{const s=localStorage.getItem(STORE_KEY);return s?JSON.parse(s):defaultPortfolio();}
|
||||
catch(e){return defaultPortfolio();}
|
||||
}
|
||||
function savePortfolio(p){localStorage.setItem(STORE_KEY,JSON.stringify(p));}
|
||||
function loadSuggestions(){
|
||||
try{const s=localStorage.getItem(SUG_KEY);return s?JSON.parse(s):{date:null,suggestions:[]};}
|
||||
catch(e){return {date:null,suggestions:[]};}
|
||||
}
|
||||
function saveSuggestions(sugs){
|
||||
const payload={date:todayStr(),generated_at:nowIso(),suggestions:sugs};
|
||||
localStorage.setItem(SUG_KEY,JSON.stringify(payload));return payload;
|
||||
}
|
||||
|
||||
/* ---------- Agent ---------- */
|
||||
const MAX_POS_FRAC=0.10, MAX_NEW_PER_DAY=4, MIN_CONV=45, CASH_FLOOR=0.05;
|
||||
const equity=(p)=>p.cash+p.positions.reduce((s,x)=>s+x.shares*x.current_price,0);
|
||||
function kellyFraction(conv,edge){
|
||||
const base=(conv/100)*Math.min(1,Math.abs(edge)/0.10);
|
||||
return Math.min(MAX_POS_FRAC,0.25*base);
|
||||
}
|
||||
const hasPosition=(p,id)=>p.positions.some(x=>x.market_id===id);
|
||||
|
||||
async function markToMarket(p){
|
||||
const notes=[],stillOpen=[];
|
||||
for(const pos of p.positions){
|
||||
const fresh=await fetchMarketPrice(pos.market_id);
|
||||
if(fresh==null){
|
||||
const proceeds=pos.shares*pos.current_price;
|
||||
p.cash+=proceeds;pos.exit_price=pos.current_price;pos.closed_at=nowIso();
|
||||
pos.realized_pnl=+(proceeds-pos.cost).toFixed(2);pos.reason_closed="market resolved/closed";
|
||||
p.closed.push(pos);
|
||||
p.history.push({date:todayStr(),action:"CLOSE",market_id:pos.market_id,question:pos.question,
|
||||
side:pos.side,detail:`Settled for ${fmtUSD(proceeds)} (P&L ${fmtUSD(pos.realized_pnl)})`});
|
||||
notes.push(`Closed '${pos.question.slice(0,50)}' (resolved)`);continue;
|
||||
}
|
||||
const price=pos.side==="YES"?fresh.yes_price:fresh.no_price;
|
||||
pos.current_price=+price.toFixed(4);
|
||||
pos.value=+(pos.shares*price).toFixed(2);
|
||||
pos.unrealized_pnl=+(pos.value-pos.cost).toFixed(2);
|
||||
stillOpen.push(pos);
|
||||
}
|
||||
p.positions=stillOpen;return notes;
|
||||
}
|
||||
function openPositions(p,sugs,focus){
|
||||
const notes=[];
|
||||
const cands=sugs.filter(s=>(s.side==="YES"||s.side==="NO")&&s.conviction>=MIN_CONV
|
||||
&&!hasPosition(p,s.market_id)&&(focus==="All"||!focus||s.category===focus))
|
||||
.sort((a,b)=>b.conviction-a.conviction);
|
||||
let opened=0;
|
||||
for(const s of cands){
|
||||
if(opened>=MAX_NEW_PER_DAY) break;
|
||||
const eq=equity(p), investable=p.cash-eq*CASH_FLOOR;
|
||||
if(investable<=50) break;
|
||||
const frac=kellyFraction(s.conviction,s.edge);
|
||||
let stake=Math.min(eq*frac,investable);
|
||||
if(stake<50) continue;
|
||||
const entry=s.entry_price;
|
||||
if(entry<=0||entry>=1) continue;
|
||||
const shares=+(stake/entry).toFixed(2), cost=+(shares*entry).toFixed(2);
|
||||
if(cost>p.cash) continue;
|
||||
p.cash=+(p.cash-cost).toFixed(2);
|
||||
p.positions.push({market_id:s.market_id,question:s.question,side:s.side,shares,
|
||||
entry_price:+entry.toFixed(4),current_price:+entry.toFixed(4),cost,value:cost,
|
||||
unrealized_pnl:0,conviction:s.conviction,rationale:s.rationale,opened_at:nowIso(),url:s.url||""});
|
||||
p.history.push({date:todayStr(),action:"OPEN",market_id:s.market_id,question:s.question,side:s.side,
|
||||
detail:`Bought ${shares} ${s.side} @ ${pct(entry)} for ${fmtUSD(cost)} (conviction ${s.conviction})`});
|
||||
notes.push(`Opened ${s.side} on '${s.question.slice(0,50)}' (${fmtUSD(cost)})`);
|
||||
opened++;
|
||||
}
|
||||
return notes;
|
||||
}
|
||||
function recordSnapshot(p){
|
||||
const eq=equity(p), posVal=+(eq-p.cash).toFixed(2);
|
||||
const snap={date:todayStr(),timestamp:nowIso(),cash:+p.cash.toFixed(2),positions_value:posVal,
|
||||
equity:+eq.toFixed(2),pnl:+(eq-p.starting_balance).toFixed(2),
|
||||
return_pct:+((eq/p.starting_balance-1)*100).toFixed(2),open_positions:p.positions.length};
|
||||
p.snapshots=p.snapshots.filter(s=>s.date!==snap.date);
|
||||
p.snapshots.push(snap);p.snapshots.sort((a,b)=>a.date<b.date?-1:1);
|
||||
}
|
||||
async function runDailyCycle(){
|
||||
setStatus("fetching markets…",true);
|
||||
const markets=await fetchMarkets(4,100);
|
||||
setStatus("analyzing…",true);
|
||||
const sugs=generateSuggestions(markets,12);
|
||||
saveSuggestions(sugs);
|
||||
const p=loadPortfolio();
|
||||
setStatus("agent trading…",true);
|
||||
const mtm=await markToMarket(p);
|
||||
const trades=openPositions(p,sugs,getFocus());
|
||||
recordSnapshot(p);
|
||||
p.last_run=nowIso();
|
||||
savePortfolio(p);
|
||||
setStatus("up to date",false);
|
||||
return {suggestions:sugs.length,actions:mtm.concat(trades),equity:+equity(p).toFixed(2)};
|
||||
}
|
||||
|
||||
/* ---------- Rendering ---------- */
|
||||
function renderAll(){renderPortfolio();renderSuggestions();}
|
||||
function renderFilterBar(all){
|
||||
const focus=getFocus();
|
||||
const counts={}; CATEGORIES.forEach(c=>counts[c]=0);
|
||||
all.forEach(s=>{const c=counts[s.category]!==undefined?s.category:"Other";counts[c]++;});
|
||||
counts["All"]=all.length;
|
||||
$("filterbar").innerHTML=CATEGORIES.map(c=>{
|
||||
const n=counts[c]||0;
|
||||
const dim=(c!=="All"&&n===0)?"opacity:.4;":"";
|
||||
return `<span class="chip ${c===focus?"active":""}" data-cat="${c}" style="${dim}">${c}<span class="ct">${n}</span></span>`;
|
||||
}).join("");
|
||||
document.querySelectorAll("#filterbar .chip").forEach(el=>{
|
||||
el.addEventListener("click",()=>{setFocus(el.dataset.cat);renderSuggestions();});
|
||||
});
|
||||
}
|
||||
function renderSuggestions(){
|
||||
const data=loadSuggestions();
|
||||
$("sugDate").textContent=data.date?`· ${data.date}`:"";
|
||||
const all=data.suggestions||[];
|
||||
const root=$("suggestions");
|
||||
renderFilterBar(all);
|
||||
if(!all.length){
|
||||
root.innerHTML=`<div class="empty">No suggestions yet. Click "Run daily cycle now".</div>`;
|
||||
$("focusNote").textContent="";return;}
|
||||
const focus=getFocus();
|
||||
const filtered=(focus==="All"?all:all.filter(s=>s.category===focus)).slice(0,12);
|
||||
$("focusNote").textContent=focus==="All"
|
||||
? "Agent trades the strongest picks across all categories."
|
||||
: `Filtered to ${focus} — the agent will only open new ${focus} positions while this is selected.`;
|
||||
if(!filtered.length){
|
||||
root.innerHTML=`<div class="empty">No ${esc(focus)} suggestions in today's batch.</div>`;return;}
|
||||
root.innerHTML=filtered.map(s=>{
|
||||
const drivers=s.drivers.map(d=>`<span class="driver">${d}</span>`).join("");
|
||||
const days=s.days_to_resolution!=null?`${s.days_to_resolution}d`:"—";
|
||||
return `<div class="sug">
|
||||
<div class="sug-row" style="margin-bottom:6px">
|
||||
<span class="cat-badge">${esc(s.category||"Other")}</span>
|
||||
</div>
|
||||
<div class="q">${esc(s.question)}</div>
|
||||
<div class="event">${esc(s.event||"")}</div>
|
||||
<div class="sug-row">
|
||||
<span class="pill ${s.side}">BUY ${s.side}</span>
|
||||
<span class="muted">@ ${Math.round(s.entry_price*100)}¢</span>
|
||||
<div class="conv-bar"><span style="width:${s.conviction}%"></span></div>
|
||||
<span class="muted">${Math.round(s.conviction)} conviction</span>
|
||||
</div>
|
||||
<div class="rationale">${esc(s.rationale)}</div>
|
||||
<div class="drivers">${drivers}</div>
|
||||
<div class="metrics">
|
||||
<span>Vol <b>${fmtUSD(s.volume)}</b></span>
|
||||
<span>24h <b>${fmtUSD(s.volume_24hr)}</b></span>
|
||||
<span>Resolves <b>${days}</b></span>
|
||||
${s.url?`<a class="market-link" href="${s.url}" target="_blank" rel="noopener">View ↗</a>`:""}
|
||||
</div></div>`;
|
||||
}).join("");
|
||||
}
|
||||
function renderPortfolio(){
|
||||
const p=loadPortfolio();
|
||||
const eq=equity(p);
|
||||
const stats=[
|
||||
{label:"Equity",value:fmtUSD(eq)},
|
||||
{label:"Cash",value:fmtUSD(p.cash)},
|
||||
{label:"Total P&L",value:fmtUSD(eq-p.starting_balance),cls:signClass(eq-p.starting_balance)},
|
||||
{label:"Return",value:fmtPct((eq/p.starting_balance-1)*100),cls:signClass(eq-p.starting_balance)},
|
||||
{label:"Open positions",value:p.positions.length},
|
||||
];
|
||||
$("stats").innerHTML=stats.map(s=>
|
||||
`<div class="stat"><div class="label">${s.label}</div><div class="value ${s.cls||""}">${s.value}</div></div>`).join("");
|
||||
renderChart(p.snapshots);
|
||||
renderPositions(p.positions);
|
||||
renderHistory(p.history.slice(-50).reverse());
|
||||
}
|
||||
function renderChart(snaps){
|
||||
const svg=$("chart");
|
||||
if(!snaps||!snaps.length){svg.innerHTML="";$("chartMeta").textContent="No history yet.";return;}
|
||||
const pts=snaps.map(s=>s.equity);
|
||||
const W=600,H=200,pad=6;
|
||||
const min=Math.min(...pts,snaps[0].equity)*0.999, max=Math.max(...pts)*1.001, span=(max-min)||1;
|
||||
const x=(i)=>snaps.length===1?W/2:pad+(i/(snaps.length-1))*(W-2*pad);
|
||||
const y=(v)=>H-pad-((v-min)/span)*(H-2*pad);
|
||||
const line=snaps.map((s,i)=>`${i===0?"M":"L"}${x(i).toFixed(1)},${y(s.equity).toFixed(1)}`).join(" ");
|
||||
const area=`${line} L${x(snaps.length-1).toFixed(1)},${H-pad} L${x(0).toFixed(1)},${H-pad} Z`;
|
||||
const up=pts[pts.length-1]>=snaps[0].equity, color=up?"#2ec27e":"#ff5d6c";
|
||||
svg.innerHTML=`<defs><linearGradient id="g" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stop-color="${color}" stop-opacity="0.35"/>
|
||||
<stop offset="100%" stop-color="${color}" stop-opacity="0"/></linearGradient></defs>
|
||||
<path d="${area}" fill="url(#g)"/><path d="${line}" fill="none" stroke="${color}" stroke-width="2"/>`;
|
||||
const last=snaps[snaps.length-1];
|
||||
$("chartMeta").innerHTML=`<span>${snaps[0].date}</span><span>${snaps.length} day(s) · ${fmtPct(last.return_pct)}</span><span>${last.date}</span>`;
|
||||
}
|
||||
function renderPositions(positions){
|
||||
const root=$("positions");
|
||||
if(!positions.length){root.innerHTML=`<div class="empty">No open positions yet.</div>`;return;}
|
||||
root.innerHTML=positions.map(p=>{
|
||||
const pnl=p.unrealized_pnl||0;
|
||||
return `<div class="pos"><div>
|
||||
<div class="pq">${esc(p.question)}</div>
|
||||
<div class="sub">${p.shares} ${p.side} @ ${Math.round(p.entry_price*100)}¢ → ${Math.round(p.current_price*100)}¢ · conv ${p.conviction}</div>
|
||||
</div><div class="right">
|
||||
<div>${fmtUSD(p.value)}</div>
|
||||
<div class="pnl ${signClass(pnl)}">${pnl>=0?"+":""}${fmtUSD(pnl)}</div>
|
||||
</div></div>`;
|
||||
}).join("");
|
||||
}
|
||||
function renderHistory(history){
|
||||
const root=$("history");
|
||||
if(!history.length){root.innerHTML=`<div class="empty">No activity yet.</div>`;return;}
|
||||
root.innerHTML=history.map(h=>
|
||||
`<div class="log-item"><span class="badge ${h.action}">${h.action}</span><span class="log-date">${h.date}</span> — ${esc(h.detail)}</div>`).join("");
|
||||
}
|
||||
function esc(s){return String(s).replace(/[&<>"]/g,c=>({"&":"&","<":"<",">":">",'"':"""}[c]));}
|
||||
|
||||
/* ---------- Wire up ---------- */
|
||||
$("runBtn").addEventListener("click",async()=>{
|
||||
const btn=$("runBtn");btn.disabled=true;btn.textContent="Running…";
|
||||
try{
|
||||
const r=await runDailyCycle();
|
||||
toast(`Cycle done · ${r.suggestions} suggestions · equity ${fmtUSD(r.equity)}`);
|
||||
renderAll();
|
||||
}catch(e){toast("Run failed: "+e.message);setStatus("error",false);}
|
||||
btn.disabled=false;btn.textContent="Run daily cycle now";
|
||||
});
|
||||
$("resetBtn").addEventListener("click",()=>{
|
||||
if(!confirm("Reset the paper portfolio to its starting balance?")) return;
|
||||
savePortfolio(defaultPortfolio());localStorage.removeItem(SUG_KEY);
|
||||
toast("Portfolio reset.");renderAll();
|
||||
});
|
||||
|
||||
/* On load: render, then auto-run once per day. */
|
||||
(async function init(){
|
||||
renderAll();
|
||||
const sug=loadSuggestions();
|
||||
if(sug.date!==todayStr()){
|
||||
const btn=$("runBtn");btn.disabled=true;btn.textContent="Running…";
|
||||
try{await runDailyCycle();renderAll();toast("Fresh daily analysis ready.");}
|
||||
catch(e){setStatus("error — click Run to retry",false);}
|
||||
btn.disabled=false;btn.textContent="Run daily cycle now";
|
||||
}else{setStatus("up to date",false);}
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user