""" desk.py - a 7-seat AI research desk. PAPER TRADING / EDUCATION ONLY. This script NEVER sends real orders. It has no broker login, no withdrawal access and no live-trading code path. "Trades" are written to a local JSON ledger (paper_ledger.json) with fake money. Not investment advice. Seats (each seat = one role prompt): 1 WATCHER reads the chart numbers 2 HUNTER looks for a setup 3 NEWS reads the headlines 4 FLOW follows volume ("big money" proxy) 5 CROWD N small voters, majority wins 6 BOSS writes the trade proposal 7 RISK hard rules in code + a skeptic prompt. RISK HAS THE FINAL VETO. Run: pip install openai yfinance python desk.py NVDA --offline # no API key, rule-based stand-ins (test the plumbing) python desk.py NVDA # with an LLM (see env vars below) LLM settings (any OpenAI-compatible endpoint that supports the Responses API): xAI Grok : LLM_BASE_URL=https://api.x.ai/v1 LLM_API_KEY= LLM_MODEL=grok-4.3 Ollama : LLM_BASE_URL=http://localhost:11434/v1 LLM_API_KEY=ollama LLM_MODEL=qwen3.5:4b LLM_REASONING=none """ import argparse, json, math, os, re, sys, time from datetime import datetime, timezone from pathlib import Path LEDGER = Path("paper_ledger.json") TRACE = Path("desk_trace.json") STOP_FILE = Path("STOP") # create a file named STOP to freeze the desk # ---------- hard risk limits (code, not vibes) ---------- LIMITS = { "max_position_pct": 0.05, # never more than 5% of paper equity in one name "max_open_positions": 3, "max_annual_vol": 0.60, # skip names that move more than 60%/yr (20d realised) "min_confidence": 0.60, # boss must be at least this sure "min_crowd_agreement": 0.60, # at least 60% of the crowd must agree with the side "max_daily_loss_pct": 0.02, # stop for the day after -2% on the paper account } ROLES = { "watcher": "You are WATCHER on a research desk. You get price statistics for one stock. " "Describe the trend and momentum in 2 sentences. No predictions, no advice. " 'Reply JSON only: {"trend":"up|down|sideways","momentum":"strong|weak|neutral","note":"..."}', "hunter": "You are HUNTER. Using ONLY these rules: breakout = close within 2% of 20d high AND volume ratio > 1.3; " "pullback = uptrend AND RSI between 35 and 50; otherwise none. " 'Reply JSON only: {"setup":"breakout|pullback|none","side":"long|short|flat","why":"..."}', "news": "You are NEWS. Read the headlines and rate the tone for this stock from -1 (very negative) to 1 (very positive). " "Ignore hype words. If headlines are unrelated, say 0. " 'Reply JSON only: {"sentiment":0.0,"key_points":["...","..."]}', "flow": "You are FLOW. You do NOT see real institutional orders; you only see volume vs its 20-day average and the price move. " "Say whether volume confirms the move. " 'Reply JSON only: {"confirms":true,"note":"..."}', "crowd": "You are one of many small voters on a desk. Persona: {persona}. Given the desk notes, vote. " 'Reply JSON only: {"vote":"long|short|flat"}', "boss": "You are BOSS (portfolio manager). Combine the desk notes into ONE proposal. You may say HOLD. " "Confidence must be honest (0..1). " 'Reply JSON only: {"action":"BUY|SELL|HOLD","confidence":0.0,"thesis":"one sentence"}', "risk": "You are RISK. Your job is to find reasons NOT to trade. Be skeptical of the boss. " 'Reply JSON only: {"veto":true,"reason":"one sentence"}', } PERSONAS = ["trend follower", "mean-reversion skeptic", "news-driven trader", "value-minded analyst", "volatility-averse saver"] # ---------- data ---------- def get_market(ticker): import yfinance as yf t = yf.Ticker(ticker) h = t.history(period="6mo") if h.empty: sys.exit(f"no data for {ticker}") c, v = h["Close"], h["Volume"] rets = c.pct_change().dropna() delta = c.diff() gain = delta.clip(lower=0).rolling(14).mean(); loss = (-delta.clip(upper=0)).rolling(14).mean() rsi = 100 - 100 / (1 + gain.iloc[-1] / max(loss.iloc[-1], 1e-9)) f = { "ticker": ticker, "date": str(h.index[-1].date()), "close": round(float(c.iloc[-1]), 2), "chg_1d_pct": round(float(c.pct_change(1).iloc[-1] * 100), 2), "chg_5d_pct": round(float(c.pct_change(5).iloc[-1] * 100), 2), "chg_20d_pct": round(float(c.pct_change(20).iloc[-1] * 100), 2), "rsi14": round(float(rsi), 1), "high_20d": round(float(c.tail(20).max()), 2), "sma50": round(float(c.tail(50).mean()), 2), "vol_ratio": round(float(v.iloc[-1] / v.tail(20).mean()), 2), "annual_vol": round(float(rets.tail(20).std() * math.sqrt(252)), 3), } news = [] for n in (t.news or [])[:8]: c_ = n.get("content", n) news.append(c_.get("title", "")) return f, [x for x in news if x] # ---------- LLM ---------- def make_llm(offline): if offline: return None from openai import OpenAI key = os.getenv("LLM_API_KEY") or os.getenv("XAI_API_KEY") if not key: sys.exit("Set LLM_API_KEY (or XAI_API_KEY), or run with --offline") return OpenAI(api_key=key, base_url=os.getenv("LLM_BASE_URL", "https://api.x.ai/v1")) def ask(llm, role, payload, persona=None): system = ROLES[role].replace("{persona}", persona or "") if llm is None: return offline_answer(role, payload, persona) kw = {} if os.getenv("LLM_REASONING"): kw["reasoning"] = {"effort": os.getenv("LLM_REASONING")} text = json.dumps(payload, ensure_ascii=False) for attempt in range(2): # models sometimes break JSON: ask once more r = llm.responses.create(model=os.getenv("LLM_MODEL", "grok-4.3"), instructions=system, input=text, **kw) m = re.search(r"\{.*\}", r.output_text, re.S) try: return json.loads(m.group(0)) except (AttributeError, json.JSONDecodeError): text = text + "\n\nYour last reply was not valid JSON. Reply with valid JSON only." return {"error": "invalid JSON from model", "raw": r.output_text[:300]} def offline_answer(role, p, persona): """Rule-based stand-ins so the pipeline runs with no key. Not smart, on purpose.""" f = p.get("market", {}) up = f.get("close", 0) > f.get("sma50", 0) if role == "watcher": return {"trend": "up" if up else "down", "momentum": "strong" if abs(f.get("chg_20d_pct", 0)) > 8 else "neutral", "note": "offline"} if role == "hunter": if f.get("close", 0) >= f.get("high_20d", 1) * 0.98 and f.get("vol_ratio", 0) > 1.3: return {"setup": "breakout", "side": "long", "why": "near 20d high on volume"} if up and 35 <= f.get("rsi14", 50) <= 50: return {"setup": "pullback", "side": "long", "why": "uptrend dip"} return {"setup": "none", "side": "flat", "why": "no rule matched"} if role == "news": return {"sentiment": 0.0, "key_points": ["offline mode: headlines not scored"]} if role == "flow": return {"confirms": f.get("vol_ratio", 0) > 1.2, "note": "volume ratio rule"} if role == "crowd": side = p["notes"]["hunter"].get("side", "flat") return {"vote": side if persona != "volatility-averse saver" else "flat"} if role == "boss": side = p["notes"]["hunter"].get("side", "flat") act = {"long": "BUY", "short": "SELL"}.get(side, "HOLD") return {"action": act, "confidence": 0.65 if act != "HOLD" else 0.3, "thesis": "offline rule"} if role == "risk": return {"veto": False, "reason": "offline: hard rules only"} # ---------- paper ledger (fake money only) ---------- def load_ledger(): if LEDGER.exists(): return json.loads(LEDGER.read_text(encoding="utf-8")) return {"cash": 100_000.0, "positions": {}, "trades": [], "start_equity_today": 100_000.0} def equity(led, prices): return led["cash"] + sum(q * prices.get(t, 0) for t, q in led["positions"].items()) def hard_risk_checks(led, f, proposal, crowd_share): fails = [] eq = equity(led, {f["ticker"]: f["close"]}) if STOP_FILE.exists(): fails.append("STOP file present (kill switch)") if proposal.get("action") == "SELL" and f["ticker"] not in led["positions"]: fails.append("no short selling on this desk") if float(proposal.get("confidence", 0)) < LIMITS["min_confidence"]: fails.append("confidence below limit") if crowd_share < LIMITS["min_crowd_agreement"]: fails.append(f"crowd agreement {crowd_share:.0%} below limit") if f["annual_vol"] > LIMITS["max_annual_vol"]: fails.append(f"volatility {f['annual_vol']:.0%} above limit") if len(led["positions"]) >= LIMITS["max_open_positions"] and f["ticker"] not in led["positions"]: fails.append("too many open positions") if eq < led["start_equity_today"] * (1 - LIMITS["max_daily_loss_pct"]): fails.append("daily loss limit hit") return fails def paper_fill(led, f, action): px = f["close"]; t = f["ticker"] if action == "BUY": qty = math.floor(equity(led, {t: px}) * LIMITS["max_position_pct"] / px) led["cash"] -= qty * px; led["positions"][t] = led["positions"].get(t, 0) + qty else: qty = led["positions"].pop(t, 0); led["cash"] += qty * px led["trades"].append({"time": datetime.now(timezone.utc).isoformat(timespec="seconds"), "ticker": t, "action": action, "qty": qty, "price": px, "paper": True}) LEDGER.write_text(json.dumps(led, indent=2), encoding="utf-8") return qty # ---------- the desk ---------- def run(ticker, offline, crowd_n): llm = make_llm(offline) f, headlines = get_market(ticker) trace = [] def log(seat, out): trace.append({"seat": seat, "out": out}); print(f"[{seat.upper():7}] {json.dumps(out, ensure_ascii=False)}") print(f"=== {ticker} {f['date']} close {f['close']} (PAPER / EDUCATION ONLY) ===") notes = {} notes["watcher"] = ask(llm, "watcher", {"market": f}); log("watcher", notes["watcher"]) notes["hunter"] = ask(llm, "hunter", {"market": f}); log("hunter", notes["hunter"]) notes["news"] = ask(llm, "news", {"ticker": ticker, "headlines": headlines}); log("news", notes["news"]) notes["flow"] = ask(llm, "flow", {"market": f}); log("flow", notes["flow"]) votes = [ask(llm, "crowd", {"market": f, "notes": notes}, PERSONAS[i % len(PERSONAS)]).get("vote", "flat") for i in range(crowd_n)] notes["crowd"] = {"votes": votes}; log("crowd", notes["crowd"]) proposal = ask(llm, "boss", {"market": f, "notes": notes}); log("boss", proposal) side = {"BUY": "long", "SELL": "short"}.get(proposal.get("action"), "flat") crowd_share = votes.count(side) / max(len(votes), 1) led = load_ledger() if proposal.get("action") not in ("BUY", "SELL"): log("risk", {"veto": None, "note": "no proposal to check, boss said HOLD"}) print(">>> NO TRADE. Boss said HOLD.") TRACE.write_text(json.dumps({"market": f, "headlines": headlines, "trace": trace, "veto": None}, indent=2, ensure_ascii=False), encoding="utf-8") return fails = hard_risk_checks(led, f, proposal, crowd_share) skeptic = ask(llm, "risk", {"market": f, "notes": notes, "proposal": proposal, "hard_rule_fails": fails}) veto = bool(fails) or bool(skeptic.get("veto")) log("risk", {"veto": veto, "hard_rule_fails": fails, "skeptic": skeptic}) if veto: print(">>> RISK VETO. Nothing traded. (This is the desk working as designed.)") else: qty = paper_fill(led, f, proposal["action"]) print(f">>> PAPER {proposal['action']} {qty} {ticker} @ {f['close']} (fake money, ledger: {LEDGER})") TRACE.write_text(json.dumps({"market": f, "headlines": headlines, "trace": trace, "veto": veto}, indent=2, ensure_ascii=False), encoding="utf-8") if __name__ == "__main__": ap = argparse.ArgumentParser(description="7-seat AI research desk (paper trading only)") ap.add_argument("ticker"); ap.add_argument("--offline", action="store_true") ap.add_argument("--crowd", type=int, default=5, help="number of crowd voters (each one is an API call)") a = ap.parse_args() run(a.ticker.upper(), a.offline, a.crowd)