Wealth-manager review fixes: mandate-sized ballast, one vehicle per industry and gap sector, growth-mandate screen, profile-cap trims with drift band, bench screens, sheltered-account tax wording, loss tax planning
Browse files- README.md +13 -0
- src/construct.py +4 -1
- src/metrics.py +2 -0
- src/orchestrator.py +112 -9
- src/personas.py +3 -1
- src/revival.py +6 -0
- tests/test_construct.py +14 -0
- tests/test_recommend.py +14 -0
README.md
CHANGED
|
@@ -260,6 +260,19 @@ Recommendation discipline for every book with a usable DCF range:
|
|
| 260 |
90 days of **catalysts** (earnings, ex-dividend), and per-holding **tripwires** with the current
|
| 261 |
number and the date they are next tested. Loss-making growth names are valued on a stated
|
| 262 |
rule-of-40 EV/Sales yardstick instead of a blank. Triage dispositions always agree with the trade list.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
- **Sector gaps are sourced, not just named** β a sector the book lacks is searched six names
|
| 264 |
deep in the quant panel (two for sectors already owned), the top 30 are verified live, the
|
| 265 |
committee screens a second batch whenever a missing sector has no strong candidate, and the
|
|
|
|
| 260 |
90 days of **catalysts** (earnings, ex-dividend), and per-holding **tripwires** with the current
|
| 261 |
number and the date they are next tested. Loss-making growth names are valued on a stated
|
| 262 |
rule-of-40 EV/Sales yardstick instead of a blank. Triage dispositions always agree with the trade list.
|
| 263 |
+
- **Mandate discipline (wealth-manager review, Nov 2026)** β bond / cash / low-volatility ballast is
|
| 264 |
+
sized to the profile: up to 30% for a conservative client or a stated loss tolerance, 15% for
|
| 265 |
+
balanced, 8% when the objective is growth, and none for an aggressive mandate (its beta is cut with
|
| 266 |
+
lower-beta equities). The 200-day trend test applies to equities, never to ballast. A growth mandate
|
| 267 |
+
penalises candidates growing revenue under 3%. New buys take one name per industry and one vehicle
|
| 268 |
+
per missing sector (never a sector ETF plus a single name in the same gap). A Keep above the
|
| 269 |
+
profile's name cap becomes a size Trim, except a strongly backed winner (65+) within 1.25Γ the cap,
|
| 270 |
+
which is held where it is with no new money. Outside a conservative or loss-tolerance mandate the
|
| 271 |
+
plan holds at most one ballast fund, and profile ballast caps are hard (the step that rounds small
|
| 272 |
+
new positions up never lifts them). The watchlist excludes distress-zone, off-mandate and
|
| 273 |
+
far-above-value names, and a conservative client's bench holds only names with a known beta of 1.15 or less. Inside a tax-free wrapper
|
| 274 |
+
rationales say nothing about tax; in a taxable account a realised loss is framed as a deductible
|
| 275 |
+
benefit, and the tax plan records it with the carry-forward and the 30-day wash-sale window.
|
| 276 |
- **Sector gaps are sourced, not just named** β a sector the book lacks is searched six names
|
| 277 |
deep in the quant panel (two for sectors already owned), the top 30 are verified live, the
|
| 278 |
committee screens a second batch whenever a missing sector has no strong candidate, and the
|
src/construct.py
CHANGED
|
@@ -188,7 +188,8 @@ def optimize_target(cur_w: dict[str, float], mu: dict[str, float], cov: np.ndarr
|
|
| 188 |
# feasibility must not silently lift the caps on names the verdicts froze (a gated
|
| 189 |
# NVDA once grew from 6.8% to 9.2% this way): only names allowed to grow absorb the
|
| 190 |
# shortfall; the uniform stretch is the last resort
|
| 191 |
-
|
|
|
|
| 192 |
short = 1.02 - hi.sum()
|
| 193 |
if growable.any():
|
| 194 |
room = hi[growable] - w0[growable]
|
|
@@ -315,6 +316,8 @@ def build_bounds(holdings: list[dict], decisions: dict, picks: list[str], caps:
|
|
| 315 |
min_size = min(0.02, max(0.01, 0.5 / max(len(holdings), 1)))
|
| 316 |
lo_b = max(min(w, cap), min(min_size, cap)) # a Buy More is funded at least to a real position
|
| 317 |
b[t] = (lo_b, max(lo_b, min(max(w, cap), _grow(w, cap))))
|
|
|
|
|
|
|
| 318 |
else:
|
| 319 |
d = decisions.get(t, {})
|
| 320 |
min_size = min(0.02, max(0.01, 0.5 / max(len(holdings), 1)))
|
|
|
|
| 188 |
# feasibility must not silently lift the caps on names the verdicts froze (a gated
|
| 189 |
# NVDA once grew from 6.8% to 9.2% this way): only names allowed to grow absorb the
|
| 190 |
# shortfall; the uniform stretch is the last resort
|
| 191 |
+
hard = getattr(optimize_target, "hard", None) or set() # profile caps (ballast) are never lifted
|
| 192 |
+
growable = (hi > w0 + 1e-9) & np.array([t not in hard for t in U])
|
| 193 |
short = 1.02 - hi.sum()
|
| 194 |
if growable.any():
|
| 195 |
room = hi[growable] - w0[growable]
|
|
|
|
| 316 |
min_size = min(0.02, max(0.01, 0.5 / max(len(holdings), 1)))
|
| 317 |
lo_b = max(min(w, cap), min(min_size, cap)) # a Buy More is funded at least to a real position
|
| 318 |
b[t] = (lo_b, max(lo_b, min(max(w, cap), _grow(w, cap))))
|
| 319 |
+
elif decisions.get(t, {}).get("hold_size"):
|
| 320 |
+
b[t] = (0.97 * w, w) # drift band: held where it is, neither shaved nor topped up
|
| 321 |
else:
|
| 322 |
d = decisions.get(t, {})
|
| 323 |
min_size = min(0.02, max(0.01, 0.5 / max(len(holdings), 1)))
|
src/metrics.py
CHANGED
|
@@ -907,6 +907,8 @@ def diagnose_needs(pm: dict, risk: dict, holdings: list[dict], context: dict | N
|
|
| 907 |
if (str(context.get("risk") or "").lower() == "conservative"
|
| 908 |
or "under 3" in str(context.get("horizon") or "").lower()):
|
| 909 |
needs["_cautious"] = {"weight": 0.0, "label": None} # marker only β never a need to fill
|
|
|
|
|
|
|
| 910 |
sa = {s: w for s, w in (pm.get("sector_allocation") or {}).items() if s != "Diversified fund"}
|
| 911 |
lt = ((risk or {}).get("lookthrough") or {}).get("sectors") or {}
|
| 912 |
eff = lt if lt else sa
|
|
|
|
| 907 |
if (str(context.get("risk") or "").lower() == "conservative"
|
| 908 |
or "under 3" in str(context.get("horizon") or "").lower()):
|
| 909 |
needs["_cautious"] = {"weight": 0.0, "label": None} # marker only β never a need to fill
|
| 910 |
+
if str(context.get("risk") or "").lower() == "aggressive":
|
| 911 |
+
needs["_aggressive"] = {"weight": 0.0, "label": None} # marker: no bond/cash ballast unless a loss tolerance is stated
|
| 912 |
sa = {s: w for s, w in (pm.get("sector_allocation") or {}).items() if s != "Diversified fund"}
|
| 913 |
lt = ((risk or {}).get("lookthrough") or {}).get("sectors") or {}
|
| 914 |
eff = lt if lt else sa
|
src/orchestrator.py
CHANGED
|
@@ -121,7 +121,7 @@ def _enrich_candidates(cands: list[dict], k: int = 8) -> None:
|
|
| 121 |
d = fetch_holding(c["ticker"])
|
| 122 |
c["live"] = {kk: d.get(kk) for kk in
|
| 123 |
("name", "price", "sma200", "beta", "pe", "rev_growth", "eps_growth",
|
| 124 |
-
"div_yield", "hi52")}
|
| 125 |
c["flags"] = M.trap_flags(d) # same guards holdings get (value trap, inorganic EPSβ¦)
|
| 126 |
price, sma = d.get("price"), d.get("sma200")
|
| 127 |
c["trend_ok"] = bool(price and (not sma or price >= sma))
|
|
@@ -149,7 +149,9 @@ def _fit_context(cands: list[dict], context: dict | None) -> list[dict]:
|
|
| 149 |
return cands
|
| 150 |
want_income = "income" in str(context.get("objective") or "").lower()
|
| 151 |
conservative = str(context.get("risk") or "").lower() == "conservative"
|
| 152 |
-
|
|
|
|
|
|
|
| 153 |
return cands
|
| 154 |
|
| 155 |
def fits(c: dict) -> bool:
|
|
@@ -161,6 +163,9 @@ def _fit_context(cands: list[dict], context: dict | None) -> list[dict]:
|
|
| 161 |
if conservative:
|
| 162 |
b = live.get("beta")
|
| 163 |
ok = ok and isinstance(b, (int, float)) and b <= 1.1
|
|
|
|
|
|
|
|
|
|
| 164 |
return ok
|
| 165 |
|
| 166 |
fit = [c for c in cands if c.get("live") and fits(c)]
|
|
@@ -545,6 +550,15 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 545 |
port_ret = M.portfolio_returns(holdings, hist)
|
| 546 |
for c in scored:
|
| 547 |
c["fit"] = M.candidate_fit(c, holdings, pm, risk, needs, port_ret, cand_hist)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 548 |
if needs.get("_cautious"): # profile screen: high-beta names are off-profile, not merely lower-ranked
|
| 549 |
for c in scored:
|
| 550 |
b = (c.get("fit") or {}).get("beta") or (c.get("live") or {}).get("beta")
|
|
@@ -557,8 +571,8 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 557 |
c["fit"]["score"] = round(c["fit"]["score"] - 0.15, 3) # costs rankβ¦
|
| 558 |
if up < -0.40: # β¦and only far above value is a caution
|
| 559 |
c["fit"]["cautions"].append(f"price {abs(up) / (1 + up) * 100:.0f}% above DCF value β a diversification case only")
|
| 560 |
-
for c in scored: # trend: buying into a broken trend is disclosed and costs fit β ETFs included
|
| 561 |
-
if c.get("trend_ok") is False:
|
| 562 |
c["fit"]["cautions"].append("below its 200-day average β would be bought into a weak trend")
|
| 563 |
c["fit"]["score"] = round(c["fit"]["score"] - 0.3, 3)
|
| 564 |
for c in scored: # forensic screen: a factor rank never outranks a distress or manipulation flag
|
|
@@ -730,6 +744,30 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 730 |
decisions[h["symbol"]]["action"] = "Keep"
|
| 731 |
decisions[h["symbol"]]["size_note"] = (f"conviction supports adding, but beta {b:.2f} is off-profile "
|
| 732 |
f"for a conservative / income book β hold, do not add")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 733 |
for h in holdings: # bond / cash ballast is judged on its role, never ejected by equity lenses
|
| 734 |
if M.is_ballast_fund(h) and cautious_book:
|
| 735 |
decisions[h["symbol"]]["ballast"] = True # optimizer floor: never sold down
|
|
@@ -782,7 +820,7 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 782 |
rat_payload = [{"ticker": h["symbol"], "name": h["name"], "weight": round(h["weight"], 3),
|
| 783 |
"pl_pct": round(h["pl_pct"], 3), "action": decisions[h["symbol"]]["action"],
|
| 784 |
"size_note": decisions[h["symbol"]].get("size_note"),
|
| 785 |
-
"action_tax_note": decisions[h["symbol"]].get("tax_note"),
|
| 786 |
"value_gap_text": _gap_text(h),
|
| 787 |
"lens_points": {k: v[h["symbol"]].get("key_point") for k, v in panel.items() if h["symbol"] in v},
|
| 788 |
"lens_risks": [v[h["symbol"]].get("key_risk") for k, v in panel.items() if h["symbol"] in v][:3],
|
|
@@ -794,7 +832,7 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 794 |
"weight": round(h["weight"], 3), "pl_pct": round(h["pl_pct"], 3),
|
| 795 |
"action": decisions[h["symbol"]]["action"],
|
| 796 |
"action_size_note": decisions[h["symbol"]].get("size_note"),
|
| 797 |
-
"action_tax_note": decisions[h["symbol"]].get("tax_note"),
|
| 798 |
"conviction_median": decisions[h["symbol"]]["conviction"],
|
| 799 |
"lens_scores": decisions[h["symbol"]]["scores"],
|
| 800 |
"lens_points": {k: v[h["symbol"]] for k, v in panel.items()
|
|
@@ -825,6 +863,10 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 825 |
cio = cio or {}
|
| 826 |
if cio is not None:
|
| 827 |
_ensure_single_names.needs = needs # noqa β gap coverage reads the diagnosed needs
|
|
|
|
|
|
|
|
|
|
|
|
|
| 828 |
cio["alternatives"] = _ensure_single_names(cio.get("alternatives") or [], eligible, holdings, fund_syms)
|
| 829 |
try:
|
| 830 |
cio["memos"] = memo_fut.result(timeout=240) or {}
|
|
@@ -842,6 +884,34 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 842 |
if str(a.get("ticker", "")).upper() in alt_meta
|
| 843 |
and REV.strong_ok(alt_meta[str(a.get("ticker", "")).upper()])]
|
| 844 |
pool = list({c["ticker"]: c for c in cio_strong + strong}.values())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 845 |
max_pos = int((context or {}).get("max_positions") or 0) or 60
|
| 846 |
n_kept = sum(1 for h in holdings if decisions[h["symbol"]]["action"] != "Sell")
|
| 847 |
max_adds = max(0, min(5 if needs.get("sector_gaps") else 4, max_pos - n_kept))
|
|
@@ -900,12 +970,27 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 900 |
# the cap); an instrument may absorb more, but not become the book in a stock-picker's book
|
| 901 |
new_cap = min(book_cap, max(0.03, 1.5 * median_w), 0.07) # a new name is a starter, never an 11% bet
|
| 902 |
instr_cap = (min(M.FUND_CAP * 0.5, max(0.10, 3 * median_w)) if n_single >= 12 else M.FUND_CAP * 0.5)
|
|
|
|
| 903 |
for c in chosen:
|
| 904 |
if c.get("instrument") and M.sector_etf_sector(c["ticker"]):
|
| 905 |
# XLF once took 22% of a six-name book: a sector fund is a sector bet, capped like a name
|
| 906 |
caps[c["ticker"]] = min(instr_cap, book_cap, 0.15)
|
| 907 |
else:
|
| 908 |
caps[c["ticker"]] = instr_cap if c.get("instrument") else min(new_cap, name_cap_ctx or 1.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 909 |
sector_of = {h["symbol"]: (M.sector_etf_sector(h["symbol"]) or ("Diversified fund" if h["symbol"] in fund_syms
|
| 910 |
else str(h["data"].get("sector") or "?"))) for h in holdings}
|
| 911 |
sector_of.update({c["ticker"]: str(c.get("sector") or "?") for c in chosen})
|
|
@@ -970,9 +1055,11 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 970 |
row[t] = r if r is not None else (bench_r if bench_r is not None else 0.0)
|
| 971 |
if any(v != 0.0 for v in row.values()):
|
| 972 |
stress_rets[name] = row
|
|
|
|
| 973 |
scen = CX.scenarios(holdings, decisions, pick_ids, mu, cov, cov_tickers, caps, sector_of,
|
| 974 |
sec_cap_ctx or M.SECTOR_CAP_BASE, book_usd, stress_rets, loss_tol,
|
| 975 |
risk_aversion=lam, betas=betas, beta_floor=beta_floor) if cov_tickers else {}
|
|
|
|
| 976 |
emit_bg(88, "scenarios done")
|
| 977 |
main = scen.get("full") or scen.get("tax_light") or {}
|
| 978 |
target = _target_rows(holdings, decisions, chosen, main.get("weights") or {}) if main else \
|
|
@@ -1089,9 +1176,22 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 1089 |
try:
|
| 1090 |
bought_now = {o["ticker"] for o in plan.get("orders") or [] if o["side"] == "BUY"}
|
| 1091 |
held_now = {h["symbol"] for h in holdings}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1092 |
wl = []
|
| 1093 |
for c in eligible:
|
| 1094 |
-
if c["ticker"] in bought_now or c["ticker"] in held_now or c.get("instrument") or not REV.strong_ok(c)
|
|
|
|
| 1095 |
continue
|
| 1096 |
fixes = ((c.get("fit") or {}).get("fixes") or [])
|
| 1097 |
wl.append({"ticker": c["ticker"], "name": (c.get("live") or {}).get("name") or c["ticker"],
|
|
@@ -1106,7 +1206,8 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 1106 |
cond = "buy on a pullback toward its 200-day average"
|
| 1107 |
elif "peak-cycle" in why:
|
| 1108 |
cond = "wait for estimate revisions to turn down and the price to reset, then reassess"
|
| 1109 |
-
if cond and x.get("ticker") not in held_now and x.get("ticker") not in bought_now
|
|
|
|
| 1110 |
wl.append({"ticker": x["ticker"], "name": x.get("name") or x["ticker"], "condition": cond,
|
| 1111 |
"why": why.split(";")[0][:120]})
|
| 1112 |
plan["watchlist"] = wl[:6]
|
|
@@ -1342,7 +1443,9 @@ def _instrument_candidates(needs: dict, holdings: list[dict], risk: dict) -> lis
|
|
| 1342 |
if i.get("asset_class") == "sector_etf" and i.get("sector") in gaps[:4] and i["ticker"] not in held:
|
| 1343 |
out.append({"ticker": i["ticker"], "sector": i["sector"], "instrument": True, "need_target": "sector_gaps",
|
| 1344 |
"signals": ["instrument β sector ETF (diversified way to fill the gap)"], "rank_pct": None})
|
| 1345 |
-
if needs.get("defensive"):
|
|
|
|
|
|
|
| 1346 |
for i in by_need.get("defensive", []):
|
| 1347 |
if i["ticker"] not in held:
|
| 1348 |
out.append({"ticker": i["ticker"], "sector": "Diversified fund", "instrument": True, "need_target": "defensive",
|
|
|
|
| 121 |
d = fetch_holding(c["ticker"])
|
| 122 |
c["live"] = {kk: d.get(kk) for kk in
|
| 123 |
("name", "price", "sma200", "beta", "pe", "rev_growth", "eps_growth",
|
| 124 |
+
"div_yield", "hi52", "industry", "sector")}
|
| 125 |
c["flags"] = M.trap_flags(d) # same guards holdings get (value trap, inorganic EPSβ¦)
|
| 126 |
price, sma = d.get("price"), d.get("sma200")
|
| 127 |
c["trend_ok"] = bool(price and (not sma or price >= sma))
|
|
|
|
| 149 |
return cands
|
| 150 |
want_income = "income" in str(context.get("objective") or "").lower()
|
| 151 |
conservative = str(context.get("risk") or "").lower() == "conservative"
|
| 152 |
+
want_growth = ("growth" in str(context.get("objective") or "").lower() and not want_income) \
|
| 153 |
+
or str(context.get("risk") or "").lower() == "aggressive"
|
| 154 |
+
if not (want_income or conservative or want_growth):
|
| 155 |
return cands
|
| 156 |
|
| 157 |
def fits(c: dict) -> bool:
|
|
|
|
| 163 |
if conservative:
|
| 164 |
b = live.get("beta")
|
| 165 |
ok = ok and isinstance(b, (int, float)) and b <= 1.1
|
| 166 |
+
if want_growth and not c.get("instrument"):
|
| 167 |
+
g = live.get("rev_growth") # growth mandate: the business must be growing
|
| 168 |
+
ok = ok and isinstance(g, (int, float)) and g >= 0.10
|
| 169 |
return ok
|
| 170 |
|
| 171 |
fit = [c for c in cands if c.get("live") and fits(c)]
|
|
|
|
| 550 |
port_ret = M.portfolio_returns(holdings, hist)
|
| 551 |
for c in scored:
|
| 552 |
c["fit"] = M.candidate_fit(c, holdings, pm, risk, needs, port_ret, cand_hist)
|
| 553 |
+
growth_mandate = (("growth" in str((context or {}).get("objective") or "").lower()
|
| 554 |
+
and "income" not in str((context or {}).get("objective") or "").lower())
|
| 555 |
+
or str((context or {}).get("risk") or "").lower() == "aggressive")
|
| 556 |
+
if growth_mandate: # Altria at ~0% revenue growth was a "gap filler" in three growth books
|
| 557 |
+
for c in scored:
|
| 558 |
+
g = (c.get("live") or {}).get("rev_growth")
|
| 559 |
+
if not c.get("instrument") and isinstance(g, (int, float)) and g < 0.03:
|
| 560 |
+
c["fit"]["cautions"].append(f"revenue growth {g * 100:.0f}% β off-mandate for a growth objective")
|
| 561 |
+
c["fit"]["score"] = round(c["fit"]["score"] - 0.35, 3)
|
| 562 |
if needs.get("_cautious"): # profile screen: high-beta names are off-profile, not merely lower-ranked
|
| 563 |
for c in scored:
|
| 564 |
b = (c.get("fit") or {}).get("beta") or (c.get("live") or {}).get("beta")
|
|
|
|
| 571 |
c["fit"]["score"] = round(c["fit"]["score"] - 0.15, 3) # costs rankβ¦
|
| 572 |
if up < -0.40: # β¦and only far above value is a caution
|
| 573 |
c["fit"]["cautions"].append(f"price {abs(up) / (1 + up) * 100:.0f}% above DCF value β a diversification case only")
|
| 574 |
+
for c in scored: # trend: buying into a broken trend is disclosed and costs fit β equity ETFs included,
|
| 575 |
+
if c.get("trend_ok") is False and c.get("need_target") != "defensive": # never bond/cash/gold ballast
|
| 576 |
c["fit"]["cautions"].append("below its 200-day average β would be bought into a weak trend")
|
| 577 |
c["fit"]["score"] = round(c["fit"]["score"] - 0.3, 3)
|
| 578 |
for c in scored: # forensic screen: a factor rank never outranks a distress or manipulation flag
|
|
|
|
| 744 |
decisions[h["symbol"]]["action"] = "Keep"
|
| 745 |
decisions[h["symbol"]]["size_note"] = (f"conviction supports adding, but beta {b:.2f} is off-profile "
|
| 746 |
f"for a conservative / income book β hold, do not add")
|
| 747 |
+
prof_cap = (_RISK_CAPS.get(str((context or {}).get("risk") or ""), (None, None)))[0]
|
| 748 |
+
if prof_cap:
|
| 749 |
+
for h in holdings:
|
| 750 |
+
d0 = decisions[h["symbol"]]
|
| 751 |
+
w0 = float(h["weight"])
|
| 752 |
+
if (d0["action"] in ("Keep", "Buy More") and h["symbol"] not in fund_syms and w0 > prof_cap
|
| 753 |
+
and d0["conviction"] >= 65 and w0 <= prof_cap * 1.25):
|
| 754 |
+
# drift band: a strongly backed winner slightly over the cap is held, not shaved
|
| 755 |
+
# (user rule: winners are not sold prematurely) β but it gets no new money
|
| 756 |
+
d0["action"] = "Keep"
|
| 757 |
+
d0["hold_size"] = True
|
| 758 |
+
d0["size_note"] = (f"at {w0 * 100:.0f}% of the book, above the {prof_cap * 100:.0f}% cap for "
|
| 759 |
+
f"{'an' if str((context or {}).get('risk'))[:1] in 'aeiou' else 'a'} "
|
| 760 |
+
f"{(context or {}).get('risk')} profile but within the drift band and strongly backed β "
|
| 761 |
+
f"let the winner run, no new money")
|
| 762 |
+
continue
|
| 763 |
+
if (d0["action"] in ("Keep", "Buy More") and h["symbol"] not in fund_syms
|
| 764 |
+
and w0 > prof_cap * 1.10):
|
| 765 |
+
# LLY once read "Keep" while the plan sold a third of it to meet the 12% cap of a
|
| 766 |
+
# balanced profile β the verdict must say what the trade does, and why
|
| 767 |
+
d0["action"] = "Trim"
|
| 768 |
+
d0["size_note"] = (f"at {float(h['weight']) * 100:.0f}% of the book against the {prof_cap * 100:.0f}% cap for "
|
| 769 |
+
f"{'an' if str((context or {}).get('risk'))[:1] in 'aeiou' else 'a'} {(context or {}).get('risk')} profile, size itself is the risk β trim back toward the cap; "
|
| 770 |
+
f"a sizing decision, not a verdict on the business")
|
| 771 |
for h in holdings: # bond / cash ballast is judged on its role, never ejected by equity lenses
|
| 772 |
if M.is_ballast_fund(h) and cautious_book:
|
| 773 |
decisions[h["symbol"]]["ballast"] = True # optimizer floor: never sold down
|
|
|
|
| 820 |
rat_payload = [{"ticker": h["symbol"], "name": h["name"], "weight": round(h["weight"], 3),
|
| 821 |
"pl_pct": round(h["pl_pct"], 3), "action": decisions[h["symbol"]]["action"],
|
| 822 |
"size_note": decisions[h["symbol"]].get("size_note"),
|
| 823 |
+
"action_tax_note": (None if wrapper in ("isa", "sipp", "pension", "401k", "ira") else decisions[h["symbol"]].get("tax_note")),
|
| 824 |
"value_gap_text": _gap_text(h),
|
| 825 |
"lens_points": {k: v[h["symbol"]].get("key_point") for k, v in panel.items() if h["symbol"] in v},
|
| 826 |
"lens_risks": [v[h["symbol"]].get("key_risk") for k, v in panel.items() if h["symbol"] in v][:3],
|
|
|
|
| 832 |
"weight": round(h["weight"], 3), "pl_pct": round(h["pl_pct"], 3),
|
| 833 |
"action": decisions[h["symbol"]]["action"],
|
| 834 |
"action_size_note": decisions[h["symbol"]].get("size_note"),
|
| 835 |
+
"action_tax_note": (None if wrapper in ("isa", "sipp", "pension", "401k", "ira") else decisions[h["symbol"]].get("tax_note")),
|
| 836 |
"conviction_median": decisions[h["symbol"]]["conviction"],
|
| 837 |
"lens_scores": decisions[h["symbol"]]["scores"],
|
| 838 |
"lens_points": {k: v[h["symbol"]] for k, v in panel.items()
|
|
|
|
| 863 |
cio = cio or {}
|
| 864 |
if cio is not None:
|
| 865 |
_ensure_single_names.needs = needs # noqa β gap coverage reads the diagnosed needs
|
| 866 |
+
_cmeta = {c["ticker"]: c for c in candidates}
|
| 867 |
+
cio["alternatives"] = [a for a in (cio.get("alternatives") or []) if isinstance(a, dict)
|
| 868 |
+
and not any("distress" in str(x) for x in
|
| 869 |
+
((_cmeta.get(str(a.get("ticker", "")).upper(), {}).get("fit") or {}).get("cautions") or []))]
|
| 870 |
cio["alternatives"] = _ensure_single_names(cio.get("alternatives") or [], eligible, holdings, fund_syms)
|
| 871 |
try:
|
| 872 |
cio["memos"] = memo_fut.result(timeout=240) or {}
|
|
|
|
| 884 |
if str(a.get("ticker", "")).upper() in alt_meta
|
| 885 |
and REV.strong_ok(alt_meta[str(a.get("ticker", "")).upper()])]
|
| 886 |
pool = list({c["ticker"]: c for c in cio_strong + strong}.values())
|
| 887 |
+
# one new idea per industry, and one vehicle per sector the book is missing: McKesson AND
|
| 888 |
+
# Cencora (both drug distributors) plus a healthcare ETF once added 25% healthcare in one move
|
| 889 |
+
held_secs = {str(h["data"].get("sector") or "") for h in holdings}
|
| 890 |
+
seen_ind, seen_gap, deduped = set(), set(), []
|
| 891 |
+
for c in pool:
|
| 892 |
+
live = c.get("live") or {}
|
| 893 |
+
ind = str(live.get("industry") or "").strip().lower()
|
| 894 |
+
sec = str(c.get("sector") or live.get("sector") or "")
|
| 895 |
+
if not c.get("instrument") and ind:
|
| 896 |
+
if ind in seen_ind:
|
| 897 |
+
continue
|
| 898 |
+
seen_ind.add(ind)
|
| 899 |
+
if sec and sec not in held_secs and sec not in ("Diversified fund", "?"):
|
| 900 |
+
if sec in seen_gap:
|
| 901 |
+
continue
|
| 902 |
+
seen_gap.add(sec)
|
| 903 |
+
deduped.append(c)
|
| 904 |
+
pool = deduped
|
| 905 |
+
if not (str((context or {}).get("risk") or "").lower() == "conservative" or M._tol_from_context(context) is not None):
|
| 906 |
+
# SHY 8% + USMV 6.8% once made a 14.8% sleeve against an 8% ballast budget: one vehicle
|
| 907 |
+
first_def, kept = None, []
|
| 908 |
+
for c in pool:
|
| 909 |
+
if c.get("instrument") and c.get("need_target") == "defensive":
|
| 910 |
+
if first_def:
|
| 911 |
+
continue
|
| 912 |
+
first_def = c["ticker"]
|
| 913 |
+
kept.append(c)
|
| 914 |
+
pool = kept
|
| 915 |
max_pos = int((context or {}).get("max_positions") or 0) or 60
|
| 916 |
n_kept = sum(1 for h in holdings if decisions[h["symbol"]]["action"] != "Sell")
|
| 917 |
max_adds = max(0, min(5 if needs.get("sector_gaps") else 4, max_pos - n_kept))
|
|
|
|
| 970 |
# the cap); an instrument may absorb more, but not become the book in a stock-picker's book
|
| 971 |
new_cap = min(book_cap, max(0.03, 1.5 * median_w), 0.07) # a new name is a starter, never an 11% bet
|
| 972 |
instr_cap = (min(M.FUND_CAP * 0.5, max(0.10, 3 * median_w)) if n_single >= 12 else M.FUND_CAP * 0.5)
|
| 973 |
+
hard_caps: set[str] = set()
|
| 974 |
for c in chosen:
|
| 975 |
if c.get("instrument") and M.sector_etf_sector(c["ticker"]):
|
| 976 |
# XLF once took 22% of a six-name book: a sector fund is a sector bet, capped like a name
|
| 977 |
caps[c["ticker"]] = min(instr_cap, book_cap, 0.15)
|
| 978 |
else:
|
| 979 |
caps[c["ticker"]] = instr_cap if c.get("instrument") else min(new_cap, name_cap_ctx or 1.0)
|
| 980 |
+
if c.get("instrument") and c.get("need_target") == "defensive":
|
| 981 |
+
# ballast follows the mandate: a 30% short-treasury sleeve is a retiree's answer, not a
|
| 982 |
+
# balanced-growth investor's (their beta is cut with lower-beta equities first)
|
| 983 |
+
prof = str((context or {}).get("risk") or "balanced").lower()
|
| 984 |
+
growth_obj = "growth" in str((context or {}).get("objective") or "").lower() \
|
| 985 |
+
and "income" not in str((context or {}).get("objective") or "").lower()
|
| 986 |
+
if prof == "conservative" or M._tol_from_context(context) is not None:
|
| 987 |
+
ballast_cap = 0.30
|
| 988 |
+
elif growth_obj:
|
| 989 |
+
ballast_cap = 0.08
|
| 990 |
+
else:
|
| 991 |
+
ballast_cap = 0.15
|
| 992 |
+
caps[c["ticker"]] = min(caps[c["ticker"]], ballast_cap)
|
| 993 |
+
hard_caps.add(c["ticker"])
|
| 994 |
sector_of = {h["symbol"]: (M.sector_etf_sector(h["symbol"]) or ("Diversified fund" if h["symbol"] in fund_syms
|
| 995 |
else str(h["data"].get("sector") or "?"))) for h in holdings}
|
| 996 |
sector_of.update({c["ticker"]: str(c.get("sector") or "?") for c in chosen})
|
|
|
|
| 1055 |
row[t] = r if r is not None else (bench_r if bench_r is not None else 0.0)
|
| 1056 |
if any(v != 0.0 for v in row.values()):
|
| 1057 |
stress_rets[name] = row
|
| 1058 |
+
CX.optimize_target.hard = hard_caps # noqa β read by the feasibility ladder
|
| 1059 |
scen = CX.scenarios(holdings, decisions, pick_ids, mu, cov, cov_tickers, caps, sector_of,
|
| 1060 |
sec_cap_ctx or M.SECTOR_CAP_BASE, book_usd, stress_rets, loss_tol,
|
| 1061 |
risk_aversion=lam, betas=betas, beta_floor=beta_floor) if cov_tickers else {}
|
| 1062 |
+
CX.optimize_target.hard = set() # noqa β never leaks into the next run
|
| 1063 |
emit_bg(88, "scenarios done")
|
| 1064 |
main = scen.get("full") or scen.get("tax_light") or {}
|
| 1065 |
target = _target_rows(holdings, decisions, chosen, main.get("weights") or {}) if main else \
|
|
|
|
| 1176 |
try:
|
| 1177 |
bought_now = {o["ticker"] for o in plan.get("orders") or [] if o["side"] == "BUY"}
|
| 1178 |
held_now = {h["symbol"] for h in holdings}
|
| 1179 |
+
cand_by = {c["ticker"]: c for c in candidates}
|
| 1180 |
+
|
| 1181 |
+
def _off_profile(tk: str, why: str = "") -> bool:
|
| 1182 |
+
"""A retiree's bench never holds UBER or TSM; distress is never on anyone's bench."""
|
| 1183 |
+
c = cand_by.get(tk) or {}
|
| 1184 |
+
txt = why + " " + " ".join(str(x) for x in ((c.get("fit") or {}).get("cautions") or []))
|
| 1185 |
+
if any(k in txt for k in ("distress", "off-mandate", "diversification case only", "too volatile")):
|
| 1186 |
+
return True # UBER at 658% above DCF value once sat on a retiree's bench
|
| 1187 |
+
if needs.get("_cautious") and not c.get("instrument"):
|
| 1188 |
+
b = (c.get("live") or {}).get("beta")
|
| 1189 |
+
return not (isinstance(b, (int, float)) and b <= 1.15) # unknown beta is not "low beta"
|
| 1190 |
+
return False
|
| 1191 |
wl = []
|
| 1192 |
for c in eligible:
|
| 1193 |
+
if c["ticker"] in bought_now or c["ticker"] in held_now or c.get("instrument") or not REV.strong_ok(c) \
|
| 1194 |
+
or _off_profile(c["ticker"]):
|
| 1195 |
continue
|
| 1196 |
fixes = ((c.get("fit") or {}).get("fixes") or [])
|
| 1197 |
wl.append({"ticker": c["ticker"], "name": (c.get("live") or {}).get("name") or c["ticker"],
|
|
|
|
| 1206 |
cond = "buy on a pullback toward its 200-day average"
|
| 1207 |
elif "peak-cycle" in why:
|
| 1208 |
cond = "wait for estimate revisions to turn down and the price to reset, then reassess"
|
| 1209 |
+
if cond and x.get("ticker") not in held_now and x.get("ticker") not in bought_now \
|
| 1210 |
+
and not _off_profile(x.get("ticker"), why):
|
| 1211 |
wl.append({"ticker": x["ticker"], "name": x.get("name") or x["ticker"], "condition": cond,
|
| 1212 |
"why": why.split(";")[0][:120]})
|
| 1213 |
plan["watchlist"] = wl[:6]
|
|
|
|
| 1443 |
if i.get("asset_class") == "sector_etf" and i.get("sector") in gaps[:4] and i["ticker"] not in held:
|
| 1444 |
out.append({"ticker": i["ticker"], "sector": i["sector"], "instrument": True, "need_target": "sector_gaps",
|
| 1445 |
"signals": ["instrument β sector ETF (diversified way to fill the gap)"], "rank_pct": None})
|
| 1446 |
+
if needs.get("defensive") and not (needs.get("_aggressive") and not needs.get("_loss_tol")):
|
| 1447 |
+
# an aggressive growth investor never had 22% parked in short treasuries "for ballast":
|
| 1448 |
+
# their beta is cut with lower-beta equities, ballast only when they state a loss tolerance
|
| 1449 |
for i in by_need.get("defensive", []):
|
| 1450 |
if i["ticker"] not in held:
|
| 1451 |
out.append({"ticker": i["ticker"], "sector": "Diversified fund", "instrument": True, "need_target": "defensive",
|
src/personas.py
CHANGED
|
@@ -422,7 +422,9 @@ _RATIONALE_SYSTEM = (
|
|
| 422 |
"would instantly understand that justifies the holding's GIVEN action (you may not change it). "
|
| 423 |
"Do NOT restate or begin with the action word β the table already shows it; write the reason only, "
|
| 424 |
"and vary your sentence openings across holdings. "
|
| 425 |
-
"When a Trim/Sell carries an action_tax_note, add a short clause
|
|
|
|
|
|
|
| 426 |
"never mention tax or account type for a Keep or Buy More. Respect the weight given: a position "
|
| 427 |
"above 3% of the book is not 'small'. "
|
| 428 |
"When a size_note is present, its reason is the point (e.g. 'too small to bother trimming', "
|
|
|
|
| 422 |
"would instantly understand that justifies the holding's GIVEN action (you may not change it). "
|
| 423 |
"Do NOT restate or begin with the action word β the table already shows it; write the reason only, "
|
| 424 |
"and vary your sentence openings across holdings. "
|
| 425 |
+
"When a Trim/Sell carries an action_tax_note, add a short clause on its tax effect: a GAIN is a tax cost; "
|
| 426 |
+
"a LOSS is a benefit β say it plainly, e.g. 'and selling books a loss that can offset taxable gains' "
|
| 427 |
+
"(never 'despite the loss', never 'the loss is a deductible loss'); vary the wording across holdings; "
|
| 428 |
"never mention tax or account type for a Keep or Buy More. Respect the weight given: a position "
|
| 429 |
"above 3% of the book is not 'small'. "
|
| 430 |
"When a size_note is present, its reason is the point (e.g. 'too small to bother trimming', "
|
src/revival.py
CHANGED
|
@@ -252,6 +252,12 @@ def tax_plan(holdings: list[dict], decisions: dict, orders: list[dict], book_usd
|
|
| 252 |
gain = (float(h["price"]) - float(h["entry"])) * float(h["qty"]) * sold_frac * float(h.get("fx_usd") or 1.0)
|
| 253 |
if gain > 0.01 * book_usd and (not h.get("bought") or _days(h["bought"]) >= 365):
|
| 254 |
notes.append(f"β${gain:,.0f} long-term gain β consider splitting the sale across two tax years (December / January)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
if notes:
|
| 256 |
out.append({"ticker": h["symbol"], "note": "; ".join(notes)})
|
| 257 |
return out[:8]
|
|
|
|
| 252 |
gain = (float(h["price"]) - float(h["entry"])) * float(h["qty"]) * sold_frac * float(h.get("fx_usd") or 1.0)
|
| 253 |
if gain > 0.01 * book_usd and (not h.get("bought") or _days(h["bought"]) >= 365):
|
| 254 |
notes.append(f"β${gain:,.0f} long-term gain β consider splitting the sale across two tax years (December / January)")
|
| 255 |
+
if h.get("qty") and float(h["price"]) < float(h["entry"]):
|
| 256 |
+
loss = (float(h["entry"]) - float(h["price"])) * float(h["qty"]) * sold_frac * float(h.get("fx_usd") or 1.0)
|
| 257 |
+
if book_usd and loss > 0.005 * book_usd:
|
| 258 |
+
notes.append(f"books β${loss:,.0f} capital loss β it offsets gains realised this year, and any excess carries "
|
| 259 |
+
f"forward (up to $3,000 a year against ordinary income in the US); do not rebuy within 30 days "
|
| 260 |
+
f"or the wash-sale rule voids it")
|
| 261 |
if notes:
|
| 262 |
out.append({"ticker": h["symbol"], "note": "; ".join(notes)})
|
| 263 |
return out[:8]
|
tests/test_construct.py
CHANGED
|
@@ -230,3 +230,17 @@ def test_ladder_lift_is_six_percent_in_a_broad_book():
|
|
| 230 |
bounds = {**{f"K{i}": (0.03, 0.04) for i in range(18)}, "S": (0.0, 0.0), "B": (0.02, 0.05)}
|
| 231 |
w = CX.optimize_target(cur, mu, cov, U, bounds, {t: t for t in U}, 0.9, 0.9, {}, tax_weight=0.0)
|
| 232 |
assert w["B"] <= 0.06 + 1e-6 and CX.optimize_target.cash > 0.15 # the add stops at 6%; the rest is cash
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
bounds = {**{f"K{i}": (0.03, 0.04) for i in range(18)}, "S": (0.0, 0.0), "B": (0.02, 0.05)}
|
| 231 |
w = CX.optimize_target(cur, mu, cov, U, bounds, {t: t for t in U}, 0.9, 0.9, {}, tax_weight=0.0)
|
| 232 |
assert w["B"] <= 0.06 + 1e-6 and CX.optimize_target.cash > 0.15 # the add stops at 6%; the rest is cash
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def test_feasibility_ladder_never_lifts_a_hard_profile_cap():
|
| 236 |
+
U = ["S", "K", "SHY", "N"]
|
| 237 |
+
cov = np.eye(4) * 0.04
|
| 238 |
+
cur = {"S": 0.40, "K": 0.60, "SHY": 0.0, "N": 0.0}
|
| 239 |
+
mu = {t: 0.05 for t in U}
|
| 240 |
+
bounds = {"S": (0.0, 0.0), "K": (0.55, 0.60), "SHY": (0.0, 0.08), "N": (0.0, 0.07)}
|
| 241 |
+
CX.optimize_target.hard = {"SHY"}
|
| 242 |
+
try:
|
| 243 |
+
w = CX.optimize_target(cur, mu, cov, U, bounds, {t: t for t in U}, 0.9, 0.9, {}, tax_weight=0.0)
|
| 244 |
+
finally:
|
| 245 |
+
CX.optimize_target.hard = set()
|
| 246 |
+
assert w["SHY"] <= 0.08 + 1e-6 and w["N"] > 0.07 # the starter is lifted, the ballast cap is not
|
tests/test_recommend.py
CHANGED
|
@@ -375,3 +375,17 @@ def test_pdf_print_theme_is_light_and_the_palette_resets():
|
|
| 375 |
assert "-print.pdf" in r.headers["content-disposition"]
|
| 376 |
finally:
|
| 377 |
A._runs.pop("themetest01", None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
assert "-print.pdf" in r.headers["content-disposition"]
|
| 376 |
finally:
|
| 377 |
A._runs.pop("themetest01", None)
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def test_tax_plan_books_capital_losses_with_wash_sale_note():
|
| 381 |
+
from src.revival import tax_plan
|
| 382 |
+
hs = [{"symbol": "MRNA", "weight": 0.36, "price": 25.0, "entry": 57.0, "qty": 600, "fx_usd": 1.0, "bought": None, "data": {}}]
|
| 383 |
+
out = tax_plan(hs, {}, [{"side": "SELL", "ticker": "MRNA", "delta_pct": -0.36}], 42000.0)
|
| 384 |
+
assert out and "capital loss" in out[0]["note"] and "wash-sale" in out[0]["note"]
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def test_drift_band_holds_a_backed_winner_and_bounds_freeze_it():
|
| 388 |
+
from src import construct as CX
|
| 389 |
+
hs = [{"symbol": "NVDA", "weight": 0.168, "data": {}}, {"symbol": "X", "weight": 0.832, "data": {}}]
|
| 390 |
+
b = CX.build_bounds(hs, {"NVDA": {"action": "Keep", "hold_size": True}, "X": {"action": "Keep"}}, [], {"NVDA": 0.15, "X": 0.9}, "full")
|
| 391 |
+
assert abs(b["NVDA"][1] - 0.168) < 1e-9 and b["NVDA"][0] > 0.16
|