s-ttp commited on
Commit
83de142
·
verified ·
1 Parent(s): 4d4dd52

Upload folder using huggingface_hub

Browse files
Files changed (9) hide show
  1. app.py +6 -3
  2. src/market_data.py +31 -0
  3. src/metrics.py +68 -0
  4. src/orchestrator.py +130 -42
  5. src/personas.py +39 -13
  6. src/report.py +17 -0
  7. static/app.js +34 -3
  8. static/index.html +37 -0
  9. static/style.css +12 -0
app.py CHANGED
@@ -46,7 +46,7 @@ def _reserve_run() -> None:
46
  _day_count["n"] += 1
47
 
48
 
49
- def _worker(run_id: str, rows: list[dict]) -> None:
50
  run = _runs[run_id]
51
 
52
  def emit(pct: int, caption: str, chip: str | None = None) -> None:
@@ -54,7 +54,7 @@ def _worker(run_id: str, rows: list[dict]) -> None:
54
 
55
  with _run_lock:
56
  try:
57
- result = safe_run(rows, emit)
58
  run["result"] = result
59
  run["status"] = "done"
60
  run["queue"].put({"type": "done", "result": result})
@@ -70,6 +70,7 @@ class ResolveReq(BaseModel):
70
 
71
  class AnalyzeReq(BaseModel):
72
  rows: list[dict]
 
73
 
74
 
75
  @app.post("/api/resolve")
@@ -95,7 +96,9 @@ def api_analyze(req: AnalyzeReq):
95
  run_id = uuid.uuid4().hex[:12]
96
  _runs[run_id] = {"queue": queue.Queue(), "status": "running",
97
  "result": None, "started": time.time()}
98
- threading.Thread(target=_worker, args=(run_id, rows), daemon=True).start()
 
 
99
  # opportunistic cleanup of runs older than an hour
100
  cutoff = time.time() - 3600
101
  for rid in [r for r, v in _runs.items() if v["started"] < cutoff]:
 
46
  _day_count["n"] += 1
47
 
48
 
49
+ def _worker(run_id: str, rows: list[dict], context: dict | None) -> None:
50
  run = _runs[run_id]
51
 
52
  def emit(pct: int, caption: str, chip: str | None = None) -> None:
 
54
 
55
  with _run_lock:
56
  try:
57
+ result = safe_run(rows, emit, context)
58
  run["result"] = result
59
  run["status"] = "done"
60
  run["queue"].put({"type": "done", "result": result})
 
70
 
71
  class AnalyzeReq(BaseModel):
72
  rows: list[dict]
73
+ context: dict | None = None
74
 
75
 
76
  @app.post("/api/resolve")
 
96
  run_id = uuid.uuid4().hex[:12]
97
  _runs[run_id] = {"queue": queue.Queue(), "status": "running",
98
  "result": None, "started": time.time()}
99
+ allowed = {"horizon", "risk", "objective"}
100
+ context = {k: str(v)[:40] for k, v in (req.context or {}).items() if k in allowed and v}
101
+ threading.Thread(target=_worker, args=(run_id, rows, context or None), daemon=True).start()
102
  # opportunistic cleanup of runs older than an hour
103
  cutoff = time.time() - 3600
104
  for rid in [r for r, v in _runs.items() if v["started"] < cutoff]:
src/market_data.py CHANGED
@@ -141,6 +141,37 @@ def fx_to_usd(currency) -> float:
141
  return _fx_cache[cur]
142
 
143
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  # ---------------- per-holding fundamentals ----------------
145
 
146
  _YF_KEYS = {
 
141
  return _fx_cache[cur]
142
 
143
 
144
+ # ---------------- Slipstream smart-money candidates (13F + insider, quality-gated) ----------------
145
+
146
+ _slip_cache: dict | None = None
147
+
148
+
149
+ def load_slipstream() -> dict:
150
+ """{ticker: {sector, score, size}} — slipstream's quality-gated smart-money candidate
151
+ pool (13F superinvestor + insider accumulation, ROE/D-E gated). Local checkout first
152
+ (dev), then the s-ttp/slipstream Space repo. {} on any failure."""
153
+ global _slip_cache
154
+ if _slip_cache is not None:
155
+ return _slip_cache
156
+ _slip_cache = {}
157
+ try:
158
+ local = "/Users/sttp/Desktop/AI Projects/mitpoc/slipstream/data/candidates.parquet"
159
+ p = local if os.path.exists(local) else None
160
+ if not p:
161
+ from huggingface_hub import hf_hub_download
162
+ p = hf_hub_download("s-ttp/slipstream", "data/candidates.parquet",
163
+ repo_type="space", token=HF_TOKEN or None)
164
+ df = pd.read_parquet(p)
165
+ _slip_cache = {str(r["ticker"]).upper(): {"sector": r.get("sector"),
166
+ "score": float(r.get("score", 0)),
167
+ "size": r.get("size")}
168
+ for r in df.to_dict("records")}
169
+ print(f" slipstream candidates loaded: {len(_slip_cache)}", flush=True)
170
+ except Exception as e:
171
+ print(f" slipstream candidates unavailable ({type(e).__name__})", flush=True)
172
+ return _slip_cache
173
+
174
+
175
  # ---------------- per-holding fundamentals ----------------
176
 
177
  _YF_KEYS = {
src/metrics.py CHANGED
@@ -50,6 +50,74 @@ def dcf_from_assumptions(eps_base: float | None, price: float | None, A: dict |
50
  return pv, up, ke, A.get("lifecycle_stage")
51
 
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  def trap_flags(d: dict) -> list[str]:
54
  """Value-trap guards (crucible): deterioration, inorganic EPS, leverage-inflated ROE."""
55
  flags = []
 
50
  return pv, up, ke, A.get("lifecycle_stage")
51
 
52
 
53
+ def mechanical_assumptions(d: dict) -> dict:
54
+ """Crucible's fixed-DCF path as data-driven default assumptions — used when the
55
+ LLM-Damodaran call fails or is unavailable, so a positive-EPS name always gets an
56
+ intrinsic value. Growth from reported EPS/revenue growth (faded), ke from sector beta."""
57
+ def num(x, default):
58
+ return float(x) if isinstance(x, (int, float)) and x == x else default
59
+ g1 = num(d.get("eps_growth"), num(d.get("rev_growth"), 0.05))
60
+ roe = num(d.get("roe"), 0.15)
61
+ return {"lifecycle_stage": "mechanical",
62
+ "high_growth_rate": float(np.clip(g1, -0.30, 0.40)),
63
+ "high_growth_years": 5,
64
+ "terminal_growth": G_STABLE,
65
+ "cost_of_equity": RF + SECTOR_BETA.get(str(d.get("sector")), 1.0) * ERP,
66
+ "reinvestment_roic": float(np.clip(roe, 0.05, 0.40)),
67
+ "normalized_eps_factor": 1.0}
68
+
69
+
70
+ def waterfill(raw: dict, sect: dict, name_cap: float, sec_cap: float,
71
+ no_topup: frozenset = frozenset()) -> dict:
72
+ """Normalize raw>=0 into weights summing to 1 under joint per-name and per-sector caps
73
+ (crucible damodaran_portfolio._waterfill, pure port). Caps relax if infeasible for the
74
+ counts so the book is always fully invested. Names in `no_topup` keep their pro-rata
75
+ share but never receive overflow redistribution (e.g. committee-Trim names must not
76
+ grow just because everything else is capped)."""
77
+ tickers = list(raw)
78
+ groups: dict[str, list] = {}
79
+ for t in tickers:
80
+ groups.setdefault(sect.get(t, "?"), []).append(t)
81
+ name_cap = max(name_cap, 1.0 / max(len(tickers), 1) + 1e-9)
82
+ sec_cap = max(sec_cap, 1.0 / max(len(groups), 1) + 1e-9)
83
+ cap_of = lambda nc, sc: sum(min(sc, len(mem) * nc) for mem in groups.values())
84
+ while cap_of(name_cap, sec_cap) < 1.0 - 1e-9 and name_cap < 1.0:
85
+ name_cap = min(1.0, name_cap + 0.02)
86
+ sec_cap = min(1.0, sec_cap + 0.02)
87
+ tot = sum(raw.values())
88
+ if tot <= 0:
89
+ return {t: 0.0 for t in tickers}
90
+ w = {t: raw[t] / tot for t in tickers}
91
+ for _ in range(500):
92
+ excess = 0.0
93
+ for t in tickers:
94
+ if w[t] > name_cap + 1e-12:
95
+ excess += w[t] - name_cap
96
+ w[t] = name_cap
97
+ for mem in groups.values():
98
+ ssum = sum(w[t] for t in mem)
99
+ if ssum > sec_cap + 1e-12:
100
+ sc = sec_cap / ssum
101
+ for t in mem:
102
+ excess += w[t] * (1 - sc)
103
+ w[t] *= sc
104
+ if excess < 1e-9:
105
+ break
106
+ room = {}
107
+ for mem in groups.values():
108
+ sec_room = max(sec_cap - sum(w[t] for t in mem), 0.0)
109
+ for t in mem:
110
+ if t not in no_topup and min(name_cap - w[t], sec_room) > 1e-12:
111
+ room[t] = max(raw[t], 1e-9)
112
+ if not room:
113
+ break
114
+ rs = sum(room.values())
115
+ for t in room:
116
+ w[t] += excess * room[t] / rs
117
+ s = sum(w.values())
118
+ return {t: w[t] / s for t in w} if s > 0 else w
119
+
120
+
121
  def trap_flags(d: dict) -> list[str]:
122
  """Value-trap guards (crucible): deterioration, inorganic EPS, leverage-inflated ROE."""
123
  flags = []
src/orchestrator.py CHANGED
@@ -13,40 +13,98 @@ from . import metrics as M
13
  from . import personas as P
14
  from . import report as R
15
  from .llm import has_llm
16
- from .market_data import fact_sheet, fetch_all, fetch_history, fetch_news, load_panel
 
17
  from .portfolio import build_holdings
18
 
19
  CHIPS = ["value", "growth", "macro", "technical", "risk", "cio"]
20
 
21
 
22
  def _alt_candidates(holdings: list[dict], gaps: list[str]) -> list[dict]:
23
- """Alternatives candidate pool from the MarketFM panel: top-decile names not already held,
24
- ≤2/sector (slipstream diversity rule), gap sectors first. [] when the panel is absent —
25
- the CIO then returns no alternatives rather than inventing tickers."""
26
- panel = load_panel()
27
- if not panel:
28
- return []
 
29
  held = {h["symbol"] for h in holdings}
30
- rows = [{"ticker": t, **v} for t, v in panel.items()
31
- if t not in held and isinstance(v.get("xs_rank_pct"), (int, float))]
32
- rows.sort(key=lambda r: -(r["xs_rank_pct"] or 0))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  gap_l = [g.lower() for g in gaps]
34
- rows.sort(key=lambda r: 0 if any(g in str(r.get("sector", "")).lower() for g in gap_l) else 1)
 
35
  picks, per_sec = [], {}
36
  for r in rows:
37
- s = str(r.get("sector", "?"))
38
  if per_sec.get(s, 0) >= 2:
39
  continue
40
  per_sec[s] = per_sec.get(s, 0) + 1
41
- picks.append({"ticker": r["ticker"], "sector": s,
42
- "rank_pct": round(float(r["xs_rank_pct"]), 2),
43
- "pred_excess_12m": r.get("pred_excess_12m")})
44
  if len(picks) >= 12:
45
  break
46
  return picks
47
 
48
 
49
- def run_analysis(rows: list[dict], emit) -> dict:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  # 1 — resolve + validate
51
  emit(3, "Resolving your holdings…")
52
  holdings, errors = build_holdings(rows)
@@ -72,27 +130,28 @@ def run_analysis(rows: list[dict], emit) -> dict:
72
  pm = M.portfolio_metrics(holdings, hist)
73
  cards = M.risk_scorecard(pm)
74
 
75
- # 4 — Damodaran DCF
76
- dcfs: dict[str, dict] = {}
77
- if has_llm():
78
- emit(36, "Estimating intrinsic value (Damodaran DCF)…")
79
- assumptions = P.damodaran_assumptions(holdings)
80
- for h in holdings:
81
- d, t = h["data"], h["symbol"]
82
- iv, up, ke, stage = M.dcf_from_assumptions(d.get("eps_ttm"), d.get("price"),
83
- assumptions.get(t))
84
- flags = M.trap_flags(d)
85
- if iv == iv: # not NaN
86
- dcfs[t] = {"intrinsic": round(iv, 2), "upside": round(up, 4),
87
- "upside_vs_entry": round(iv / h["entry"] - 1, 4),
88
- "ke": round(ke, 4), "lifecycle": stage, "flags": flags}
89
- elif flags:
90
- dcfs[t] = {"intrinsic": None, "upside": None, "upside_vs_entry": None,
91
- "ke": None, "lifecycle": stage, "flags": flags}
92
- h["dcf"] = dcfs.get(t, {})
93
- else:
94
- for h in holdings:
95
- h["dcf"] = {"flags": M.trap_flags(h["data"])}
 
96
 
97
  # 5 — persona panel (batched, concurrent)
98
  panel: dict[str, dict] = {}
@@ -101,7 +160,7 @@ def run_analysis(rows: list[dict], emit) -> dict:
101
  briefs = {h["symbol"]: fact_sheet(h["data"], h, news[h["symbol"]], h.get("dcf"))
102
  for h in holdings}
103
  regime = pm.get("regime_risk_on")
104
- context = (f"{n} holdings, {'equal-weighted (no quantities given)' if pm['equal_weighted'] else 'value-weighted'}. "
105
  f"Sector mix: " + ", ".join(f"{s} {w * 100:.0f}%" for s, w in
106
  list(pm["sector_allocation"].items())[:6]) + ". "
107
  f"Market regime: {'risk-on (S&P above 200-day)' if regime else 'risk-off (S&P below 200-day)' if regime is not None else 'unknown'}. "
@@ -113,7 +172,7 @@ def run_analysis(rows: list[dict], emit) -> dict:
113
  emit(45 + 5 * len(done_chips), f"Deliberation: {len(done_chips)}/5 analysts have ruled…",
114
  chip=k if ok else None)
115
 
116
- panel = P.run_panel(briefs, context, progress=chip_progress)
117
 
118
  # 6 — deterministic actions (validator owns this, not the LLM)
119
  emit(72, "Stress-testing portfolio concentration and strategy…")
@@ -130,10 +189,12 @@ def run_analysis(rows: list[dict], emit) -> dict:
130
  "risk_scorecard": cards,
131
  "healthy_bands": {"per_name_cap": M.MAX_POS_W,
132
  "sector_band": [M.SECTOR_CAP_LO, M.SECTOR_CAP_HI]},
 
133
  })
134
 
135
  # 8 — CIO synthesis + alternatives
136
  cio = None
 
137
  if has_llm():
138
  emit(84, "The Chief Investment Officer drafts the verdict…", chip="cio")
139
  gaps = (strat or {}).get("gaps") or []
@@ -150,18 +211,45 @@ def run_analysis(rows: list[dict], emit) -> dict:
150
  "strategist": strat, "risk_scorecard": cards,
151
  "metrics": {k: v for k, v in pm.items() if k != "equity_curve"},
152
  "alternative_candidates": candidates,
 
153
  })
154
 
155
- # 9 — assemble
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  emit(94, "Sealing the verdict…")
157
  result = R.assemble(holdings, pm, cards, decisions, panel, strat, cio, errors)
 
 
 
 
 
 
 
158
  emit(100, "Done.")
159
  return result
160
 
161
 
162
- def safe_run(rows: list[dict], emit) -> dict:
163
  try:
164
- return run_analysis(rows, emit)
165
  except ValueError:
166
  raise
167
  except Exception:
 
13
  from . import personas as P
14
  from . import report as R
15
  from .llm import has_llm
16
+ from .market_data import (fact_sheet, fetch_all, fetch_history, fetch_news,
17
+ load_panel, load_slipstream)
18
  from .portfolio import build_holdings
19
 
20
  CHIPS = ["value", "growth", "macro", "technical", "risk", "cio"]
21
 
22
 
23
  def _alt_candidates(holdings: list[dict], gaps: list[str]) -> list[dict]:
24
+ """Equity alternatives pool cued from the existing portfolio, merged from two signals:
25
+ - MarketFM panel: factor-composite rank + ML-predicted 12m excess return
26
+ - Slipstream: 13F superinvestor + insider accumulation, quality-gated (ROE/D-E)
27
+ Names on both lists are boosted. Held names excluded, ≤2/sector, sectors the
28
+ strategist flagged as portfolio gaps come first. [] when neither source is
29
+ available — the CIO then returns no alternatives rather than inventing tickers."""
30
+ panel, slip = load_panel(), load_slipstream()
31
  held = {h["symbol"] for h in holdings}
32
+ merged: dict[str, dict] = {}
33
+ for t, v in panel.items():
34
+ if t in held or not isinstance(v.get("xs_rank_pct"), (int, float)):
35
+ continue
36
+ merged[t] = {"ticker": t, "sector": str(v.get("sector") or "?"),
37
+ "strength": float(v["xs_rank_pct"]) / 100.0,
38
+ "rank_pct": round(float(v["xs_rank_pct"]), 1),
39
+ "pred_excess_12m": v.get("pred_excess_12m"),
40
+ "signals": ["quant factor rank"]}
41
+ if slip:
42
+ scores = sorted(x["score"] for x in slip.values())
43
+ for t, v in slip.items():
44
+ if t in held:
45
+ continue
46
+ pct = scores.index(v["score"]) / max(len(scores) - 1, 1) # percentile of smart-money score
47
+ if t in merged:
48
+ merged[t]["strength"] = max(merged[t]["strength"], pct) + 0.15 # both signals agree
49
+ merged[t]["signals"].append("smart-money accumulation (13F+insider)")
50
+ else:
51
+ merged[t] = {"ticker": t, "sector": str(v.get("sector") or "?"),
52
+ "strength": pct, "signals": ["smart-money accumulation (13F+insider)"]}
53
+ rows = sorted(merged.values(), key=lambda r: -r["strength"])
54
  gap_l = [g.lower() for g in gaps]
55
+ rows.sort(key=lambda r: 0 if any(g in r["sector"].lower() or r["sector"].lower() in g
56
+ for g in gap_l) else 1)
57
  picks, per_sec = [], {}
58
  for r in rows:
59
+ s = r["sector"]
60
  if per_sec.get(s, 0) >= 2:
61
  continue
62
  per_sec[s] = per_sec.get(s, 0) + 1
63
+ picks.append({k: v for k, v in r.items() if k != "strength"})
 
 
64
  if len(picks) >= 12:
65
  break
66
  return picks
67
 
68
 
69
+ _RISK_CAPS = {"conservative": (0.10, 0.25), "balanced": (0.12, 0.30), "aggressive": (0.15, 0.40)}
70
+
71
+
72
+ def _target_portfolio(holdings, decisions, alternatives, context) -> list[dict]:
73
+ """Deterministic recommended target book (only when the user gave context):
74
+ current weights × conviction multiplier (Sell → 0), CIO alternatives seeded as
75
+ starter positions, then crucible's waterfill under risk-profile name/sector caps."""
76
+ name_cap, sec_cap = _RISK_CAPS.get(str(context.get("risk")), _RISK_CAPS["balanced"])
77
+ raw, sect = {}, {}
78
+ kept = [h for h in holdings if decisions[h["symbol"]]["action"] != "Sell"]
79
+ if not kept:
80
+ return []
81
+ for h in kept:
82
+ t = h["symbol"]
83
+ conv = decisions[t]["conviction"]
84
+ raw[t] = h["weight"] * float(min(max(0.5 + conv / 100.0, 0.5), 1.5))
85
+ sect[t] = str(h["data"].get("sector") or "?")
86
+ starter = (sum(h["weight"] for h in kept) / len(kept)) * 0.8
87
+ for a in alternatives:
88
+ t = a["ticker"]
89
+ if t not in raw:
90
+ raw[t] = starter
91
+ sect[t] = str(a.get("sector") or "?")
92
+ trims = frozenset(h["symbol"] for h in kept if decisions[h["symbol"]]["action"] == "Trim")
93
+ w = M.waterfill(raw, sect, name_cap, sec_cap, no_topup=trims)
94
+ cur = {h["symbol"]: h["weight"] for h in holdings}
95
+ rows = [{"ticker": t, "sector": sect[t], "current_w": round(cur.get(t, 0.0), 4),
96
+ "target_w": round(tw, 4), "delta": round(tw - cur.get(t, 0.0), 4),
97
+ "is_new": t not in cur} for t, tw in w.items()]
98
+ rows += [{"ticker": h["symbol"], "sector": str(h["data"].get("sector") or "?"),
99
+ "current_w": round(h["weight"], 4), "target_w": 0.0,
100
+ "delta": round(-h["weight"], 4), "is_new": False}
101
+ for h in holdings if decisions[h["symbol"]]["action"] == "Sell"]
102
+ rows.sort(key=lambda r: -r["target_w"])
103
+ return rows
104
+
105
+
106
+ def run_analysis(rows: list[dict], emit, context: dict | None = None) -> dict:
107
+ context = {k: v for k, v in (context or {}).items() if v} or None
108
  # 1 — resolve + validate
109
  emit(3, "Resolving your holdings…")
110
  holdings, errors = build_holdings(rows)
 
130
  pm = M.portfolio_metrics(holdings, hist)
131
  cards = M.risk_scorecard(pm)
132
 
133
+ # 4 — Damodaran DCF: LLM sets lifecycle assumptions when available; the mechanical
134
+ # data-driven assumptions guarantee every positive-EPS name gets an intrinsic value.
135
+ emit(36, "Estimating intrinsic value (Damodaran DCF)…")
136
+ assumptions = P.damodaran_assumptions(holdings) if has_llm() else {}
137
+ for h in holdings:
138
+ d, t = h["data"], h["symbol"]
139
+ eps = d.get("eps_ttm")
140
+ flags = M.trap_flags(d)
141
+ h["dcf"] = {"flags": flags} if flags else {}
142
+ if not isinstance(eps, (int, float)) or eps != eps or eps <= 0:
143
+ continue # no positive EPS — a DCF would be meaningless; column shows n/a
144
+ A, src = assumptions.get(t), "ai"
145
+ if not isinstance(A, dict):
146
+ A, src = M.mechanical_assumptions(d), "mechanical"
147
+ iv, up, ke, stage = M.dcf_from_assumptions(eps, d.get("price"), A)
148
+ if iv != iv: # NaN (degenerate assumptions) — retry on the mechanical path
149
+ A, src = M.mechanical_assumptions(d), "mechanical"
150
+ iv, up, ke, stage = M.dcf_from_assumptions(eps, d.get("price"), A)
151
+ if iv == iv:
152
+ h["dcf"] = {"intrinsic": round(iv, 2), "upside": round(up, 4),
153
+ "upside_vs_entry": round(iv / h["entry"] - 1, 4),
154
+ "ke": round(ke, 4), "lifecycle": stage, "src": src, "flags": flags}
155
 
156
  # 5 — persona panel (batched, concurrent)
157
  panel: dict[str, dict] = {}
 
160
  briefs = {h["symbol"]: fact_sheet(h["data"], h, news[h["symbol"]], h.get("dcf"))
161
  for h in holdings}
162
  regime = pm.get("regime_risk_on")
163
+ panel_ctx = (f"{n} holdings, {'equal-weighted (no quantities given)' if pm['equal_weighted'] else 'value-weighted'}. "
164
  f"Sector mix: " + ", ".join(f"{s} {w * 100:.0f}%" for s, w in
165
  list(pm["sector_allocation"].items())[:6]) + ". "
166
  f"Market regime: {'risk-on (S&P above 200-day)' if regime else 'risk-off (S&P below 200-day)' if regime is not None else 'unknown'}. "
 
172
  emit(45 + 5 * len(done_chips), f"Deliberation: {len(done_chips)}/5 analysts have ruled…",
173
  chip=k if ok else None)
174
 
175
+ panel = P.run_panel(briefs, panel_ctx, progress=chip_progress)
176
 
177
  # 6 — deterministic actions (validator owns this, not the LLM)
178
  emit(72, "Stress-testing portfolio concentration and strategy…")
 
189
  "risk_scorecard": cards,
190
  "healthy_bands": {"per_name_cap": M.MAX_POS_W,
191
  "sector_band": [M.SECTOR_CAP_LO, M.SECTOR_CAP_HI]},
192
+ "investor_context": context or "not provided — judge the portfolio on its own terms",
193
  })
194
 
195
  # 8 — CIO synthesis + alternatives
196
  cio = None
197
+ candidates: list[dict] = []
198
  if has_llm():
199
  emit(84, "The Chief Investment Officer drafts the verdict…", chip="cio")
200
  gaps = (strat or {}).get("gaps") or []
 
211
  "strategist": strat, "risk_scorecard": cards,
212
  "metrics": {k: v for k, v in pm.items() if k != "equity_curve"},
213
  "alternative_candidates": candidates,
214
+ "investor_context": context or "not provided",
215
  })
216
 
217
+ # 9 — recommended target portfolio (only when the user shared their context)
218
+ target = None
219
+ if context:
220
+ alts = [a for a in (cio or {}).get("alternatives", []) if isinstance(a, dict)]
221
+ alt_meta = {c["ticker"]: c for c in candidates}
222
+ chosen = [alt_meta.get(str(a.get("ticker", "")).upper(),
223
+ {"ticker": str(a.get("ticker", "")).upper()})
224
+ for a in alts if a.get("ticker")]
225
+ # top up to >=3 new names straight from the ranked pool: without fresh names the
226
+ # cap overflow from a concentrated book would inflate tiny existing positions
227
+ have = {c["ticker"] for c in chosen}
228
+ for c in candidates:
229
+ if len(chosen) >= 3:
230
+ break
231
+ if c["ticker"] not in have:
232
+ chosen.append(c)
233
+ have.add(c["ticker"])
234
+ target = _target_portfolio(holdings, decisions, chosen, context)
235
+
236
+ # 10 — assemble
237
  emit(94, "Sealing the verdict…")
238
  result = R.assemble(holdings, pm, cards, decisions, panel, strat, cio, errors)
239
+ sig_meta = {c["ticker"]: c.get("signals", []) for c in candidates}
240
+ for a in result["alternatives"]:
241
+ a["signals"] = sig_meta.get(a["ticker"], [])
242
+ result["context"] = context
243
+ result["target_portfolio"] = target
244
+ if target:
245
+ result["report_md"] = R.append_target_md(result["report_md"], target, context)
246
  emit(100, "Done.")
247
  return result
248
 
249
 
250
+ def safe_run(rows: list[dict], emit, context: dict | None = None) -> dict:
251
  try:
252
+ return run_analysis(rows, emit, context)
253
  except ValueError:
254
  raise
255
  except Exception:
src/personas.py CHANGED
@@ -110,7 +110,9 @@ _STRATEGIST_SYSTEM = (
110
  "under-concentration vs the healthy bands given, style tilt (value vs growth vs momentum), "
111
  "correlated-risk clusters (treat the computed correlation pairs as fact), missing exposures "
112
  "(sectors/geographies/asset classes absent), and whether the collection reads as a coherent "
113
- "strategy or an accumulation of ideas. Plain English, no jargon; every claim cites a number "
 
 
114
  "from the data. Respond ONLY with JSON: {"
115
  '"strategy_read": "<2-3 sentences: what strategy this portfolio implies>", '
116
  '"style_tilt": "<one short phrase>", '
@@ -133,8 +135,11 @@ _CIO_SYSTEM = (
133
  "3) rationale: for EACH holding, ONE plain-English sentence justifying its given action, "
134
  "reflecting the committee's consensus or naming the dissent.\n"
135
  "4) alternatives: pick 2-4 tickers ONLY from the provided candidate list that best fill the "
136
- "strategist's gaps; for each, one sentence framed as gap-filling (never as a hot tip). If the "
137
- "candidate list is empty, return [].\n"
 
 
 
138
  'Respond ONLY with JSON: {"verdict": "<one sentence>", '
139
  '"highlights": [{"severity": "good|warn|bad", "title": "<=10 words", '
140
  '"detail": "<1-2 sentences with a number>", "lens": "<value|growth|macro|technical|risk|portfolio>"}], '
@@ -152,8 +157,14 @@ def _batched_scores(persona_key: str, briefs: dict[str, str], context: str) -> d
152
  blocks = "\n\n".join(f"=== {t} ===\n{b}" for t, b in briefs.items())
153
  user = (f"PORTFOLIO CONTEXT:\n{context}\n\nHOLDINGS TO SCORE "
154
  f"({', '.join(briefs)}):\n\n{blocks}\n\nJSON only, every ticker covered.")
155
- out = parse_json(call_llm(p["system"], user, max_tokens=350 + 220 * len(briefs),
156
- prefer=p.get("provider"))) or {}
 
 
 
 
 
 
157
  clean = {}
158
  for t in briefs:
159
  v = out.get(t) or out.get(t.upper()) or {}
@@ -202,22 +213,37 @@ def damodaran_assumptions(holdings: list[dict]) -> dict:
202
  lines.append(" | ".join(row))
203
  if not lines:
204
  return {}
205
- user = "COMPANIES:\n" + "\n".join(lines) + "\n\nJSON only, every ticker."
206
- for attempt in range(2): # a truncated/malformed reply costs the whole DCF stage — retry once
207
- out = parse_json(call_llm(_DAMODARAN_SYSTEM, user, max_tokens=500 + 250 * len(lines)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
  if isinstance(out, dict) and out:
209
  return out
210
- print(f" damodaran assumptions unparseable (attempt {attempt + 1})", flush=True)
211
- return {}
212
 
213
 
214
  def strategist_review(payload: dict) -> dict | None:
215
- return parse_json(call_llm(_STRATEGIST_SYSTEM, json.dumps(payload, default=str),
216
- max_tokens=1600))
217
 
218
 
219
  def cio_synthesis(payload: dict) -> dict | None:
220
- return parse_json(call_llm(_CIO_SYSTEM, json.dumps(payload, default=str), max_tokens=2400))
 
221
 
222
 
223
  # ---------------- deterministic validator — conviction medians → actions ----------------
 
110
  "under-concentration vs the healthy bands given, style tilt (value vs growth vs momentum), "
111
  "correlated-risk clusters (treat the computed correlation pairs as fact), missing exposures "
112
  "(sectors/geographies/asset classes absent), and whether the collection reads as a coherent "
113
+ "strategy or an accumulation of ideas. If investor_context is provided (horizon, risk "
114
+ "appetite, objective), judge fit against it — e.g. a high-beta book vs a conservative, "
115
+ "short-horizon investor. Plain English, no jargon; every claim cites a number "
116
  "from the data. Respond ONLY with JSON: {"
117
  '"strategy_read": "<2-3 sentences: what strategy this portfolio implies>", '
118
  '"style_tilt": "<one short phrase>", '
 
135
  "3) rationale: for EACH holding, ONE plain-English sentence justifying its given action, "
136
  "reflecting the committee's consensus or naming the dissent.\n"
137
  "4) alternatives: pick 2-4 tickers ONLY from the provided candidate list that best fill the "
138
+ "strategist's gaps and complement the existing holdings; each candidate carries its backing "
139
+ "signals (quant factor rank and/or smart-money 13F+insider accumulation) — cite the signal in "
140
+ "your one-sentence reason, framed as gap-filling (never as a hot tip). If investor_context is "
141
+ "provided, respect it (e.g. lower-beta, dividend-paying picks for a conservative income "
142
+ "investor). If the candidate list is empty, return [].\n"
143
  'Respond ONLY with JSON: {"verdict": "<one sentence>", '
144
  '"highlights": [{"severity": "good|warn|bad", "title": "<=10 words", '
145
  '"detail": "<1-2 sentences with a number>", "lens": "<value|growth|macro|technical|risk|portfolio>"}], '
 
157
  blocks = "\n\n".join(f"=== {t} ===\n{b}" for t, b in briefs.items())
158
  user = (f"PORTFOLIO CONTEXT:\n{context}\n\nHOLDINGS TO SCORE "
159
  f"({', '.join(briefs)}):\n\n{blocks}\n\nJSON only, every ticker covered.")
160
+ out = {}
161
+ for attempt in range(2): # truncated/unparseable JSON silently loses a whole lens — retry once
162
+ out = parse_json(call_llm(p["system"], user, max_tokens=700 + 320 * len(briefs),
163
+ prefer=p.get("provider")))
164
+ if isinstance(out, dict) and out:
165
+ break
166
+ print(f" persona {persona_key} reply unparseable (attempt {attempt + 1})", flush=True)
167
+ out = {}
168
  clean = {}
169
  for t in briefs:
170
  v = out.get(t) or out.get(t.upper()) or {}
 
213
  lines.append(" | ".join(row))
214
  if not lines:
215
  return {}
216
+ # chunks of 6: one truncated/malformed reply then costs at most 6 names, and each
217
+ # chunk retries once; anything still missing falls back to mechanical assumptions.
218
+ out: dict = {}
219
+ for i in range(0, len(lines), 6):
220
+ chunk = lines[i:i + 6]
221
+ user = "COMPANIES:\n" + "\n".join(chunk) + "\n\nJSON only, every ticker."
222
+ for attempt in range(2):
223
+ got = parse_json(call_llm(_DAMODARAN_SYSTEM, user, max_tokens=500 + 250 * len(chunk)))
224
+ if isinstance(got, dict) and got:
225
+ out.update(got)
226
+ break
227
+ print(f" damodaran chunk {i // 6} unparseable (attempt {attempt + 1})", flush=True)
228
+ return out
229
+
230
+
231
+ def _call_and_parse(system: str, payload: dict, max_tokens: int, label: str) -> dict | None:
232
+ for attempt in range(2):
233
+ out = parse_json(call_llm(system, json.dumps(payload, default=str), max_tokens=max_tokens))
234
  if isinstance(out, dict) and out:
235
  return out
236
+ print(f" {label} reply unparseable (attempt {attempt + 1})", flush=True)
237
+ return None
238
 
239
 
240
  def strategist_review(payload: dict) -> dict | None:
241
+ return _call_and_parse(_STRATEGIST_SYSTEM, payload, 2000, "strategist")
 
242
 
243
 
244
  def cio_synthesis(payload: dict) -> dict | None:
245
+ n = len(payload.get("holdings", []))
246
+ return _call_and_parse(_CIO_SYSTEM, payload, 1800 + 300 * n, "cio")
247
 
248
 
249
  # ---------------- deterministic validator — conviction medians → actions ----------------
src/report.py CHANGED
@@ -152,3 +152,20 @@ def _markdown(res: dict, panel: dict) -> str:
152
  + (f" — *risk: {v['key_risk']}*" if v.get("key_risk") else ""))
153
  L += ["", "---", f"*{res['disclaimer']}*"]
154
  return "\n".join(L)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  + (f" — *risk: {v['key_risk']}*" if v.get("key_risk") else ""))
153
  L += ["", "---", f"*{res['disclaimer']}*"]
154
  return "\n".join(L)
155
+
156
+
157
+ _CTX_LABELS = {"horizon": "Investment horizon", "risk": "Risk appetite", "objective": "Objective"}
158
+
159
+
160
+ def append_target_md(md: str, target: list[dict], context: dict) -> str:
161
+ L = [md, "", "## Recommended target portfolio",
162
+ "*Based on your context: " + "; ".join(
163
+ f"{_CTX_LABELS.get(k, k)}: {v}" for k, v in context.items() if v) + ".*",
164
+ "*Deterministic construction: committee conviction sizes positions under "
165
+ "risk-profile name/sector caps. Educational illustration, not advice.*", "",
166
+ "| Holding | Current | Target | Change |", "|---|---|---|---|"]
167
+ for r in target:
168
+ tag = " *(new)*" if r["is_new"] else ""
169
+ L.append(f"| {r['ticker']}{tag} | {r['current_w'] * 100:.1f}% | {r['target_w'] * 100:.1f}% "
170
+ f"| {r['delta'] * 100:+.1f}pp |")
171
+ return "\n".join(L)
static/app.js CHANGED
@@ -76,11 +76,16 @@ $("#analyze").onclick = async () => {
76
  const errEl = $("#input-error"); errEl.hidden = true;
77
  if (!rows.length) { errEl.hidden = false; errEl.textContent = "Add at least one holding."; return; }
78
  if (rows.some(r => !r.entry)) { errEl.hidden = false; errEl.textContent = "Every holding needs an entry price."; return; }
 
 
 
 
 
79
  let resp;
80
  try {
81
  resp = await fetch("/api/analyze", {
82
  method: "POST", headers: { "Content-Type": "application/json" },
83
- body: JSON.stringify({ rows }),
84
  });
85
  } catch { errEl.hidden = false; errEl.textContent = "Could not reach the server."; return; }
86
  if (!resp.ok) {
@@ -174,11 +179,37 @@ function renderResults(R) {
174
  `<b>Strategy read:</b> ${esc(st.strategy_read)}` +
175
  (st.style_tilt ? ` <b>Style:</b> ${esc(st.style_tilt)}.` : "") +
176
  (st.gaps && st.gaps.length ? ` <b>Missing exposure:</b> ${esc(st.gaps.join(", "))}.` : "");
177
- // alternatives
178
  const alts = R.alternatives || [];
179
  $("#alt-section").hidden = !alts.length;
180
  const av = $("#alternatives"); av.innerHTML = "";
181
- for (const a of alts) av.appendChild(el("div", "alt", `<b>${esc(a.ticker)}</b><p>${esc(a.reason)}</p>`));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  // footer
183
  $("#download").href = "/api/report/" + currentRun;
184
  $("#meta").textContent = `Generated ${R.generated_at}` +
 
76
  const errEl = $("#input-error"); errEl.hidden = true;
77
  if (!rows.length) { errEl.hidden = false; errEl.textContent = "Add at least one holding."; return; }
78
  if (rows.some(r => !r.entry)) { errEl.hidden = false; errEl.textContent = "Every holding needs an entry price."; return; }
79
+ const context = {
80
+ horizon: $("#ctx-horizon").value || null,
81
+ risk: $("#ctx-risk").value || null,
82
+ objective: $("#ctx-objective").value || null,
83
+ };
84
  let resp;
85
  try {
86
  resp = await fetch("/api/analyze", {
87
  method: "POST", headers: { "Content-Type": "application/json" },
88
+ body: JSON.stringify({ rows, context }),
89
  });
90
  } catch { errEl.hidden = false; errEl.textContent = "Could not reach the server."; return; }
91
  if (!resp.ok) {
 
179
  `<b>Strategy read:</b> ${esc(st.strategy_read)}` +
180
  (st.style_tilt ? ` <b>Style:</b> ${esc(st.style_tilt)}.` : "") +
181
  (st.gaps && st.gaps.length ? ` <b>Missing exposure:</b> ${esc(st.gaps.join(", "))}.` : "");
182
+ // alternatives (signal tags show which engine surfaced each pick)
183
  const alts = R.alternatives || [];
184
  $("#alt-section").hidden = !alts.length;
185
  const av = $("#alternatives"); av.innerHTML = "";
186
+ for (const a of alts) {
187
+ const tags = (a.signals || []).map(s =>
188
+ `<span class="sig">${esc(s.includes("smart") ? "🐋 smart money" : "🧮 quant rank")}</span>`).join(" ");
189
+ av.appendChild(el("div", "alt", `<b>${esc(a.ticker)}</b> ${tags}<p>${esc(a.reason)}</p>`));
190
+ }
191
+ // recommended target portfolio (only when the user gave context)
192
+ const target = R.target_portfolio || [];
193
+ $("#target-section").hidden = !target.length;
194
+ if (target.length) {
195
+ const ctx = R.context || {};
196
+ $("#target-note").textContent =
197
+ `Built for: ${[ctx.horizon, ctx.risk, ctx.objective].filter(Boolean).join(" · ")} — ` +
198
+ `committee conviction sizes positions under risk-profile caps. Educational illustration, not advice.`;
199
+ const tb = $("#target-body"); tb.innerHTML = "";
200
+ for (const r of target) {
201
+ const d = r.delta;
202
+ const dCls = d > 0.005 ? "up" : d < -0.005 ? "dn" : "";
203
+ const tr = el("tr");
204
+ tr.innerHTML = `
205
+ <td class="tick"><b>${esc(r.ticker)}</b>${r.is_new ? ' <span class="badge buy">New</span>' : ""}</td>
206
+ <td class="why">${esc(r.sector)}</td>
207
+ <td>${pct(r.current_w, false)}</td>
208
+ <td><b>${pct(r.target_w, false)}</b></td>
209
+ <td class="${dCls}">${d > 0 ? "▲" : d < 0 ? "▼" : "·"} ${pct(Math.abs(d), false)}</td>`;
210
+ tb.appendChild(tr);
211
+ }
212
+ }
213
  // footer
214
  $("#download").href = "/api/report/" + currentRun;
215
  $("#meta").textContent = `Generated ${R.generated_at}` +
static/index.html CHANGED
@@ -43,6 +43,32 @@
43
  <button class="ghost" id="add-row">+ Add holding</button>
44
  <button class="ghost" id="load-sample">Load sample portfolio</button>
45
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  <button id="analyze" class="primary">Convene the conclave</button>
47
  <div class="microcopy">Five AI analysts across Claude, GPT &amp; Gemini + Damodaran valuation · verdict in ~90 seconds</div>
48
  <div id="input-error" class="input-error" hidden></div>
@@ -127,6 +153,17 @@
127
  <div id="alternatives" class="alt-cards"></div>
128
  </section>
129
 
 
 
 
 
 
 
 
 
 
 
 
130
  <footer class="card footer">
131
  <div class="footer-actions">
132
  <a id="download" class="primary" href="#" download>Download full report</a>
 
43
  <button class="ghost" id="add-row">+ Add holding</button>
44
  <button class="ghost" id="load-sample">Load sample portfolio</button>
45
  </div>
46
+ <details class="ctx" id="ctx-panel">
47
+ <summary>Optional — tell the conclave about yourself, and it will also draft a <b>recommended target portfolio</b></summary>
48
+ <div class="ctx-grid">
49
+ <label>Investment horizon
50
+ <select id="ctx-horizon">
51
+ <option value="">—</option>
52
+ <option value="under 3 years">Under 3 years</option>
53
+ <option value="3-7 years">3–7 years</option>
54
+ <option value="7+ years">7+ years</option>
55
+ </select></label>
56
+ <label>Risk appetite
57
+ <select id="ctx-risk">
58
+ <option value="">—</option>
59
+ <option value="conservative">Conservative</option>
60
+ <option value="balanced">Balanced</option>
61
+ <option value="aggressive">Aggressive</option>
62
+ </select></label>
63
+ <label>Objective
64
+ <select id="ctx-objective">
65
+ <option value="">—</option>
66
+ <option value="growth">Growth</option>
67
+ <option value="income">Income</option>
68
+ <option value="balanced growth and income">Growth + income</option>
69
+ </select></label>
70
+ </div>
71
+ </details>
72
  <button id="analyze" class="primary">Convene the conclave</button>
73
  <div class="microcopy">Five AI analysts across Claude, GPT &amp; Gemini + Damodaran valuation · verdict in ~90 seconds</div>
74
  <div id="input-error" class="input-error" hidden></div>
 
153
  <div id="alternatives" class="alt-cards"></div>
154
  </section>
155
 
156
+ <section class="card" id="target-section" hidden>
157
+ <h2>Recommended target portfolio</h2>
158
+ <div id="target-note" class="hint" style="margin:0 0 12px"></div>
159
+ <div class="table-scroll">
160
+ <table id="target-table">
161
+ <thead><tr><th>Holding</th><th>Sector</th><th>Current</th><th>Target</th><th>Change</th></tr></thead>
162
+ <tbody id="target-body"></tbody>
163
+ </table>
164
+ </div>
165
+ </section>
166
+
167
  <footer class="card footer">
168
  <div class="footer-actions">
169
  <a id="download" class="primary" href="#" download>Download full report</a>
static/style.css CHANGED
@@ -54,6 +54,18 @@ button, .primary { font: inherit; cursor: pointer; border-radius: 10px; }
54
  .rm:hover { color: var(--bad); }
55
  .row-actions { display: flex; gap: 10px; margin-bottom: 20px; }
56
  .microcopy { color: var(--dim); font-size: .82rem; margin-top: 10px; }
 
 
 
 
 
 
 
 
 
 
 
 
57
  .input-error { margin-top: 12px; color: var(--bad); font-size: .9rem; }
58
 
59
  /* ── progress ── */
 
54
  .rm:hover { color: var(--bad); }
55
  .row-actions { display: flex; gap: 10px; margin-bottom: 20px; }
56
  .microcopy { color: var(--dim); font-size: .82rem; margin-top: 10px; }
57
+ .ctx { margin: 0 0 18px; border: 1px solid var(--line); border-radius: 10px; padding: 12px 16px; }
58
+ .ctx summary { cursor: pointer; color: var(--dim); font-size: .88rem; }
59
+ .ctx summary b { color: var(--accent2); }
60
+ .ctx[open] summary { margin-bottom: 12px; color: var(--text); }
61
+ .ctx-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
62
+ .ctx-grid label { display: flex; flex-direction: column; gap: 6px; color: var(--dim); font-size: .78rem; text-transform: uppercase; letter-spacing: .06em; }
63
+ .ctx-grid select { background: var(--panel2); color: var(--text); border: 1px solid var(--line); border-radius: 8px; padding: 9px 10px; font: inherit; }
64
+ .ctx-grid select:focus { outline: none; border-color: var(--accent); }
65
+ .sig { display: inline-block; border: 1px solid var(--line); border-radius: 999px; padding: 1px 9px; font-size: .68rem; color: var(--dim); margin-left: 4px; vertical-align: middle; }
66
+ #target-table { width: 100%; border-collapse: collapse; font-size: .92rem; }
67
+ #target-table th { text-align: left; color: var(--dim); font-size: .75rem; text-transform: uppercase; letter-spacing: .06em; padding: 8px 10px; border-bottom: 1px solid var(--line); }
68
+ #target-table td { padding: 10px; border-bottom: 1px solid var(--line); }
69
  .input-error { margin-top: 12px; color: var(--bad); font-size: .9rem; }
70
 
71
  /* ── progress ── */