Report tuning: rationale writer split from CIO, value-gap text, verdict-consistent order bounds, size-scaled diversification target, sector-aware narrative
Browse files- src/construct.py +4 -1
- src/metrics.py +1 -1
- src/orchestrator.py +37 -1
- src/personas.py +60 -10
- src/revival.py +6 -2
src/construct.py
CHANGED
|
@@ -263,7 +263,10 @@ def build_bounds(holdings: list[dict], decisions: dict, picks: list[str], caps:
|
|
| 263 |
elif act == "Buy More":
|
| 264 |
b[t] = (min(w, cap), min(max(w, cap), _grow(w, cap)))
|
| 265 |
else:
|
| 266 |
-
|
|
|
|
|
|
|
|
|
|
| 267 |
for t in picks:
|
| 268 |
b[t] = (0.0, caps.get(t, M.MAX_POS_W))
|
| 269 |
return b
|
|
|
|
| 263 |
elif act == "Buy More":
|
| 264 |
b[t] = (min(w, cap), min(max(w, cap), _grow(w, cap)))
|
| 265 |
else:
|
| 266 |
+
d = decisions.get(t, {})
|
| 267 |
+
lo_k = (0.8 if d.get("protect") else 0.5) * w # a backed Keep is not churned to fund adds
|
| 268 |
+
hi_k = min(w, cap) if d.get("no_add") else _grow(w, cap) # lukewarm/flagged Keeps get no adds
|
| 269 |
+
b[t] = (min(lo_k, cap), max(hi_k, 0.0) if w > cap else hi_k)
|
| 270 |
for t in picks:
|
| 271 |
b[t] = (0.0, caps.get(t, M.MAX_POS_W))
|
| 272 |
return b
|
src/metrics.py
CHANGED
|
@@ -405,7 +405,7 @@ def _pillar_concentration(m: dict, holdings, risk) -> tuple[float, str]:
|
|
| 405 |
def _pillar_diversification(m: dict, holdings, context) -> tuple[float, str]:
|
| 406 |
n = int(m.get("n_holdings") or len(holdings) or 1)
|
| 407 |
eff = m.get("effective_n")
|
| 408 |
-
target = min(n,
|
| 409 |
base = float(np.clip(100 * float(eff) / max(target, 1), 20, 100)) if eff else 60.0
|
| 410 |
notes = [f"~{eff} effective positions of {n}"] if eff else []
|
| 411 |
k = len(m.get("corr_clusters") or [])
|
|
|
|
| 405 |
def _pillar_diversification(m: dict, holdings, context) -> tuple[float, str]:
|
| 406 |
n = int(m.get("n_holdings") or len(holdings) or 1)
|
| 407 |
eff = m.get("effective_n")
|
| 408 |
+
target = min(n, max(8.0, 0.4 * n)) # 47 names behaving like 13 is cosmetic diversification
|
| 409 |
base = float(np.clip(100 * float(eff) / max(target, 1), 20, 100)) if eff else 60.0
|
| 410 |
notes = [f"~{eff} effective positions of {n}"] if eff else []
|
| 411 |
k = len(m.get("corr_clusters") or [])
|
src/orchestrator.py
CHANGED
|
@@ -696,7 +696,24 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 696 |
"street": (h["data"].get("us") or {}).get("street")}
|
| 697 |
for h in holdings
|
| 698 |
if n <= 25 or h["weight"] >= 0.01 or decisions[h["symbol"]]["action"] != "Keep"]
|
| 699 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 700 |
cio = P.cio_synthesis({
|
| 701 |
"holdings": [{"ticker": h["symbol"], "name": h["name"],
|
| 702 |
"weight": round(h["weight"], 3), "pl_pct": round(h["pl_pct"], 3),
|
|
@@ -708,6 +725,7 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 708 |
"lens_points": {k: v[h["symbol"]] for k, v in panel.items()
|
| 709 |
if h["symbol"] in v},
|
| 710 |
"dcf": {k: (h.get("dcf") or {}).get(k) for k in ("intrinsic", "upside", "intrinsic_low", "intrinsic_high", "implied_growth", "model", "lifecycle", "note", "flags")},
|
|
|
|
| 711 |
"asymmetry": {k: (h.get("asymmetry") or {}).get(k) for k in ("expected_return", "up_down_ratio", "clears_hurdle")} if h.get("asymmetry") else None,
|
| 712 |
"sizing": {k: (h.get("sizing") or {}).get(k) for k in ("half_kelly", "current")} if h.get("sizing") else None,
|
| 713 |
"sell_triggers": (h["data"].get("us") or {}).get("sell_triggers"),
|
|
@@ -733,6 +751,11 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 733 |
cio["memos"] = memo_fut.result(timeout=240) or {}
|
| 734 |
except Exception:
|
| 735 |
cio["memos"] = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 736 |
alts = [a for a in (cio or {}).get("alternatives", []) if isinstance(a, dict)]
|
| 737 |
alt_meta = {c["ticker"]: c for c in candidates}
|
| 738 |
strong = [c for c in eligible if REV.strong_ok(c)]
|
|
@@ -799,6 +822,13 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 799 |
sector_of = {h["symbol"]: ("Diversified fund" if h["symbol"] in fund_syms else str(h["data"].get("sector") or "?")) for h in holdings}
|
| 800 |
sector_of.update({c["ticker"]: str(c.get("sector") or "?") for c in chosen})
|
| 801 |
book_usd = sum(h["market_value"] for h in holdings) if all(h.get("market_value") for h in holdings) else None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 802 |
loss_tol = M._tol_from_context(context)
|
| 803 |
risk_prof = str((context or {}).get("risk") or "balanced").lower()
|
| 804 |
lam = {"conservative": 5.0, "balanced": 3.0, "aggressive": 1.5}.get(risk_prof, 3.0)
|
|
@@ -837,6 +867,7 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 837 |
scen = CX.scenarios(holdings, decisions, pick_ids, mu, cov, cov_tickers, caps, sector_of,
|
| 838 |
sec_cap_ctx or M.SECTOR_CAP_BASE, book_usd, stress_rets, loss_tol,
|
| 839 |
risk_aversion=lam, betas=betas, beta_floor=beta_floor) if cov_tickers else {}
|
|
|
|
| 840 |
main = scen.get("full") or scen.get("tax_light") or {}
|
| 841 |
target = _target_rows(holdings, decisions, chosen, main.get("weights") or {}) if main else \
|
| 842 |
_target_portfolio(holdings, decisions, chosen, context or {"risk": "balanced"})
|
|
@@ -858,6 +889,7 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 858 |
if dx is not None and 0 <= dx <= 7:
|
| 859 |
decisions[h["symbol"]]["tax_note"] = ((decisions[h["symbol"]].get("tax_note") or "")
|
| 860 |
+ f"; ex-dividend in {dx} day{'s' if dx != 1 else ''} — sell after the ex-date to keep the dividend").strip("; ")
|
|
|
|
| 861 |
health_bd = M.health_breakdown(cards, pm, holdings, decisions, context, risk)
|
| 862 |
health = health_bd["score"]
|
| 863 |
construction = {"picks": picks, "scenarios": scen, "post_trade": {"current": current_block, **post},
|
|
@@ -890,8 +922,10 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 890 |
if over_budget(0.85):
|
| 891 |
construction["skip_narrative"] = True
|
| 892 |
degraded.append("plan narrative skipped (time budget)")
|
|
|
|
| 893 |
plan = REV.build_plan(holdings, decisions, target, eligible,
|
| 894 |
health, pm.get("total_pl_pct"), cards, context, needs, construction)
|
|
|
|
| 895 |
|
| 896 |
# 10 — assemble (+ risk block, provenance, audit artifact, diagnostics)
|
| 897 |
emit(94, "Sealing the verdict…")
|
|
@@ -935,7 +969,9 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 935 |
"candidates": [{k: v for k, v in c.items() if k != "live"} for c in candidates],
|
| 936 |
},
|
| 937 |
}
|
|
|
|
| 938 |
result = R.assemble(holdings, pm, cards, decisions, panel, strat, cio, errors, news, extra)
|
|
|
|
| 939 |
sig_meta = {c["ticker"]: c.get("signals", []) for c in candidates}
|
| 940 |
mostly_foreign = sum(1 for h in holdings if "." in h["symbol"]) > len(holdings) / 2
|
| 941 |
fit_meta = {c["ticker"]: c.get("fit") for c in candidates}
|
|
|
|
| 696 |
"street": (h["data"].get("us") or {}).get("street")}
|
| 697 |
for h in holdings
|
| 698 |
if n <= 25 or h["weight"] >= 0.01 or decisions[h["symbol"]]["action"] != "Keep"]
|
| 699 |
+
_writers = cf.ThreadPoolExecutor(max_workers=2)
|
| 700 |
+
memo_fut = _writers.submit(P.write_memos, memo_payload)
|
| 701 |
+
def _gap_text(h):
|
| 702 |
+
up = (h.get("dcf") or {}).get("upside")
|
| 703 |
+
if not isinstance(up, (int, float)) or (h.get("dcf") or {}).get("note"):
|
| 704 |
+
return None
|
| 705 |
+
return (f"price {abs(up) / (1 + up) * 100:.0f}% below DCF value" if up > 0
|
| 706 |
+
else f"price {abs(up) / (1 + up) * 100:.0f}% above DCF value")
|
| 707 |
+
rat_payload = [{"ticker": h["symbol"], "name": h["name"], "weight": round(h["weight"], 3),
|
| 708 |
+
"pl_pct": round(h["pl_pct"], 3), "action": decisions[h["symbol"]]["action"],
|
| 709 |
+
"size_note": decisions[h["symbol"]].get("size_note"),
|
| 710 |
+
"action_tax_note": decisions[h["symbol"]].get("tax_note"),
|
| 711 |
+
"value_gap_text": _gap_text(h),
|
| 712 |
+
"lens_points": {k: v[h["symbol"]].get("key_point") for k, v in panel.items() if h["symbol"] in v},
|
| 713 |
+
"lens_risks": [v[h["symbol"]].get("key_risk") for k, v in panel.items() if h["symbol"] in v][:3],
|
| 714 |
+
"forensic_flags": (h["data"].get("us") or {}).get("flags"),
|
| 715 |
+
"street": (h["data"].get("us") or {}).get("street")} for h in holdings]
|
| 716 |
+
rat_fut = _writers.submit(P.write_rationales, rat_payload)
|
| 717 |
cio = P.cio_synthesis({
|
| 718 |
"holdings": [{"ticker": h["symbol"], "name": h["name"],
|
| 719 |
"weight": round(h["weight"], 3), "pl_pct": round(h["pl_pct"], 3),
|
|
|
|
| 725 |
"lens_points": {k: v[h["symbol"]] for k, v in panel.items()
|
| 726 |
if h["symbol"] in v},
|
| 727 |
"dcf": {k: (h.get("dcf") or {}).get(k) for k in ("intrinsic", "upside", "intrinsic_low", "intrinsic_high", "implied_growth", "model", "lifecycle", "note", "flags")},
|
| 728 |
+
"value_gap_text": _gap_text(h),
|
| 729 |
"asymmetry": {k: (h.get("asymmetry") or {}).get(k) for k in ("expected_return", "up_down_ratio", "clears_hurdle")} if h.get("asymmetry") else None,
|
| 730 |
"sizing": {k: (h.get("sizing") or {}).get(k) for k in ("half_kelly", "current")} if h.get("sizing") else None,
|
| 731 |
"sell_triggers": (h["data"].get("us") or {}).get("sell_triggers"),
|
|
|
|
| 751 |
cio["memos"] = memo_fut.result(timeout=240) or {}
|
| 752 |
except Exception:
|
| 753 |
cio["memos"] = {}
|
| 754 |
+
try:
|
| 755 |
+
cio["rationale"] = rat_fut.result(timeout=240) or cio.get("rationale") or {}
|
| 756 |
+
except Exception:
|
| 757 |
+
pass
|
| 758 |
+
emit_bg(88, "cio+writers joined")
|
| 759 |
alts = [a for a in (cio or {}).get("alternatives", []) if isinstance(a, dict)]
|
| 760 |
alt_meta = {c["ticker"]: c for c in candidates}
|
| 761 |
strong = [c for c in eligible if REV.strong_ok(c)]
|
|
|
|
| 822 |
sector_of = {h["symbol"]: ("Diversified fund" if h["symbol"] in fund_syms else str(h["data"].get("sector") or "?")) for h in holdings}
|
| 823 |
sector_of.update({c["ticker"]: str(c.get("sector") or "?") for c in chosen})
|
| 824 |
book_usd = sum(h["market_value"] for h in holdings) if all(h.get("market_value") for h in holdings) else None
|
| 825 |
+
over_sec = (needs.get("sector_overweight") or {}).get("sector")
|
| 826 |
+
for h in holdings: # the order plan must agree with the verdicts: adds only where the committee backs it
|
| 827 |
+
dec = decisions[h["symbol"]]
|
| 828 |
+
flagged = bool((h["data"].get("us") or {}).get("flags"))
|
| 829 |
+
dec["no_add"] = dec["action"] == "Keep" and (dec["conviction"] < 55 or flagged)
|
| 830 |
+
dec["protect"] = dec["action"] == "Keep" and str(h["data"].get("sector") or "") != str(over_sec or "")
|
| 831 |
+
emit_bg(88, "bounds/scenarios start")
|
| 832 |
loss_tol = M._tol_from_context(context)
|
| 833 |
risk_prof = str((context or {}).get("risk") or "balanced").lower()
|
| 834 |
lam = {"conservative": 5.0, "balanced": 3.0, "aggressive": 1.5}.get(risk_prof, 3.0)
|
|
|
|
| 867 |
scen = CX.scenarios(holdings, decisions, pick_ids, mu, cov, cov_tickers, caps, sector_of,
|
| 868 |
sec_cap_ctx or M.SECTOR_CAP_BASE, book_usd, stress_rets, loss_tol,
|
| 869 |
risk_aversion=lam, betas=betas, beta_floor=beta_floor) if cov_tickers else {}
|
| 870 |
+
emit_bg(88, "scenarios done")
|
| 871 |
main = scen.get("full") or scen.get("tax_light") or {}
|
| 872 |
target = _target_rows(holdings, decisions, chosen, main.get("weights") or {}) if main else \
|
| 873 |
_target_portfolio(holdings, decisions, chosen, context or {"risk": "balanced"})
|
|
|
|
| 889 |
if dx is not None and 0 <= dx <= 7:
|
| 890 |
decisions[h["symbol"]]["tax_note"] = ((decisions[h["symbol"]].get("tax_note") or "")
|
| 891 |
+ f"; ex-dividend in {dx} day{'s' if dx != 1 else ''} — sell after the ex-date to keep the dividend").strip("; ")
|
| 892 |
+
emit_bg(88, "post-trade blocks done")
|
| 893 |
health_bd = M.health_breakdown(cards, pm, holdings, decisions, context, risk)
|
| 894 |
health = health_bd["score"]
|
| 895 |
construction = {"picks": picks, "scenarios": scen, "post_trade": {"current": current_block, **post},
|
|
|
|
| 922 |
if over_budget(0.85):
|
| 923 |
construction["skip_narrative"] = True
|
| 924 |
degraded.append("plan narrative skipped (time budget)")
|
| 925 |
+
construction["sector_of"] = sector_of
|
| 926 |
plan = REV.build_plan(holdings, decisions, target, eligible,
|
| 927 |
health, pm.get("total_pl_pct"), cards, context, needs, construction)
|
| 928 |
+
emit_bg(92, "plan + narrative done")
|
| 929 |
|
| 930 |
# 10 — assemble (+ risk block, provenance, audit artifact, diagnostics)
|
| 931 |
emit(94, "Sealing the verdict…")
|
|
|
|
| 969 |
"candidates": [{k: v for k, v in c.items() if k != "live"} for c in candidates],
|
| 970 |
},
|
| 971 |
}
|
| 972 |
+
emit_bg(94, "extra assembled")
|
| 973 |
result = R.assemble(holdings, pm, cards, decisions, panel, strat, cio, errors, news, extra)
|
| 974 |
+
emit_bg(96, "report assembled")
|
| 975 |
sig_meta = {c["ticker"]: c.get("signals", []) for c in candidates}
|
| 976 |
mostly_foreign = sum(1 for h in holdings if "." in h["symbol"]) > len(holdings) / 2
|
| 977 |
fit_meta = {c["ticker"]: c.get("fit") for c in candidates}
|
src/personas.py
CHANGED
|
@@ -10,6 +10,7 @@ from __future__ import annotations
|
|
| 10 |
|
| 11 |
import concurrent.futures as cf
|
| 12 |
import json
|
|
|
|
| 13 |
import os
|
| 14 |
|
| 15 |
import numpy as np
|
|
@@ -157,14 +158,9 @@ _CIO_SYSTEM = (
|
|
| 157 |
"1) verdict: ONE sentence describing the portfolio (its character + its biggest issue).\n"
|
| 158 |
"2) highlights: the 3-5 most decision-relevant findings across stock and portfolio level, "
|
| 159 |
"each with the number that proves it and which lens surfaced it.\n"
|
| 160 |
-
"3)
|
| 161 |
-
"
|
| 162 |
-
"
|
| 163 |
-
"numbers, EV/EBITDA, PEG, beta, percentiles, moving averages or 'the committee' (the detail "
|
| 164 |
-
"view already shows all that). Translate the data into everyday meaning — e.g. 'Profits fell "
|
| 165 |
-
"sharply last year and this one stock is nearly half your portfolio' or 'The business keeps "
|
| 166 |
-
"growing strongly and the price is still reasonable for it'. At most one simple concrete "
|
| 167 |
-
"fact per sentence.\n"
|
| 168 |
"4) premortem: for the LARGEST position only, one paragraph (<=70 words) written from 18 "
|
| 169 |
"months ahead explaining how it lost 40% — the most plausible failure path from its data.\n"
|
| 170 |
"5) alternatives: pick 2-4 tickers ONLY from the provided candidate list. The list is "
|
|
@@ -186,7 +182,6 @@ _CIO_SYSTEM = (
|
|
| 186 |
'Respond ONLY with JSON: {"verdict": "<one sentence>", '
|
| 187 |
'"highlights": [{"severity": "good|warn|bad", "title": "<=10 words", '
|
| 188 |
'"detail": "<1-2 sentences with a number>", "lens": "<value|growth|macro|technical|risk|portfolio>"}], '
|
| 189 |
-
'"rationale": {"<TICKER>": "<one sentence>"}, '
|
| 190 |
'"premortem": {"ticker": "<largest position>", "story": "<paragraph>"}, '
|
| 191 |
'"alternatives": [{"ticker": "<from candidate list>", "reason": "<one sentence>"}]} '
|
| 192 |
+ RAILS
|
|
@@ -386,7 +381,7 @@ def coerce_cio(out) -> dict | None:
|
|
| 386 |
"rationale": {str(k).upper(): str(v)[:300] for k, v in rat.items()}
|
| 387 |
if isinstance(rat, dict) else {},
|
| 388 |
"alternatives": [{"ticker": str(a.get("ticker", "")).upper()[:12],
|
| 389 |
-
"reason":
|
| 390 |
for a in alts if isinstance(a, dict) and a.get("ticker")][:4]
|
| 391 |
if isinstance(alts, list) else []}
|
| 392 |
|
|
@@ -400,6 +395,61 @@ def cio_synthesis(payload: dict) -> dict | None:
|
|
| 400 |
return coerce_cio(_call_and_parse(_CIO_SYSTEM, payload, 1600 + 160 * n, "cio"))
|
| 401 |
|
| 402 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 403 |
_MEMO_SYSTEM = (
|
| 404 |
"You are a buy-side analyst writing the investment memo line for each holding of a private "
|
| 405 |
"portfolio, from the committee's lens notes, the validated action and the data given. For EACH "
|
|
|
|
| 10 |
|
| 11 |
import concurrent.futures as cf
|
| 12 |
import json
|
| 13 |
+
import re
|
| 14 |
import os
|
| 15 |
|
| 16 |
import numpy as np
|
|
|
|
| 158 |
"1) verdict: ONE sentence describing the portfolio (its character + its biggest issue).\n"
|
| 159 |
"2) highlights: the 3-5 most decision-relevant findings across stock and portfolio level, "
|
| 160 |
"each with the number that proves it and which lens surfaced it.\n"
|
| 161 |
+
"3) (per-holding rationales are written separately — do NOT include them.) When you cite a "
|
| 162 |
+
"holding's value gap use its 'value_gap_text' verbatim (e.g. 'price 54% below DCF value'); "
|
| 163 |
+
"never restate 'upside' as 'below worth'.\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
"4) premortem: for the LARGEST position only, one paragraph (<=70 words) written from 18 "
|
| 165 |
"months ahead explaining how it lost 40% — the most plausible failure path from its data.\n"
|
| 166 |
"5) alternatives: pick 2-4 tickers ONLY from the provided candidate list. The list is "
|
|
|
|
| 182 |
'Respond ONLY with JSON: {"verdict": "<one sentence>", '
|
| 183 |
'"highlights": [{"severity": "good|warn|bad", "title": "<=10 words", '
|
| 184 |
'"detail": "<1-2 sentences with a number>", "lens": "<value|growth|macro|technical|risk|portfolio>"}], '
|
|
|
|
| 185 |
'"premortem": {"ticker": "<largest position>", "story": "<paragraph>"}, '
|
| 186 |
'"alternatives": [{"ticker": "<from candidate list>", "reason": "<one sentence>"}]} '
|
| 187 |
+ RAILS
|
|
|
|
| 381 |
"rationale": {str(k).upper(): str(v)[:300] for k, v in rat.items()}
|
| 382 |
if isinstance(rat, dict) else {},
|
| 383 |
"alternatives": [{"ticker": str(a.get("ticker", "")).upper()[:12],
|
| 384 |
+
"reason": _clip(a.get("reason", ""), 320)}
|
| 385 |
for a in alts if isinstance(a, dict) and a.get("ticker")][:4]
|
| 386 |
if isinstance(alts, list) else []}
|
| 387 |
|
|
|
|
| 395 |
return coerce_cio(_call_and_parse(_CIO_SYSTEM, payload, 1600 + 160 * n, "cio"))
|
| 396 |
|
| 397 |
|
| 398 |
+
_RATIONALE_SYSTEM = (
|
| 399 |
+
"You write, for EACH holding of a private portfolio, ONE short sentence a non-finance friend "
|
| 400 |
+
"would instantly understand that justifies the holding's GIVEN action (you may not change it). "
|
| 401 |
+
"Do NOT restate or begin with the action word — the table already shows it; write the reason only, "
|
| 402 |
+
"and vary your sentence openings across holdings. "
|
| 403 |
+
"When a Trim/Sell carries an action_tax_note, add a short clause acknowledging the tax cost. "
|
| 404 |
+
"When a size_note is present, its reason is the point (e.g. 'too small to bother trimming', "
|
| 405 |
+
"'already past the healthy size'). NO jargon and NO scores: never mention conviction numbers, "
|
| 406 |
+
"EV/EBITDA, PEG, beta, percentiles, moving averages or 'the committee'. Use 'value_gap_text' "
|
| 407 |
+
"verbatim if you cite valuation. At most one simple concrete fact per sentence, drawn from "
|
| 408 |
+
"the lens points, forensic flags, street view or memo material given. "
|
| 409 |
+
'Respond ONLY with JSON: {"<TICKER>": "<one sentence>"} covering EVERY ticker. ' + RAILS
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def write_rationales(holdings_payload: list[dict]) -> dict[str, str]:
|
| 414 |
+
"""One-line rationales in parallel chunks on the cheap tier (they were ~40% of the CIO's
|
| 415 |
+
output on a large book); the CIO keeps verdict, highlights, pre-mortem and alternatives."""
|
| 416 |
+
from .llm import LLM_MODEL_CHEAP
|
| 417 |
+
chunks = [holdings_payload[i:i + 12] for i in range(0, len(holdings_payload), 12)]
|
| 418 |
+
|
| 419 |
+
def one(chunk):
|
| 420 |
+
for attempt in range(2):
|
| 421 |
+
out = parse_json(call_llm(_RATIONALE_SYSTEM, json.dumps({"holdings": chunk}, default=str),
|
| 422 |
+
max_tokens=300 + 90 * len(chunk), tier="standard",
|
| 423 |
+
label="rationales", thinking="off", model=LLM_MODEL_CHEAP))
|
| 424 |
+
if isinstance(out, dict) and out:
|
| 425 |
+
return {str(k).upper(): _strip_action(str(v))[:300] for k, v in out.items() if isinstance(v, str)}
|
| 426 |
+
return {}
|
| 427 |
+
res: dict[str, str] = {}
|
| 428 |
+
with cf.ThreadPoolExecutor(max_workers=min(6, len(chunks) or 1)) as ex:
|
| 429 |
+
for got in ex.map(one, chunks):
|
| 430 |
+
res.update(got)
|
| 431 |
+
return res
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
_ACTION_LEAD = re.compile(r"^\s*(keep|hold|trim|sell|exit|buy more|buy|add)\b[^a-z0-9]*(because|as|since|—|-|:)?\s*", re.I)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def _strip_action(text: str) -> str:
|
| 438 |
+
"""A cheap writer once opened a Trim's rationale with 'Keep because…' — the validated
|
| 439 |
+
action is the table's, so any leading action word is removed and the reason kept."""
|
| 440 |
+
out = _ACTION_LEAD.sub("", text.strip(), count=1)
|
| 441 |
+
return (out[:1].upper() + out[1:]) if out else text.strip()
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def _clip(text: str, n: int) -> str:
|
| 445 |
+
text = str(text)
|
| 446 |
+
if len(text) <= n:
|
| 447 |
+
return text
|
| 448 |
+
cut = text[:n]
|
| 449 |
+
end = max(cut.rfind(". "), cut.rfind("; "))
|
| 450 |
+
return (cut[:end + 1] if end > n * 0.5 else cut.rsplit(" ", 1)[0] + "…").strip()
|
| 451 |
+
|
| 452 |
+
|
| 453 |
_MEMO_SYSTEM = (
|
| 454 |
"You are a buy-side analyst writing the investment memo line for each holding of a private "
|
| 455 |
"portfolio, from the committee's lens notes, the validated action and the data given. For EACH "
|
src/revival.py
CHANGED
|
@@ -214,7 +214,8 @@ def order_plan(holdings: list[dict], target: list[dict]) -> list[dict]:
|
|
| 214 |
if abs(d) < band:
|
| 215 |
continue
|
| 216 |
o = {"side": "BUY" if d > 0 else "SELL", "ticker": r["ticker"],
|
| 217 |
-
"delta_pct": round(d, 4), "is_new": r.get("is_new", False)
|
|
|
|
| 218 |
if total:
|
| 219 |
usd = abs(d) * total
|
| 220 |
o["amount_usd"] = round(usd, 0)
|
|
@@ -302,6 +303,8 @@ _PLAN_SYSTEM = (
|
|
| 302 |
"they make the payoff concrete (e.g. 'the tax-light route gets most of the benefit for a "
|
| 303 |
"third of the tax'). Plain English a non-finance friend understands; no "
|
| 304 |
"jargon, no scores. You may ONLY reference tickers and numbers present in the plan JSON. "
|
|
|
|
|
|
|
| 305 |
'Respond ONLY JSON: {"pitch": "<one warm, direct sentence framing the plan>", '
|
| 306 |
'"moves": [{"title": "<=8 words, imperative>", "detail": "<1-2 sentences: what to do and '
|
| 307 |
'the concrete payoff, citing a number from the plan>"}] (2-4 moves, most impactful first)} '
|
|
@@ -404,11 +407,12 @@ def build_plan(holdings, decisions, target, candidates, health, total_pl, cards,
|
|
| 404 |
}
|
| 405 |
if construction:
|
| 406 |
order_plan.quote_types = construction.get("quote_types") or {} # noqa — module-level hint for duty rules
|
|
|
|
| 407 |
plan["orders"] = order_plan(holdings, target) # rebuild with duty awareness
|
| 408 |
buys = [o["ticker"] for o in plan["orders"] if o["side"] == "BUY"]
|
| 409 |
plan["switch_pairs"] = switch_pairs(holdings, decisions, candidates, needs, prefer=buys)
|
| 410 |
if construction:
|
| 411 |
-
plan.update({k: v for k, v in construction.items() if k
|
| 412 |
pt = (construction.get("post_trade") or {})
|
| 413 |
planned = pt.get("full") or pt.get("tax_light") or {}
|
| 414 |
if planned: # the whole-book proof overrides the thinner outlook estimate
|
|
|
|
| 214 |
if abs(d) < band:
|
| 215 |
continue
|
| 216 |
o = {"side": "BUY" if d > 0 else "SELL", "ticker": r["ticker"],
|
| 217 |
+
"delta_pct": round(d, 4), "is_new": r.get("is_new", False),
|
| 218 |
+
"sector": (getattr(order_plan, "sector_of", None) or {}).get(r["ticker"])}
|
| 219 |
if total:
|
| 220 |
usd = abs(d) * total
|
| 221 |
o["amount_usd"] = round(usd, 0)
|
|
|
|
| 303 |
"they make the payoff concrete (e.g. 'the tax-light route gets most of the benefit for a "
|
| 304 |
"third of the tax'). Plain English a non-finance friend understands; no "
|
| 305 |
"jargon, no scores. You may ONLY reference tickers and numbers present in the plan JSON. "
|
| 306 |
+
"Each order carries its sector: only a BUY marked is_new adds a sector the book lacks — adding "
|
| 307 |
+
"to an existing holding never 'fills a gap', so do not describe it that way. "
|
| 308 |
'Respond ONLY JSON: {"pitch": "<one warm, direct sentence framing the plan>", '
|
| 309 |
'"moves": [{"title": "<=8 words, imperative>", "detail": "<1-2 sentences: what to do and '
|
| 310 |
'the concrete payoff, citing a number from the plan>"}] (2-4 moves, most impactful first)} '
|
|
|
|
| 407 |
}
|
| 408 |
if construction:
|
| 409 |
order_plan.quote_types = construction.get("quote_types") or {} # noqa — module-level hint for duty rules
|
| 410 |
+
order_plan.sector_of = construction.get("sector_of") or {} # noqa — sectors on orders for the narrator
|
| 411 |
plan["orders"] = order_plan(holdings, target) # rebuild with duty awareness
|
| 412 |
buys = [o["ticker"] for o in plan["orders"] if o["side"] == "BUY"]
|
| 413 |
plan["switch_pairs"] = switch_pairs(holdings, decisions, candidates, needs, prefer=buys)
|
| 414 |
if construction:
|
| 415 |
+
plan.update({k: v for k, v in construction.items() if k not in ("quote_types", "sector_of")})
|
| 416 |
pt = (construction.get("post_trade") or {})
|
| 417 |
planned = pt.get("full") or pt.get("tax_light") or {}
|
| 418 |
if planned: # the whole-book proof overrides the thinner outlook estimate
|