Real-book review fixes: one currency per ratio for foreign filers, completed size trims with cash as dry powder, staged average-downs, funded Buy Mores, live tripwires, harvest and switch consistency, net tax summary, benchmark-aware sector check, PDF table layout
Browse files- README.md +7 -0
- src/construct.py +70 -13
- src/fundamentals.py +74 -20
- src/market_data.py +18 -0
- src/metrics.py +23 -0
- src/orchestrator.py +32 -2
- src/pdf_report.py +23 -8
- src/personas.py +10 -2
- src/report.py +10 -5
- src/revival.py +102 -18
- static/app.js +4 -3
- tests/test_construct.py +27 -4
- tests/test_recommend.py +45 -0
README.md
CHANGED
|
@@ -186,6 +186,13 @@ the same exchanges. Tax notes apply US short/long-term rules only to US listings
|
|
| 186 |
Plain US listings get a deep block computed deterministically from Sharadar history and Alpha
|
| 187 |
Vantage estimates, so the committee argues from numbers rather than adjectives:
|
| 188 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
- **Forensic quality** — Piotroski F-score, Altman Z (masked for financials and REITs), Beneish
|
| 190 |
M-score, Sloan accruals, cash conversion (FCF / net income).
|
| 191 |
- **Buffett / Greenblatt / Lynch economics** — owner earnings and owner-earnings yield, FCF yield,
|
|
|
|
| 186 |
Plain US listings get a deep block computed deterministically from Sharadar history and Alpha
|
| 187 |
Vantage estimates, so the committee argues from numbers rather than adjectives:
|
| 188 |
|
| 189 |
+
- **One currency per ratio** — US-listed foreign filers (Alibaba in CNY, TSMC in TWD, Novo in DKK,
|
| 190 |
+
Spotify in EUR) report statements in their own currency while market value is in USD. The
|
| 191 |
+
reporting-currency factor is derived from each filing's own P/S and P/E, and every ratio that
|
| 192 |
+
mixes the two (Altman Z, FCF and earnings yields, per-share DCF inputs) is put on one basis.
|
| 193 |
+
- **Tripwires that have not fired yet** — sell triggers are set relative to today's reading, so a
|
| 194 |
+
Buy More never ships beside a trigger it has already crossed.
|
| 195 |
+
|
| 196 |
- **Forensic quality** — Piotroski F-score, Altman Z (masked for financials and REITs), Beneish
|
| 197 |
M-score, Sloan accruals, cash conversion (FCF / net income).
|
| 198 |
- **Buffett / Greenblatt / Lynch economics** — owner earnings and owner-earnings yield, FCF yield,
|
src/construct.py
CHANGED
|
@@ -149,6 +149,9 @@ def greedy_select(cur_w: dict[str, float], candidates: list[dict], cov: np.ndarr
|
|
| 149 |
|
| 150 |
# ---------------- constrained sizing ----------------
|
| 151 |
|
|
|
|
|
|
|
|
|
|
| 152 |
def optimize_target(cur_w: dict[str, float], mu: dict[str, float], cov: np.ndarray, tickers: list[str],
|
| 153 |
bounds: dict[str, tuple[float, float]], sector_of: dict[str, str],
|
| 154 |
sector_cap: float, turnover_max: float, tax_cost: dict[str, float],
|
|
@@ -189,6 +192,7 @@ def optimize_target(cur_w: dict[str, float], mu: dict[str, float], cov: np.ndarr
|
|
| 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():
|
|
@@ -196,16 +200,26 @@ def optimize_target(cur_w: dict[str, float], mu: dict[str, float], cov: np.ndarr
|
|
| 196 |
lifted = hi[growable] + short * (room / room.sum() if room.sum() > 0 else 1.0 / growable.sum())
|
| 197 |
lift_cap = 0.10 if len(U) <= 12 else 0.06 # in a broad book an add is never a 10% bet (five 6% adds once ate 31%)
|
| 198 |
hi[growable] = np.minimum(lifted, np.maximum(hi[growable], lift_cap))
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
if hi.sum() < 1.0:
|
| 210 |
# proceeds exceed what the committee's ideas can absorb: the professional answer is
|
| 211 |
# cash held for the watchlist, not a forced top-up of lukewarm Keeps
|
|
@@ -271,6 +285,9 @@ def optimize_target(cur_w: dict[str, float], mu: dict[str, float], cov: np.ndarr
|
|
| 271 |
return None
|
| 272 |
|
| 273 |
|
|
|
|
|
|
|
|
|
|
| 274 |
def _grow(w: float, cap: float) -> float:
|
| 275 |
"""An existing position may at most double, or gain 3 points of the book, whichever is
|
| 276 |
larger — a 0.8% satellite is never turned into a 14% core by the solver."""
|
|
@@ -315,7 +332,15 @@ def build_bounds(holdings: list[dict], decisions: dict, picks: list[str], caps:
|
|
| 315 |
elif act == "Buy More":
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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:
|
|
@@ -333,6 +358,18 @@ def build_bounds(holdings: list[dict], decisions: dict, picks: list[str], caps:
|
|
| 333 |
return b
|
| 334 |
|
| 335 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
def tax_cost_per_weight(holdings: list[dict]) -> dict[str, float]:
|
| 337 |
"""Tax cost per unit of weight SOLD ≈ gain fraction of proceeds × rate (long-term 20%,
|
| 338 |
short-term/unknown 30%). Losses are free (a small negative → harvesting is rewarded)."""
|
|
@@ -408,12 +445,26 @@ def scenarios(holdings: list[dict], decisions: dict, picks: list[str], mu: dict[
|
|
| 408 |
when a loss tolerance was stated — whether every crash replay stays inside it."""
|
| 409 |
cur = {h["symbol"]: float(h["weight"]) for h in holdings}
|
| 410 |
tc = tax_cost_per_weight(holdings)
|
|
|
|
|
|
|
|
|
|
| 411 |
specs = {"full": {"turnover": 0.40, "tax_w": 0.5, "mode": "full"},
|
| 412 |
"tax_light": {"turnover": 0.15, "tax_w": 2.5, "mode": "full"},
|
| 413 |
"new_cash": {"turnover": 0.12, "tax_w": 0.0, "mode": "new_cash"}}
|
| 414 |
if loss_tol is not None: # what it actually takes to honour the stated tolerance
|
| 415 |
specs["de_risk"] = {"turnover": 0.80, "tax_w": 0.5, "mode": "de_risk"}
|
| 416 |
out: dict[str, dict] = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 417 |
for name, sp in specs.items():
|
| 418 |
bounds = build_bounds(holdings, decisions, picks, caps, sp["mode"], new_cash=0.10)
|
| 419 |
w = optimize_target(cur, mu, cov, tickers, bounds, sector_of, sector_cap,
|
|
@@ -426,8 +477,12 @@ def scenarios(holdings: list[dict], decisions: dict, picks: list[str], mu: dict[
|
|
| 426 |
staged = list(getattr(optimize_target, "relaxed", []) or [])
|
| 427 |
cash = round(float(getattr(optimize_target, "cash", 0.0) or 0.0), 4)
|
| 428 |
turnover = 0.5 * sum(abs(w.get(t, 0.0) - cur.get(t, 0.0)) for t in set(w) | set(cur))
|
| 429 |
-
|
| 430 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 431 |
edge_before = sum(cur[t] * mu.get(t, 0.0) for t in cur)
|
| 432 |
edge_after = sum(w[t] * mu.get(t, 0.0) for t in w)
|
| 433 |
out[name] = {"weights": {t: round(v, 4) for t, v in w.items() if v > 1e-4},
|
|
@@ -439,4 +494,6 @@ def scenarios(holdings: list[dict], decisions: dict, picks: list[str], mu: dict[
|
|
| 439 |
"label": {"full": "Full rebalance", "tax_light": "Tax-light rebalance",
|
| 440 |
"new_cash": "New cash only (≈10% added, no sells)",
|
| 441 |
"de_risk": "Meet your loss tolerance (bigger trade)"}[name]}
|
|
|
|
|
|
|
| 442 |
return out
|
|
|
|
| 149 |
|
| 150 |
# ---------------- constrained sizing ----------------
|
| 151 |
|
| 152 |
+
CASH_SOFT = 0.15 # unplaced proceeds held as dry powder before any trim is staged
|
| 153 |
+
|
| 154 |
+
|
| 155 |
def optimize_target(cur_w: dict[str, float], mu: dict[str, float], cov: np.ndarray, tickers: list[str],
|
| 156 |
bounds: dict[str, tuple[float, float]], sector_of: dict[str, str],
|
| 157 |
sector_cap: float, turnover_max: float, tax_cost: dict[str, float],
|
|
|
|
| 192 |
# NVDA once grew from 6.8% to 9.2% this way): only names allowed to grow absorb the
|
| 193 |
# shortfall; the uniform stretch is the last resort
|
| 194 |
hard = getattr(optimize_target, "hard", None) or set() # profile caps (ballast) are never lifted
|
| 195 |
+
hard = set(hard) | set(getattr(optimize_target, "no_lift", None) or set()) # averaging-down + broad-book starters
|
| 196 |
growable = (hi > w0 + 1e-9) & np.array([t not in hard for t in U])
|
| 197 |
short = 1.02 - hi.sum()
|
| 198 |
if growable.any():
|
|
|
|
| 200 |
lifted = hi[growable] + short * (room / room.sum() if room.sum() > 0 else 1.0 / growable.sum())
|
| 201 |
lift_cap = 0.10 if len(U) <= 12 else 0.06 # in a broad book an add is never a 10% bet (five 6% adds once ate 31%)
|
| 202 |
hi[growable] = np.minimum(lifted, np.maximum(hi[growable], lift_cap))
|
| 203 |
+
# still short: the sales are bigger than the book can absorb at sensible sizes. A manager
|
| 204 |
+
# completes the risk-reducing trims and holds the unplaced proceeds as dry powder; only if
|
| 205 |
+
# that cash would pass CASH_SOFT are valuation trims staged (half now), and a size trim
|
| 206 |
+
# (META 25% vs a 15% cap) is staged only past the 25% cash ceiling. A staged cut must still
|
| 207 |
+
# be a real trade — a 0.4%-of-book shave is noise, so such trims are completed instead.
|
| 208 |
+
size_trims = set(getattr(optimize_target, "size_trims", None) or set())
|
| 209 |
+
band = float(getattr(optimize_target, "min_trade", 0.005) or 0.005)
|
| 210 |
+
for tier, limit in (("value", CASH_SOFT), ("size", 0.25)):
|
| 211 |
+
if 1.0 - hi.sum() <= limit:
|
| 212 |
+
break
|
| 213 |
+
idx_s = [i for i in range(len(U)) if w0[i] - hi[i] > 1e-9 and hi[i] > 1e-9
|
| 214 |
+
and ((U[i] in size_trims) == (tier == "size")) and 0.5 * (w0[i] - hi[i]) >= band]
|
| 215 |
+
if not idx_s:
|
| 216 |
+
continue
|
| 217 |
+
room = np.array([0.5 * (w0[i] - hi[i]) for i in idx_s])
|
| 218 |
+
need = (1.0 - hi.sum()) - limit
|
| 219 |
+
add = np.minimum(need * room / room.sum(), room) if room.sum() > need else room
|
| 220 |
+
for k, i in enumerate(idx_s):
|
| 221 |
+
hi[i] += add[k]
|
| 222 |
+
optimize_target.relaxed = list(optimize_target.relaxed) + [U[i] for k, i in enumerate(idx_s) if add[k] > 1e-4]
|
| 223 |
if hi.sum() < 1.0:
|
| 224 |
# proceeds exceed what the committee's ideas can absorb: the professional answer is
|
| 225 |
# cash held for the watchlist, not a forced top-up of lukewarm Keeps
|
|
|
|
| 285 |
return None
|
| 286 |
|
| 287 |
|
| 288 |
+
AVG_DOWN_PL = -0.10 # a Buy More this far underwater is an average-down, sized in steps
|
| 289 |
+
|
| 290 |
+
|
| 291 |
def _grow(w: float, cap: float) -> float:
|
| 292 |
"""An existing position may at most double, or gain 3 points of the book, whichever is
|
| 293 |
larger — a 0.8% satellite is never turned into a 14% core by the solver."""
|
|
|
|
| 332 |
elif act == "Buy More":
|
| 333 |
min_size = min(0.02, max(0.01, 0.5 / max(len(holdings), 1)))
|
| 334 |
lo_b = max(min(w, cap), min(min_size, cap)) # a Buy More is funded at least to a real position
|
| 335 |
+
up = _grow(w, cap)
|
| 336 |
+
if float(h.get("pl_pct") or 0) <= AVG_DOWN_PL:
|
| 337 |
+
# averaging down is staged: a loser at most doubles, and by no more than 2 points
|
| 338 |
+
# of the book per step (NVO −47% was once taken from 1.1% to 6.0% in one trade)
|
| 339 |
+
up = min(cap, w + min(w, 0.02))
|
| 340 |
+
hi_b = max(lo_b, min(max(w, cap), up))
|
| 341 |
+
band = min(0.02, max(0.005, 0.5 / max(len(holdings), 1)))
|
| 342 |
+
lo_b = max(lo_b, min(hi_b, w + band)) # a Buy More is a real trade, never an unfunded label
|
| 343 |
+
b[t] = (lo_b, hi_b)
|
| 344 |
elif decisions.get(t, {}).get("hold_size"):
|
| 345 |
b[t] = (0.97 * w, w) # drift band: held where it is, neither shaved nor topped up
|
| 346 |
else:
|
|
|
|
| 358 |
return b
|
| 359 |
|
| 360 |
|
| 361 |
+
def _long_term(h: dict) -> bool:
|
| 362 |
+
b = h.get("bought")
|
| 363 |
+
if not b:
|
| 364 |
+
return False
|
| 365 |
+
try:
|
| 366 |
+
from datetime import date
|
| 367 |
+
y, mo, d = (int(x) for x in str(b)[:10].split("-"))
|
| 368 |
+
return (date.today() - date(y, mo, d)).days >= 365
|
| 369 |
+
except Exception:
|
| 370 |
+
return False
|
| 371 |
+
|
| 372 |
+
|
| 373 |
def tax_cost_per_weight(holdings: list[dict]) -> dict[str, float]:
|
| 374 |
"""Tax cost per unit of weight SOLD ≈ gain fraction of proceeds × rate (long-term 20%,
|
| 375 |
short-term/unknown 30%). Losses are free (a small negative → harvesting is rewarded)."""
|
|
|
|
| 445 |
when a loss tolerance was stated — whether every crash replay stays inside it."""
|
| 446 |
cur = {h["symbol"]: float(h["weight"]) for h in holdings}
|
| 447 |
tc = tax_cost_per_weight(holdings)
|
| 448 |
+
tax_net = {h["symbol"]: ((float(h["price"]) - float(h["entry"])) / float(h["price"]) if float(h["price"]) > 0 else 0.0)
|
| 449 |
+
* (0.30 if h.get("bought") and not _long_term(h) else 0.20) # undated lots: long-held, as the tax summary states
|
| 450 |
+
for h in holdings}
|
| 451 |
specs = {"full": {"turnover": 0.40, "tax_w": 0.5, "mode": "full"},
|
| 452 |
"tax_light": {"turnover": 0.15, "tax_w": 2.5, "mode": "full"},
|
| 453 |
"new_cash": {"turnover": 0.12, "tax_w": 0.0, "mode": "new_cash"}}
|
| 454 |
if loss_tol is not None: # what it actually takes to honour the stated tolerance
|
| 455 |
specs["de_risk"] = {"turnover": 0.80, "tax_w": 0.5, "mode": "de_risk"}
|
| 456 |
out: dict[str, dict] = {}
|
| 457 |
+
# feasibility-ladder hints: averaging-down adds never get lifted past their staged step, and in
|
| 458 |
+
# a broad book a new idea stays a starter — unplaced proceeds become cash, not a 6% bet
|
| 459 |
+
optimize_target.no_lift = {h["symbol"] for h in holdings # noqa
|
| 460 |
+
if decisions.get(h["symbol"], {}).get("action") == "Buy More"
|
| 461 |
+
and float(h.get("pl_pct") or 0) <= AVG_DOWN_PL} | (
|
| 462 |
+
# in a broad book nothing is lifted past its own sizing rule (TSM 1.9% → 6% via the lift):
|
| 463 |
+
# proceeds the ideas cannot absorb are held as cash instead
|
| 464 |
+
set(picks) | {h["symbol"] for h in holdings} if len(holdings) > 12 else set())
|
| 465 |
+
optimize_target.size_trims = {t for t, d in decisions.items() # noqa
|
| 466 |
+
if "size itself is the risk" in str(d.get("size_note") or "")}
|
| 467 |
+
optimize_target.min_trade = min(0.02, max(0.005, 0.5 / max(len(holdings), 1))) # noqa
|
| 468 |
for name, sp in specs.items():
|
| 469 |
bounds = build_bounds(holdings, decisions, picks, caps, sp["mode"], new_cash=0.10)
|
| 470 |
w = optimize_target(cur, mu, cov, tickers, bounds, sector_of, sector_cap,
|
|
|
|
| 477 |
staged = list(getattr(optimize_target, "relaxed", []) or [])
|
| 478 |
cash = round(float(getattr(optimize_target, "cash", 0.0) or 0.0), 4)
|
| 479 |
turnover = 0.5 * sum(abs(w.get(t, 0.0) - cur.get(t, 0.0)) for t in set(w) | set(cur))
|
| 480 |
+
# new-cash mode sells nothing: weights shrink by dilution, which is not a taxable sale
|
| 481 |
+
base_w = {t: v / (1 + 0.10) for t, v in cur.items()} if sp["mode"] == "new_cash" else cur
|
| 482 |
+
sold = {t: max(base_w.get(t, 0.0) - w.get(t, 0.0) - (1e-4 if sp["mode"] == "new_cash" else 0.0), 0.0) for t in cur}
|
| 483 |
+
# reported tax nets realised losses against gains in full (the optimiser's own cost caps
|
| 484 |
+
# losses so it never sells just to harvest) — the headline must agree with the tax summary
|
| 485 |
+
tax_frac = max(0.0, sum(tax_net.get(t, 0.0) * s for t, s in sold.items()))
|
| 486 |
edge_before = sum(cur[t] * mu.get(t, 0.0) for t in cur)
|
| 487 |
edge_after = sum(w[t] * mu.get(t, 0.0) for t in w)
|
| 488 |
out[name] = {"weights": {t: round(v, 4) for t, v in w.items() if v > 1e-4},
|
|
|
|
| 494 |
"label": {"full": "Full rebalance", "tax_light": "Tax-light rebalance",
|
| 495 |
"new_cash": "New cash only (≈10% added, no sells)",
|
| 496 |
"de_risk": "Meet your loss tolerance (bigger trade)"}[name]}
|
| 497 |
+
optimize_target.no_lift = set() # noqa — never leaks into the next run
|
| 498 |
+
optimize_target.size_trims = set() # noqa
|
| 499 |
return out
|
src/fundamentals.py
CHANGED
|
@@ -175,14 +175,32 @@ def piotroski(a: list[dict]) -> dict | None:
|
|
| 175 |
return {"score": pts, "signals": why}
|
| 176 |
|
| 177 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
def altman_z(c: dict, mcap: float | None) -> float | None:
|
| 179 |
-
"""Classic public-company Z (1968). Not meaningful for banks/insurers — caller masks financials.
|
|
|
|
|
|
|
| 180 |
ta, tl = _f(c.get("assets")), _f(c.get("liabilities"))
|
| 181 |
if not ta or not tl:
|
| 182 |
return None
|
| 183 |
wc = _f(c.get("workingcapital")) or ((_f(c.get("assetsc")) or 0.0) - (_f(c.get("liabilitiesc")) or 0.0))
|
| 184 |
re, ebit, rev = _f(c.get("retearn")) or 0.0, _f(c.get("ebit")) or 0.0, _f(c.get("revenue")) or 0.0
|
| 185 |
-
mc = mcap or _f(c.get("marketcap")) or 0.0
|
| 186 |
z = 1.2 * wc / ta + 1.4 * re / ta + 3.3 * ebit / ta + 0.6 * mc / tl + 1.0 * rev / ta
|
| 187 |
return round(min(z, 30.0), 2) # 30+ is "irrelevantly safe"
|
| 188 |
|
|
@@ -237,7 +255,9 @@ def economics(a: list[dict], price: float | None, mcap: float | None, sector: st
|
|
| 237 |
c = a[0]
|
| 238 |
ni, cfo, capex, fcf = _f(c.get("netinc")), _f(c.get("ncfo")), _f(c.get("capex")), _f(c.get("fcf"))
|
| 239 |
da, rev, sh = _f(c.get("depamor")), _f(c.get("revenue")), _f(c.get("sharesbas"))
|
| 240 |
-
|
|
|
|
|
|
|
| 241 |
ta = _f(c.get("assets"))
|
| 242 |
if ni is not None and cfo is not None and ta:
|
| 243 |
out["accruals"] = round((ni - cfo) / ta, 3) # Sloan: > 0.10 is a red flag
|
|
@@ -245,14 +265,17 @@ def economics(a: list[dict], price: float | None, mcap: float | None, sector: st
|
|
| 245 |
out["cash_conversion"] = round(fcf / ni, 2) if ni > 0 else None # FCF / net income
|
| 246 |
if ni is not None and da is not None and capex is not None and sh:
|
| 247 |
oe = ni + da - abs(capex) # Buffett owner earnings (full capex)
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
|
|
|
|
|
|
|
|
|
| 251 |
if fcf is not None and mc:
|
| 252 |
out["fcf_yield"] = round(fcf / mc, 4)
|
| 253 |
ebit, ev = _f(c.get("ebit")), _f(c.get("ev"))
|
| 254 |
if ebit is not None and ev and ev > 0:
|
| 255 |
-
out["greenblatt_ey"] = round(ebit / ev, 4) # EBIT / EV
|
| 256 |
out["roic"] = _f(c.get("roic"))
|
| 257 |
# 5-year incremental ROIC: Δ NOPAT / Δ invested capital
|
| 258 |
if len(a) >= 6:
|
|
@@ -301,7 +324,7 @@ def economics(a: list[dict], price: float | None, mcap: float | None, sector: st
|
|
| 301 |
out["rule_of_40"] = round((r1 + fcf / rev) * 100, 1)
|
| 302 |
# Graham number and Lynch PEG
|
| 303 |
eps, bvps = _f(c.get("epsdil")) or _f(c.get("eps")), _f(c.get("bvps"))
|
| 304 |
-
if eps and bvps and eps > 0 and bvps > 0:
|
| 305 |
out["graham_number"] = round(math.sqrt(22.5 * eps * bvps), 2)
|
| 306 |
eps3 = [_f(r.get("epsdil")) or _f(r.get("eps")) for r in a[:4]]
|
| 307 |
if len(eps3) == 4 and eps3[0] and eps3[3] and eps3[0] > 0 and eps3[3] > 0:
|
|
@@ -310,7 +333,7 @@ def economics(a: list[dict], price: float | None, mcap: float | None, sector: st
|
|
| 310 |
g = out.get("eps_cagr_3y")
|
| 311 |
if pe and pe > 0 and g and g > 0:
|
| 312 |
out["peg_3y"] = round(pe / (g * 100), 2) # Lynch: P/E ÷ EPS growth
|
| 313 |
-
out["lynch_category"] = lynch_category(a, sector,
|
| 314 |
return out
|
| 315 |
|
| 316 |
|
|
@@ -331,7 +354,11 @@ def lynch_category(a: list[dict], sector: str, mcap: float | None, dps: float |
|
|
| 331 |
ni_prev = [_f(r.get("netinc")) for r in a[1:3]] # a loss within the last two years
|
| 332 |
if ni_now is not None and ni_now > 0 and any(x is not None and x < 0 for x in ni_prev):
|
| 333 |
return "turnaround"
|
| 334 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
return "cyclical"
|
| 336 |
if g is not None and g >= 0.20:
|
| 337 |
return "fast grower"
|
|
@@ -443,7 +470,7 @@ def earnings_momentum(t: str) -> dict:
|
|
| 443 |
now, ago = _f(x.get("eps_estimate_average")), _f(x.get("eps_estimate_average_90_days_ago"))
|
| 444 |
if now and ago:
|
| 445 |
out["fy_eps_est"] = now
|
| 446 |
-
out["eps_revision_90d_pct"] = round((now
|
| 447 |
up, dn = _f(x.get("eps_estimate_revision_up_trailing_30_days")), _f(x.get("eps_estimate_revision_down_trailing_30_days"))
|
| 448 |
if up is not None or dn is not None:
|
| 449 |
out["revisions_30d"] = {"up": int(up or 0), "down": int(dn or 0)}
|
|
@@ -549,10 +576,19 @@ def forensic_flags(us: dict) -> list[str]:
|
|
| 549 |
fl.append(f"insiders net sellers (${ins['sell_usd'] / 1e6:.0f}M sold vs ${ins.get('buy_usd', 0) / 1e6:.0f}M bought, 6m)")
|
| 550 |
er = us.get("earnings") or {}
|
| 551 |
if (er.get("eps_revision_90d_pct") or 0) < -5:
|
| 552 |
-
fl.append(
|
| 553 |
return fl
|
| 554 |
|
| 555 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 556 |
def sell_triggers(d: dict, us: dict) -> list[str]:
|
| 557 |
"""Fisher/Lynch sell discipline: the observable facts that would break the thesis."""
|
| 558 |
e = us.get("econ") or {}
|
|
@@ -561,23 +597,41 @@ def sell_triggers(d: dict, us: dict) -> list[str]:
|
|
| 561 |
def _pct(x):
|
| 562 |
return f"{x * 100:.0f}%" if isinstance(x, (int, float)) else None
|
| 563 |
g, peg, payout = _pct(d.get("rev_growth")), d.get("peg"), e.get("fcf_payout") or d.get("payout_ratio")
|
|
|
|
|
|
|
|
|
|
| 564 |
if cat == "fast grower":
|
| 565 |
-
|
| 566 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 567 |
tr.append("gross margin contracts more than 300bp year on year")
|
| 568 |
elif cat == "stalwart":
|
| 569 |
-
|
| 570 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 571 |
elif cat == "cyclical":
|
| 572 |
tr.append("peak margins with inventory building faster than sales — sell strength, not weakness"
|
| 573 |
+ (f" (revenue growth now {g})" if g else ""))
|
| 574 |
elif cat == "slow grower":
|
| 575 |
-
|
| 576 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 577 |
elif cat == "turnaround":
|
| 578 |
tr.append("free cash flow turns negative again or debt is refinanced at a materially higher cost")
|
| 579 |
if e.get("roic") is not None:
|
| 580 |
-
tr.append(f"ROIC falls below 10% (now {e['roic'] * 100:.0f}%)"
|
|
|
|
| 581 |
tr.append("Piotroski F-score ≤ 3 or Beneish M above −1.78 at the next annual report")
|
| 582 |
ins = us.get("insiders") or {}
|
| 583 |
if ins.get("buy_usd", 0) > 0:
|
|
@@ -656,7 +710,7 @@ def us_lines(us: dict) -> list[str]:
|
|
| 656 |
if er.get("n_q"):
|
| 657 |
em.append(f"beat {er['beats_8q']}/{er['n_q']} recent quarters (avg surprise {er['avg_surprise_pct']:+.1f}%)")
|
| 658 |
if er.get("eps_revision_90d_pct") is not None:
|
| 659 |
-
em.append(
|
| 660 |
if er.get("revisions_30d"):
|
| 661 |
em.append(f"revisions 30d: {er['revisions_30d']['up']} up / {er['revisions_30d']['down']} down")
|
| 662 |
if em:
|
|
|
|
| 175 |
return {"score": pts, "signals": why}
|
| 176 |
|
| 177 |
|
| 178 |
+
def fx_local(c: dict) -> float:
|
| 179 |
+
"""Reporting-currency units per USD for an SF1 row. Statement fields (assets, revenue, FCF…)
|
| 180 |
+
are in the filer's currency while marketcap/ev are in USD — Alibaba files in CNY (≈6.8),
|
| 181 |
+
TSMC in TWD (≈31.6), Novo in DKK. Derived from the row's own USD ratios (P/S, then P/E);
|
| 182 |
+
1.0 for USD filers or when it can't be told."""
|
| 183 |
+
mc = _f(c.get("marketcap"))
|
| 184 |
+
if not mc or mc <= 0:
|
| 185 |
+
return 1.0
|
| 186 |
+
for num, ratio in (("revenue", "ps"), ("netinc", "pe")):
|
| 187 |
+
a, r = _f(c.get(num)), _f(c.get(ratio))
|
| 188 |
+
if a and r and a > 0 and r > 0:
|
| 189 |
+
fx = a * r / mc
|
| 190 |
+
return 1.0 if abs(fx - 1) < 0.03 or not (0.05 < fx < 50000) else fx
|
| 191 |
+
return 1.0
|
| 192 |
+
|
| 193 |
+
|
| 194 |
def altman_z(c: dict, mcap: float | None) -> float | None:
|
| 195 |
+
"""Classic public-company Z (1968). Not meaningful for banks/insurers — caller masks financials.
|
| 196 |
+
Market value is put on the statements' currency basis first (a CNY balance sheet against a USD
|
| 197 |
+
market cap made Alibaba look distressed: Z 1.6 instead of 3.1)."""
|
| 198 |
ta, tl = _f(c.get("assets")), _f(c.get("liabilities"))
|
| 199 |
if not ta or not tl:
|
| 200 |
return None
|
| 201 |
wc = _f(c.get("workingcapital")) or ((_f(c.get("assetsc")) or 0.0) - (_f(c.get("liabilitiesc")) or 0.0))
|
| 202 |
re, ebit, rev = _f(c.get("retearn")) or 0.0, _f(c.get("ebit")) or 0.0, _f(c.get("revenue")) or 0.0
|
| 203 |
+
mc = (mcap or _f(c.get("marketcap")) or 0.0) * fx_local(c)
|
| 204 |
z = 1.2 * wc / ta + 1.4 * re / ta + 3.3 * ebit / ta + 0.6 * mc / tl + 1.0 * rev / ta
|
| 205 |
return round(min(z, 30.0), 2) # 30+ is "irrelevantly safe"
|
| 206 |
|
|
|
|
| 255 |
c = a[0]
|
| 256 |
ni, cfo, capex, fcf = _f(c.get("netinc")), _f(c.get("ncfo")), _f(c.get("capex")), _f(c.get("fcf"))
|
| 257 |
da, rev, sh = _f(c.get("depamor")), _f(c.get("revenue")), _f(c.get("sharesbas"))
|
| 258 |
+
mc_usd = mcap or _f(c.get("marketcap"))
|
| 259 |
+
fx = fx_local(c)
|
| 260 |
+
mc = mc_usd * fx if mc_usd else None # statements' currency
|
| 261 |
ta = _f(c.get("assets"))
|
| 262 |
if ni is not None and cfo is not None and ta:
|
| 263 |
out["accruals"] = round((ni - cfo) / ta, 3) # Sloan: > 0.10 is a red flag
|
|
|
|
| 265 |
out["cash_conversion"] = round(fcf / ni, 2) if ni > 0 else None # FCF / net income
|
| 266 |
if ni is not None and da is not None and capex is not None and sh:
|
| 267 |
oe = ni + da - abs(capex) # Buffett owner earnings (full capex)
|
| 268 |
+
if fx == 1.0:
|
| 269 |
+
out["owner_earnings_ps"] = round(oe / sh, 2)
|
| 270 |
+
if price:
|
| 271 |
+
out["owner_earnings_yield"] = round(oe / sh / price, 4)
|
| 272 |
+
elif mc: # foreign filer: whole-company basis
|
| 273 |
+
out["owner_earnings_yield"] = round(oe / mc, 4)
|
| 274 |
if fcf is not None and mc:
|
| 275 |
out["fcf_yield"] = round(fcf / mc, 4)
|
| 276 |
ebit, ev = _f(c.get("ebit")), _f(c.get("ev"))
|
| 277 |
if ebit is not None and ev and ev > 0:
|
| 278 |
+
out["greenblatt_ey"] = round(ebit / (ev * fx), 4) # EBIT / EV
|
| 279 |
out["roic"] = _f(c.get("roic"))
|
| 280 |
# 5-year incremental ROIC: Δ NOPAT / Δ invested capital
|
| 281 |
if len(a) >= 6:
|
|
|
|
| 324 |
out["rule_of_40"] = round((r1 + fcf / rev) * 100, 1)
|
| 325 |
# Graham number and Lynch PEG
|
| 326 |
eps, bvps = _f(c.get("epsdil")) or _f(c.get("eps")), _f(c.get("bvps"))
|
| 327 |
+
if eps and bvps and eps > 0 and bvps > 0 and fx == 1.0:
|
| 328 |
out["graham_number"] = round(math.sqrt(22.5 * eps * bvps), 2)
|
| 329 |
eps3 = [_f(r.get("epsdil")) or _f(r.get("eps")) for r in a[:4]]
|
| 330 |
if len(eps3) == 4 and eps3[0] and eps3[3] and eps3[0] > 0 and eps3[3] > 0:
|
|
|
|
| 333 |
g = out.get("eps_cagr_3y")
|
| 334 |
if pe and pe > 0 and g and g > 0:
|
| 335 |
out["peg_3y"] = round(pe / (g * 100), 2) # Lynch: P/E ÷ EPS growth
|
| 336 |
+
out["lynch_category"] = lynch_category(a, sector, mc_usd, dps)
|
| 337 |
return out
|
| 338 |
|
| 339 |
|
|
|
|
| 354 |
ni_prev = [_f(r.get("netinc")) for r in a[1:3]] # a loss within the last two years
|
| 355 |
if ni_now is not None and ni_now > 0 and any(x is not None and x < 0 for x in ni_prev):
|
| 356 |
return "turnaround"
|
| 357 |
+
# a cyclical is a business whose sales follow the cycle (oil, autos, airlines) — not every
|
| 358 |
+
# name filed under a cyclical SECTOR: MercadoLibre growing 45% a year with no down year is a
|
| 359 |
+
# fast grower, and judging it on "peak margins with inventory building" was the wrong yardstick
|
| 360 |
+
rev_dip = any(x is not None and y is not None and x < y for x, y in zip(revs[:3], revs[1:4]))
|
| 361 |
+
if sector in CYCLICAL and sector != "Financial Services" and (rev_dip or g is None or g < 0.15):
|
| 362 |
return "cyclical"
|
| 363 |
if g is not None and g >= 0.20:
|
| 364 |
return "fast grower"
|
|
|
|
| 470 |
now, ago = _f(x.get("eps_estimate_average")), _f(x.get("eps_estimate_average_90_days_ago"))
|
| 471 |
if now and ago:
|
| 472 |
out["fy_eps_est"] = now
|
| 473 |
+
out["eps_revision_90d_pct"] = round((now - ago) / abs(ago) * 100, 1) # a deeper loss is a cut, not a rise
|
| 474 |
up, dn = _f(x.get("eps_estimate_revision_up_trailing_30_days")), _f(x.get("eps_estimate_revision_down_trailing_30_days"))
|
| 475 |
if up is not None or dn is not None:
|
| 476 |
out["revisions_30d"] = {"up": int(up or 0), "down": int(dn or 0)}
|
|
|
|
| 576 |
fl.append(f"insiders net sellers (${ins['sell_usd'] / 1e6:.0f}M sold vs ${ins.get('buy_usd', 0) / 1e6:.0f}M bought, 6m)")
|
| 577 |
er = us.get("earnings") or {}
|
| 578 |
if (er.get("eps_revision_90d_pct") or 0) < -5:
|
| 579 |
+
fl.append(_rev_words(er["eps_revision_90d_pct"]))
|
| 580 |
return fl
|
| 581 |
|
| 582 |
|
| 583 |
+
def _rev_words(pct: float, brief: bool = False) -> str:
|
| 584 |
+
"""A cut beyond −100% means the estimate crossed zero — "cut 161%" reads as nonsense."""
|
| 585 |
+
if pct <= -100:
|
| 586 |
+
return "EPS estimates swung from a profit to a loss in 90 days"
|
| 587 |
+
if pct >= 100 and brief:
|
| 588 |
+
return f"FY EPS estimate more than doubled over 90d ({pct:+.0f}%)"
|
| 589 |
+
return f"FY EPS estimate {pct:+.1f}% over 90d" if brief else f"estimates cut {abs(pct):.0f}% in 90 days"
|
| 590 |
+
|
| 591 |
+
|
| 592 |
def sell_triggers(d: dict, us: dict) -> list[str]:
|
| 593 |
"""Fisher/Lynch sell discipline: the observable facts that would break the thesis."""
|
| 594 |
e = us.get("econ") or {}
|
|
|
|
| 597 |
def _pct(x):
|
| 598 |
return f"{x * 100:.0f}%" if isinstance(x, (int, float)) else None
|
| 599 |
g, peg, payout = _pct(d.get("rev_growth")), d.get("peg"), e.get("fcf_payout") or d.get("payout_ratio")
|
| 600 |
+
# a tripwire is a line not yet crossed: thresholds are set relative to today's reading, so a
|
| 601 |
+
# Buy More never ships with its own sell trigger already hit (Salesforce "below 15%" at 11%)
|
| 602 |
+
rg = d.get("rev_growth")
|
| 603 |
if cat == "fast grower":
|
| 604 |
+
if isinstance(rg, (int, float)) and rg <= 0:
|
| 605 |
+
tr.append(f"revenue keeps shrinking for two more quarters (now {g})")
|
| 606 |
+
elif isinstance(rg, (int, float)) and rg < 0.20:
|
| 607 |
+
thr = int(rg * 100 // 2)
|
| 608 |
+
tr.append(f"revenue growth falls below {thr}% for two consecutive quarters (now {g})")
|
| 609 |
+
else:
|
| 610 |
+
tr.append(f"revenue growth falls below 15% for two consecutive quarters (now {g})" if g
|
| 611 |
+
else "revenue growth falls below 15% for two consecutive quarters")
|
| 612 |
tr.append("gross margin contracts more than 300bp year on year")
|
| 613 |
elif cat == "stalwart":
|
| 614 |
+
if isinstance(peg, (int, float)) and peg > 2.5:
|
| 615 |
+
tr.append(f"two straight years without earnings growth — at a PEG of {peg:.1f} the price "
|
| 616 |
+
f"already assumes growth that has to arrive")
|
| 617 |
+
else:
|
| 618 |
+
tr.append(f"two straight years without earnings growth, or PEG above 2.5 (now {peg:.1f})"
|
| 619 |
+
if isinstance(peg, (int, float)) else "two straight years without earnings growth, or PEG above 2.5")
|
| 620 |
elif cat == "cyclical":
|
| 621 |
tr.append("peak margins with inventory building faster than sales — sell strength, not weakness"
|
| 622 |
+ (f" (revenue growth now {g})" if g else ""))
|
| 623 |
elif cat == "slow grower":
|
| 624 |
+
if isinstance(payout, (int, float)) and payout > 0.9:
|
| 625 |
+
tr.append(f"the dividend stays uncovered by free cash flow for another year, or is cut "
|
| 626 |
+
f"(FCF payout now {payout * 100:.0f}%)")
|
| 627 |
+
else:
|
| 628 |
+
tr.append("dividend growth stops or FCF payout exceeds 90%"
|
| 629 |
+
+ (f" (now {payout * 100:.0f}%)" if isinstance(payout, (int, float)) else ""))
|
| 630 |
elif cat == "turnaround":
|
| 631 |
tr.append("free cash flow turns negative again or debt is refinanced at a materially higher cost")
|
| 632 |
if e.get("roic") is not None:
|
| 633 |
+
tr.append(f"ROIC falls below 10% (now {e['roic'] * 100:.0f}%)" if e["roic"] >= 0.10 else
|
| 634 |
+
f"ROIC fails to climb back above 10% within two years (now {e['roic'] * 100:.0f}%)")
|
| 635 |
tr.append("Piotroski F-score ≤ 3 or Beneish M above −1.78 at the next annual report")
|
| 636 |
ins = us.get("insiders") or {}
|
| 637 |
if ins.get("buy_usd", 0) > 0:
|
|
|
|
| 710 |
if er.get("n_q"):
|
| 711 |
em.append(f"beat {er['beats_8q']}/{er['n_q']} recent quarters (avg surprise {er['avg_surprise_pct']:+.1f}%)")
|
| 712 |
if er.get("eps_revision_90d_pct") is not None:
|
| 713 |
+
em.append(_rev_words(er["eps_revision_90d_pct"], brief=True))
|
| 714 |
if er.get("revisions_30d"):
|
| 715 |
em.append(f"revisions 30d: {er['revisions_30d']['up']} up / {er['revisions_30d']['down']} down")
|
| 716 |
if em:
|
src/market_data.py
CHANGED
|
@@ -467,6 +467,24 @@ def fetch_sharadar(ticker: str) -> dict:
|
|
| 467 |
out = dict(_fetch_sharadar_raw(_SHARE_CLASS_ALIAS[t]))
|
| 468 |
if out:
|
| 469 |
out["fund_note"] = f"statements filed under {_SHARE_CLASS_ALIAS[t]}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 470 |
return out
|
| 471 |
|
| 472 |
|
|
|
|
| 467 |
out = dict(_fetch_sharadar_raw(_SHARE_CLASS_ALIAS[t]))
|
| 468 |
if out:
|
| 469 |
out["fund_note"] = f"statements filed under {_SHARE_CLASS_ALIAS[t]}"
|
| 470 |
+
return _to_usd(out)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def _to_usd(out: dict) -> dict:
|
| 474 |
+
"""SF1 per-share and statement fields are in the filer's reporting currency; price, P/E and
|
| 475 |
+
market cap are USD. A foreign filer quoted in USD (Spotify reports in EUR) would otherwise have
|
| 476 |
+
its DCF built on euros against a dollar price. FX = net income × P/E ÷ market cap."""
|
| 477 |
+
ni, pe, mc = out.get("sh_netinc"), out.get("pe"), out.get("mcap")
|
| 478 |
+
if not all(isinstance(x, (int, float)) and x > 0 for x in (ni, pe, mc)):
|
| 479 |
+
return out
|
| 480 |
+
fx = ni * pe / mc
|
| 481 |
+
if abs(fx - 1) < 0.03 or not (0.05 < fx < 50000):
|
| 482 |
+
return out
|
| 483 |
+
out = dict(out)
|
| 484 |
+
for k in ("eps_ttm", "bvps", "fcfps", "sh_netinc", "sh_depamor"):
|
| 485 |
+
if isinstance(out.get(k), (int, float)):
|
| 486 |
+
out[k] = out[k] / fx
|
| 487 |
+
out["fx_reporting"] = round(fx, 4)
|
| 488 |
return out
|
| 489 |
|
| 490 |
|
src/metrics.py
CHANGED
|
@@ -1224,6 +1224,29 @@ SPY_SECTORS_FALLBACK = {"Technology": 0.33, "Financial Services": 0.13, "Consume
|
|
| 1224 |
"Real Estate": 0.02, "Basic Materials": 0.02}
|
| 1225 |
|
| 1226 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1227 |
def active_sector_weights(pm_sectors: dict, bench_sectors: dict) -> list[dict]:
|
| 1228 |
"""Book vs benchmark sector weights — the active bets, largest first."""
|
| 1229 |
if not bench_sectors:
|
|
|
|
| 1224 |
"Real Estate": 0.02, "Basic Materials": 0.02}
|
| 1225 |
|
| 1226 |
|
| 1227 |
+
def sector_card_vs_bench(cards: list[dict], pm: dict, active: list[dict] | None) -> None:
|
| 1228 |
+
"""Restate the sector check against the benchmark: 39% Communication Services is a 30-point
|
| 1229 |
+
overweight against 9% in the S&P 500 — "inside a healthy band of 15–45%" undersold it."""
|
| 1230 |
+
if not active:
|
| 1231 |
+
return
|
| 1232 |
+
for c in cards:
|
| 1233 |
+
if c.get("check") != "Sector concentration":
|
| 1234 |
+
continue
|
| 1235 |
+
sa = {s: v for s, v in (pm.get("sector_allocation") or {}).items() if s != "Diversified fund"}
|
| 1236 |
+
if not sa:
|
| 1237 |
+
return
|
| 1238 |
+
s, wt = max(sa.items(), key=lambda kv: kv[1])
|
| 1239 |
+
row = next((x for x in active if str(x.get("sector")).title() == str(s).title()), None)
|
| 1240 |
+
if not row or not isinstance(row.get("benchmark"), (int, float)):
|
| 1241 |
+
return
|
| 1242 |
+
b = float(row["benchmark"])
|
| 1243 |
+
over = wt - b
|
| 1244 |
+
c["status"] = "ALERT" if wt > SECTOR_CAP_HI or (wt > SECTOR_CAP_BASE and over > 0.25) else \
|
| 1245 |
+
"WATCH" if wt > SECTOR_CAP_BASE or over > 0.15 else "OK"
|
| 1246 |
+
c["detail"] = (f"{s} is {wt * 100:.0f}% of the portfolio vs {b * 100:.0f}% of the benchmark "
|
| 1247 |
+
f"({over * 100:+.0f} points; a single sector above {SECTOR_CAP_BASE * 100:.0f}% is a concentrated bet).")
|
| 1248 |
+
return
|
| 1249 |
+
|
| 1250 |
def active_sector_weights(pm_sectors: dict, bench_sectors: dict) -> list[dict]:
|
| 1251 |
"""Book vs benchmark sector weights — the active bets, largest first."""
|
| 1252 |
if not bench_sectors:
|
src/orchestrator.py
CHANGED
|
@@ -329,6 +329,28 @@ def _llm_local_candidates(holdings: list[dict], gaps: list[str]) -> list[dict]:
|
|
| 329 |
return picks
|
| 330 |
|
| 331 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s: float | None = None) -> dict:
|
| 333 |
t0 = time.time()
|
| 334 |
budget = float(budget_s or 720)
|
|
@@ -424,6 +446,8 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 424 |
risk["active_sectors"] = M.active_sector_weights(pm.get("sector_allocation") or {}, spy_lt.get("sectors") or {})
|
| 425 |
except Exception:
|
| 426 |
pass
|
|
|
|
|
|
|
| 427 |
cards += _risk_cards(risk, holdings, context)
|
| 428 |
needs = M.diagnose_needs(pm, risk, holdings, context) # what THIS book needs — drives everything below
|
| 429 |
REV.strong_ok.cautious = bool(needs.get("_cautious")) # noqa — reset every run (a BBY at 64 with a
|
|
@@ -435,7 +459,11 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 435 |
"holdings": [{"ticker": h["symbol"], "sector": h["data"].get("sector"),
|
| 436 |
"weight": round(h["weight"], 3), "pl_pct": round(h["pl_pct"], 3)} for h in holdings],
|
| 437 |
"metrics": {k: v for k, v in pm.items() if k != "equity_curve"},
|
| 438 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 439 |
"healthy_bands": {"per_name_cap": M.effective_name_cap(len(holdings)),
|
| 440 |
"sector_band": [M.SECTOR_CAP_LO, M.SECTOR_CAP_HI]},
|
| 441 |
"investor_context": context or "not provided — judge the portfolio on its own terms",
|
|
@@ -1169,6 +1197,7 @@ def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s:
|
|
| 1169 |
construction["skip_narrative"] = True
|
| 1170 |
degraded.append("plan narrative skipped (time budget)")
|
| 1171 |
construction["sector_of"] = sector_of
|
|
|
|
| 1172 |
plan = REV.build_plan(holdings, decisions, target, eligible,
|
| 1173 |
health, pm.get("total_pl_pct"), cards, context, needs, construction)
|
| 1174 |
# watchlist: ideas the plan could not fund, and screened-out names with the condition that
|
|
@@ -1456,7 +1485,8 @@ def _instrument_candidates(needs: dict, holdings: list[dict], risk: dict) -> lis
|
|
| 1456 |
out.append({"ticker": i["ticker"], "sector": "Diversified fund", "instrument": True, "need_target": "income",
|
| 1457 |
"signals": ["instrument — dividend equity ETF"], "rank_pct": None})
|
| 1458 |
ccy = (risk or {}).get("currency_exposure") or {}
|
| 1459 |
-
|
|
|
|
| 1460 |
for i in by_need.get("geography", [])[:1]:
|
| 1461 |
if i["ticker"] not in held:
|
| 1462 |
out.append({"ticker": i["ticker"], "sector": "Diversified fund", "instrument": True, "need_target": "diversifier",
|
|
|
|
| 329 |
return picks
|
| 330 |
|
| 331 |
|
| 332 |
+
def _non_us_companies(holdings: list[dict]) -> dict:
|
| 333 |
+
"""Where the BUSINESSES are, not the trading currency: Alibaba, TSMC and Novo trade in USD
|
| 334 |
+
but are 20%+ of a book that "currency exposure: USD 100%" once called purely domestic."""
|
| 335 |
+
from .market_data import _sharadar_ticker_meta
|
| 336 |
+
w, names = 0.0, []
|
| 337 |
+
for h in holdings:
|
| 338 |
+
t = h["symbol"]
|
| 339 |
+
if str(h["data"].get("quote_type") or "").upper() in M.FUND_TYPES:
|
| 340 |
+
continue
|
| 341 |
+
loc = ""
|
| 342 |
+
if "." in t:
|
| 343 |
+
loc = "foreign listing"
|
| 344 |
+
else:
|
| 345 |
+
try:
|
| 346 |
+
loc = str((_sharadar_ticker_meta(t) or {}).get("location") or "")
|
| 347 |
+
except Exception:
|
| 348 |
+
loc = ""
|
| 349 |
+
if loc and "U.S.A" not in loc:
|
| 350 |
+
w += float(h["weight"])
|
| 351 |
+
names.append(f"{t} ({loc.split(';')[-1].strip()})")
|
| 352 |
+
return {"weight": round(w, 4), "names": names}
|
| 353 |
+
|
| 354 |
def run_analysis(rows: list[dict], emit, context: dict | None = None, budget_s: float | None = None) -> dict:
|
| 355 |
t0 = time.time()
|
| 356 |
budget = float(budget_s or 720)
|
|
|
|
| 446 |
risk["active_sectors"] = M.active_sector_weights(pm.get("sector_allocation") or {}, spy_lt.get("sectors") or {})
|
| 447 |
except Exception:
|
| 448 |
pass
|
| 449 |
+
risk["non_us_companies"] = _non_us_companies(holdings)
|
| 450 |
+
M.sector_card_vs_bench(cards, pm, risk.get("active_sectors"))
|
| 451 |
cards += _risk_cards(risk, holdings, context)
|
| 452 |
needs = M.diagnose_needs(pm, risk, holdings, context) # what THIS book needs — drives everything below
|
| 453 |
REV.strong_ok.cautious = bool(needs.get("_cautious")) # noqa — reset every run (a BBY at 64 with a
|
|
|
|
| 459 |
"holdings": [{"ticker": h["symbol"], "sector": h["data"].get("sector"),
|
| 460 |
"weight": round(h["weight"], 3), "pl_pct": round(h["pl_pct"], 3)} for h in holdings],
|
| 461 |
"metrics": {k: v for k, v in pm.items() if k != "equity_curve"},
|
| 462 |
+
# one beta in the narrative: the realised beta in metrics; the factor model's own market
|
| 463 |
+
# beta (1.19 vs 1.14) stays in the analytics table, labelled as such
|
| 464 |
+
"risk_analytics": {k: ({kk: vv for kk, vv in v.items() if kk != "market_beta"} if k == "factor_betas" and isinstance(v, dict) else v)
|
| 465 |
+
for k, v in risk.items()},
|
| 466 |
+
"benchmark": BENCH_NAMES.get(bench, bench), "risk_scorecard": cards,
|
| 467 |
"healthy_bands": {"per_name_cap": M.effective_name_cap(len(holdings)),
|
| 468 |
"sector_band": [M.SECTOR_CAP_LO, M.SECTOR_CAP_HI]},
|
| 469 |
"investor_context": context or "not provided — judge the portfolio on its own terms",
|
|
|
|
| 1197 |
construction["skip_narrative"] = True
|
| 1198 |
degraded.append("plan narrative skipped (time budget)")
|
| 1199 |
construction["sector_of"] = sector_of
|
| 1200 |
+
construction["current_beta"] = pm.get("realized_beta") # one beta across the report
|
| 1201 |
plan = REV.build_plan(holdings, decisions, target, eligible,
|
| 1202 |
health, pm.get("total_pl_pct"), cards, context, needs, construction)
|
| 1203 |
# watchlist: ideas the plan could not fund, and screened-out names with the condition that
|
|
|
|
| 1485 |
out.append({"ticker": i["ticker"], "sector": "Diversified fund", "instrument": True, "need_target": "income",
|
| 1486 |
"signals": ["instrument — dividend equity ETF"], "rank_pct": None})
|
| 1487 |
ccy = (risk or {}).get("currency_exposure") or {}
|
| 1488 |
+
non_us_w = float(((risk or {}).get("non_us_companies") or {}).get("weight") or 0.0)
|
| 1489 |
+
if len(ccy) == 1 and "USD" in ccy and len(holdings) >= 3 and non_us_w < 0.10: # ADRs are international too
|
| 1490 |
for i in by_need.get("geography", [])[:1]:
|
| 1491 |
if i["ticker"] not in held:
|
| 1492 |
out.append({"ticker": i["ticker"], "sector": "Diversified fund", "instrument": True, "need_target": "diversifier",
|
src/pdf_report.py
CHANGED
|
@@ -248,6 +248,19 @@ class _HealthBlock(Flowable):
|
|
| 248 |
py -= 13.5
|
| 249 |
|
| 250 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
def _wordmark(c, x, y, size=11.5):
|
| 252 |
"""Vitals, set like the EmergentSignals wordmark: the three state circles, then the name in Inter
|
| 253 |
600 with the green-dot i."""
|
|
@@ -437,11 +450,11 @@ def _build_pdf(res: dict) -> bytes:
|
|
| 437 |
bits.append("<b>Style tilts:</b> " + _txt(", ".join(f"{k} {v:+.2f}" for k, v in ft["tilts"].items())))
|
| 438 |
fb = rk.get("factor_betas") or {}
|
| 439 |
if fb.get("betas"):
|
| 440 |
-
bits.append(f"<b>Measured factor betas (market beta {fb['market_beta']}):</b> "
|
| 441 |
+ _txt(", ".join(f"{k} {v:+.2f}" for k, v in fb["betas"].items())))
|
| 442 |
br = rk.get("benchmark_relative") or {}
|
| 443 |
if br:
|
| 444 |
-
bits.append(f"<b>Vs {_txt(bn)}:</b> " + _txt(
|
| 445 |
if rk.get("active_sectors"):
|
| 446 |
bits.append("<b>Active sector bets:</b> " + _txt(", ".join(
|
| 447 |
f"{x['sector']} {x['active'] * 100:+.0f}pp" for x in rk["active_sectors"][:6])))
|
|
@@ -461,9 +474,9 @@ def _build_pdf(res: dict) -> bytes:
|
|
| 461 |
"; ".join(v["label"] for v in needs.values() if v.get("label"))), S_BODY))
|
| 462 |
E.append(Spacer(1, 3))
|
| 463 |
for g in (res.get("plan") or {}).get("gap_search") or []:
|
| 464 |
-
line = (f"<b>{_txt(g['sector'])}:</b> {g['screened']}
|
| 465 |
+ (f"buyable today: {_txt(', '.join(g['buyable']))}" if g.get("buyable") else "none buyable today")
|
| 466 |
-
+ (f" ({_txt(g['why_not'])}
|
| 467 |
+ (f"; on the bench with entry conditions: {_txt(', '.join(g['bench']))}" if g.get("bench") else ""))
|
| 468 |
E.append(Paragraph(line, S_DIM)); E.append(Spacer(1, 2))
|
| 469 |
for a in alts:
|
|
@@ -515,6 +528,8 @@ def _build_pdf(res: dict) -> bytes:
|
|
| 515 |
E.append(Spacer(1, 4))
|
| 516 |
E.append(Paragraph("<b>Do nothing.</b> Nothing clears the hurdle for a trade; inactivity is the recommendation until a sell trigger fires.", S_BODY))
|
| 517 |
desk = []
|
|
|
|
|
|
|
| 518 |
for x in plan.get("tax_plan") or []:
|
| 519 |
desk.append(f"<b>Tax plan {_txt(x['ticker'])}:</b> {_txt(x['note'])}")
|
| 520 |
ra, rb = plan.get("risk_contributions_after") or {}, plan.get("risk_contributions") or {}
|
|
@@ -572,9 +587,9 @@ def _build_pdf(res: dict) -> bytes:
|
|
| 572 |
E.append(Spacer(1, 2))
|
| 573 |
rows3: list[list] = [["Holding", "Call", "Why"]]
|
| 574 |
for t in tri:
|
| 575 |
-
rows3.append([_txt(t.get("ticker")), _txt(t.get("disposition")),
|
| 576 |
Paragraph(_txt(t.get("note")), S_CELL)])
|
| 577 |
-
E.append(_table(rows3, [22 * mm,
|
| 578 |
|
| 579 |
target = res.get("target_portfolio") or []
|
| 580 |
if target:
|
|
@@ -627,9 +642,9 @@ def _build_pdf(res: dict) -> bytes:
|
|
| 627 |
E.append(Spacer(1, 3))
|
| 628 |
rows_d: list[list] = [["Holding", "Fundamentals", "As of", "Price as of"]]
|
| 629 |
for d in ds:
|
| 630 |
-
rows_d.append([_txt(d["ticker"]), _txt(d.get("fundamentals") or "?"),
|
| 631 |
_txt(d.get("fund_asof") or "—"), _txt(d.get("price_asof") or "—")])
|
| 632 |
-
E.append(_table(rows_d, [
|
| 633 |
aligns=["LEFT", "LEFT", "LEFT", "LEFT"]))
|
| 634 |
|
| 635 |
E.append(Spacer(1, 14))
|
|
|
|
| 248 |
py -= 13.5
|
| 249 |
|
| 250 |
|
| 251 |
+
def br_text(br: dict) -> str:
|
| 252 |
+
"""Benchmark-relative stats in words: 'active return +9.1%/yr', never 'active return ann 0.0908'."""
|
| 253 |
+
lab = {"upside_capture": "upside capture", "downside_capture": "downside capture", "sortino": "Sortino",
|
| 254 |
+
"calmar": "Calmar", "active_return_ann": "active return", "information_ratio": "information ratio"}
|
| 255 |
+
out = []
|
| 256 |
+
for k, v in br.items():
|
| 257 |
+
if not isinstance(v, (int, float)):
|
| 258 |
+
continue
|
| 259 |
+
out.append(f"{lab.get(k, k.replace('_', ' '))} {v * 100:+.1f}%/yr" if k.endswith("_ann") or "return" in k
|
| 260 |
+
else f"{lab.get(k, k.replace('_', ' '))} {v:.2f}")
|
| 261 |
+
return ", ".join(out)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
def _wordmark(c, x, y, size=11.5):
|
| 265 |
"""Vitals, set like the EmergentSignals wordmark: the three state circles, then the name in Inter
|
| 266 |
600 with the green-dot i."""
|
|
|
|
| 450 |
bits.append("<b>Style tilts:</b> " + _txt(", ".join(f"{k} {v:+.2f}" for k, v in ft["tilts"].items())))
|
| 451 |
fb = rk.get("factor_betas") or {}
|
| 452 |
if fb.get("betas"):
|
| 453 |
+
bits.append(f"<b>Measured factor betas (factor-model market beta {fb['market_beta']}):</b> "
|
| 454 |
+ _txt(", ".join(f"{k} {v:+.2f}" for k, v in fb["betas"].items())))
|
| 455 |
br = rk.get("benchmark_relative") or {}
|
| 456 |
if br:
|
| 457 |
+
bits.append(f"<b>Vs {_txt(bn)}:</b> " + _txt(br_text(br)))
|
| 458 |
if rk.get("active_sectors"):
|
| 459 |
bits.append("<b>Active sector bets:</b> " + _txt(", ".join(
|
| 460 |
f"{x['sector']} {x['active'] * 100:+.0f}pp" for x in rk["active_sectors"][:6])))
|
|
|
|
| 474 |
"; ".join(v["label"] for v in needs.values() if v.get("label"))), S_BODY))
|
| 475 |
E.append(Spacer(1, 3))
|
| 476 |
for g in (res.get("plan") or {}).get("gap_search") or []:
|
| 477 |
+
line = (f"<b>{_txt(g['sector'])}:</b> {g['screened']} name{'' if g['screened'] == 1 else 's'} screened — "
|
| 478 |
+ (f"buyable today: {_txt(', '.join(g['buyable']))}" if g.get("buyable") else "none buyable today")
|
| 479 |
+
+ (f"; {'the rest' if g.get('buyable') else 'all'} passed over — {_txt(g['why_not'])}" if g.get("why_not") else "")
|
| 480 |
+ (f"; on the bench with entry conditions: {_txt(', '.join(g['bench']))}" if g.get("bench") else ""))
|
| 481 |
E.append(Paragraph(line, S_DIM)); E.append(Spacer(1, 2))
|
| 482 |
for a in alts:
|
|
|
|
| 528 |
E.append(Spacer(1, 4))
|
| 529 |
E.append(Paragraph("<b>Do nothing.</b> Nothing clears the hurdle for a trade; inactivity is the recommendation until a sell trigger fires.", S_BODY))
|
| 530 |
desk = []
|
| 531 |
+
if plan.get("tax_summary"):
|
| 532 |
+
desk.append(f"<b>Tax, net:</b> {_txt(plan['tax_summary'])}")
|
| 533 |
for x in plan.get("tax_plan") or []:
|
| 534 |
desk.append(f"<b>Tax plan {_txt(x['ticker'])}:</b> {_txt(x['note'])}")
|
| 535 |
ra, rb = plan.get("risk_contributions_after") or {}, plan.get("risk_contributions") or {}
|
|
|
|
| 587 |
E.append(Spacer(1, 2))
|
| 588 |
rows3: list[list] = [["Holding", "Call", "Why"]]
|
| 589 |
for t in tri:
|
| 590 |
+
rows3.append([_txt(t.get("ticker")), Paragraph(_txt(t.get("disposition")), S_CELL),
|
| 591 |
Paragraph(_txt(t.get("note")), S_CELL)])
|
| 592 |
+
E.append(_table(rows3, [22 * mm, 34 * mm, 116 * mm]))
|
| 593 |
|
| 594 |
target = res.get("target_portfolio") or []
|
| 595 |
if target:
|
|
|
|
| 642 |
E.append(Spacer(1, 3))
|
| 643 |
rows_d: list[list] = [["Holding", "Fundamentals", "As of", "Price as of"]]
|
| 644 |
for d in ds:
|
| 645 |
+
rows_d.append([_txt(d["ticker"]), Paragraph(_txt(d.get("fundamentals") or "?"), S_CELL),
|
| 646 |
_txt(d.get("fund_asof") or "—"), _txt(d.get("price_asof") or "—")])
|
| 647 |
+
E.append(_table(rows_d, [24 * mm, 66 * mm, 30 * mm, 42 * mm],
|
| 648 |
aligns=["LEFT", "LEFT", "LEFT", "LEFT"]))
|
| 649 |
|
| 650 |
E.append(Spacer(1, 14))
|
src/personas.py
CHANGED
|
@@ -28,7 +28,9 @@ _RUBRIC = (
|
|
| 28 |
" <30 = name-specific damage — broken thesis, structural decline, imminent cliff; reserve "
|
| 29 |
"for names you would not hold at all.\n"
|
| 30 |
"Anchor at 50; deviate only on NAME-SPECIFIC evidence from the data, never market mood. "
|
| 31 |
-
"Every key_point and key_risk must cite an actual number or headline from the data.
|
|
|
|
|
|
|
| 32 |
'Respond ONLY with JSON: {"<TICKER>": {"conviction": <0-100>, '
|
| 33 |
'"key_point": "<=18 words, your strongest point, with a number", '
|
| 34 |
'"key_risk": "<=12 words"}, ...} covering EVERY ticker.'
|
|
@@ -137,7 +139,13 @@ _STRATEGIST_SYSTEM = (
|
|
| 137 |
"worst one-year drop they say they could stomach, liquidity_need = whether they need "
|
| 138 |
"some of this money within two years), judge SUITABILITY against it explicitly — e.g. a "
|
| 139 |
"stress loss deeper than their stated tolerance, or an illiquid/high-beta book for "
|
| 140 |
-
"someone who needs cash soon.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
"from the data. Respond ONLY with JSON: {"
|
| 142 |
'"strategy_read": "<2-3 sentences: what strategy this portfolio implies>", '
|
| 143 |
'"style_tilt": "<one short phrase>", '
|
|
|
|
| 28 |
" <30 = name-specific damage — broken thesis, structural decline, imminent cliff; reserve "
|
| 29 |
"for names you would not hold at all.\n"
|
| 30 |
"Anchor at 50; deviate only on NAME-SPECIFIC evidence from the data, never market mood. "
|
| 31 |
+
"Every key_point and key_risk must cite an actual number or headline from the data. "
|
| 32 |
+
"key_risk is a genuine downside for the holder — a position trading ABOVE its entry price is a "
|
| 33 |
+
"gain, never a risk; mention the entry price as overhead resistance only when the holding is underwater.\n"
|
| 34 |
'Respond ONLY with JSON: {"<TICKER>": {"conviction": <0-100>, '
|
| 35 |
'"key_point": "<=18 words, your strongest point, with a number", '
|
| 36 |
'"key_risk": "<=12 words"}, ...} covering EVERY ticker.'
|
|
|
|
| 139 |
"worst one-year drop they say they could stomach, liquidity_need = whether they need "
|
| 140 |
"some of this money within two years), judge SUITABILITY against it explicitly — e.g. a "
|
| 141 |
"stress loss deeper than their stated tolerance, or an illiquid/high-beta book for "
|
| 142 |
+
"someone who needs cash soon. currency_exposure is only the TRADING currency: use "
|
| 143 |
+
"risk_analytics.non_us_companies for where the businesses are — a book holding Alibaba or TSMC "
|
| 144 |
+
"through US listings is not purely domestic. Compare drawdowns by their exact multiple "
|
| 145 |
+
"(−39.5% vs −24.5% is 1.6×, never 'twice'); beta explains only beta × the benchmark move, so "
|
| 146 |
+
"attribute any loss beyond that to style or sector exposure instead of calling it consistent "
|
| 147 |
+
"with beta. Never quote raw field names (no underscores). "
|
| 148 |
+
"Plain English, no jargon; every claim cites a number "
|
| 149 |
"from the data. Respond ONLY with JSON: {"
|
| 150 |
'"strategy_read": "<2-3 sentences: what strategy this portfolio implies>", '
|
| 151 |
'"style_tilt": "<one short phrase>", '
|
src/report.py
CHANGED
|
@@ -71,7 +71,9 @@ def assemble(holdings, pm, cards, decisions, panel, strat, cio, errors, news=Non
|
|
| 71 |
"price_asof": h["data"].get("price_asof"), "data_flags": h["data"].get("data_flags") or [],
|
| 72 |
"lifecycle": dcf.get("lifecycle"), "flags": dcf.get("flags") or [],
|
| 73 |
"strengths": [v["key_point"] for v in lens_points.values() if v.get("key_point")][:3],
|
| 74 |
-
|
|
|
|
|
|
|
| 75 |
"lens_scores": dec["scores"],
|
| 76 |
"news": [{"headline": n.get("headline", ""), "sentiment": n.get("sentiment", "")}
|
| 77 |
for n in news.get(t, [])[:4]],
|
|
@@ -198,11 +200,12 @@ def _markdown(res: dict, panel: dict) -> str:
|
|
| 198 |
+ ", ".join(f"{k} {v:+.2f}" for k, v in ft["tilts"].items()))
|
| 199 |
fb = rk.get("factor_betas") or {}
|
| 200 |
if fb.get("betas"):
|
| 201 |
-
L.append(f"**Measured factor betas (vs {bn}, market beta {fb['market_beta']}):** "
|
| 202 |
+ ", ".join(f"{k} {v:+.2f}" for k, v in fb["betas"].items()))
|
| 203 |
br = rk.get("benchmark_relative") or {}
|
| 204 |
if br:
|
| 205 |
-
|
|
|
|
| 206 |
if rk.get("active_sectors"):
|
| 207 |
L.append(f"**Active sector bets vs {bn}:** " + ", ".join(
|
| 208 |
f"{x['sector']} {x['active'] * 100:+.0f}pp ({x['book'] * 100:.0f}% vs {x['benchmark'] * 100:.0f}%)" for x in rk["active_sectors"][:6]))
|
|
@@ -220,6 +223,8 @@ def _markdown(res: dict, panel: dict) -> str:
|
|
| 220 |
if plan.get("cash"):
|
| 221 |
L.append(f"**Unallocated cash:** {plan['cash'] * 100:.1f}% of the book held as dry powder for the watchlist "
|
| 222 |
f"(the committee's ideas could not absorb every sale at sensible sizes).")
|
|
|
|
|
|
|
| 223 |
for x in plan.get("tax_plan") or []:
|
| 224 |
L.append(f"- **Tax plan {x['ticker']}:** {x['note']}")
|
| 225 |
for x in plan.get("watchlist") or []:
|
|
@@ -257,9 +262,9 @@ def _markdown(res: dict, panel: dict) -> str:
|
|
| 257 |
if needs:
|
| 258 |
L.append("*What this portfolio needs:* " + "; ".join(v["label"] for v in needs.values() if v.get("label")))
|
| 259 |
for g in (res.get("plan") or {}).get("gap_search") or []:
|
| 260 |
-
L.append(f"- *{g['sector']}:* {g['screened']}
|
| 261 |
+ (f"buyable today: {', '.join(g['buyable'])}" if g.get("buyable") else "none buyable today")
|
| 262 |
-
+ (f" ({g['why_not']}
|
| 263 |
+ (f"; on the bench: {', '.join(g['bench'])}" if g.get("bench") else ""))
|
| 264 |
for a in res["alternatives"]:
|
| 265 |
fit = a.get("fit") or {}
|
|
|
|
| 71 |
"price_asof": h["data"].get("price_asof"), "data_flags": h["data"].get("data_flags") or [],
|
| 72 |
"lifecycle": dcf.get("lifecycle"), "flags": dcf.get("flags") or [],
|
| 73 |
"strengths": [v["key_point"] for v in lens_points.values() if v.get("key_point")][:3],
|
| 74 |
+
# the weakest lens speaks first: its risk is the committee's real top concern
|
| 75 |
+
"risks": [v["key_risk"] for k, v in sorted(lens_points.items(), key=lambda kv: (dec["scores"] or {}).get(kv[0], 50))
|
| 76 |
+
if v.get("key_risk")][:3],
|
| 77 |
"lens_scores": dec["scores"],
|
| 78 |
"news": [{"headline": n.get("headline", ""), "sentiment": n.get("sentiment", "")}
|
| 79 |
for n in news.get(t, [])[:4]],
|
|
|
|
| 200 |
+ ", ".join(f"{k} {v:+.2f}" for k, v in ft["tilts"].items()))
|
| 201 |
fb = rk.get("factor_betas") or {}
|
| 202 |
if fb.get("betas"):
|
| 203 |
+
L.append(f"**Measured factor betas (vs {bn}, factor-model market beta {fb['market_beta']}):** "
|
| 204 |
+ ", ".join(f"{k} {v:+.2f}" for k, v in fb["betas"].items()))
|
| 205 |
br = rk.get("benchmark_relative") or {}
|
| 206 |
if br:
|
| 207 |
+
from .pdf_report import br_text
|
| 208 |
+
L.append(f"**Vs {bn}:** " + br_text(br))
|
| 209 |
if rk.get("active_sectors"):
|
| 210 |
L.append(f"**Active sector bets vs {bn}:** " + ", ".join(
|
| 211 |
f"{x['sector']} {x['active'] * 100:+.0f}pp ({x['book'] * 100:.0f}% vs {x['benchmark'] * 100:.0f}%)" for x in rk["active_sectors"][:6]))
|
|
|
|
| 223 |
if plan.get("cash"):
|
| 224 |
L.append(f"**Unallocated cash:** {plan['cash'] * 100:.1f}% of the book held as dry powder for the watchlist "
|
| 225 |
f"(the committee's ideas could not absorb every sale at sensible sizes).")
|
| 226 |
+
if plan.get("tax_summary"):
|
| 227 |
+
L.append(f"**Tax, net:** {plan['tax_summary']}")
|
| 228 |
for x in plan.get("tax_plan") or []:
|
| 229 |
L.append(f"- **Tax plan {x['ticker']}:** {x['note']}")
|
| 230 |
for x in plan.get("watchlist") or []:
|
|
|
|
| 262 |
if needs:
|
| 263 |
L.append("*What this portfolio needs:* " + "; ".join(v["label"] for v in needs.values() if v.get("label")))
|
| 264 |
for g in (res.get("plan") or {}).get("gap_search") or []:
|
| 265 |
+
L.append(f"- *{g['sector']}:* {g['screened']} name{'' if g['screened'] == 1 else 's'} screened — "
|
| 266 |
+ (f"buyable today: {', '.join(g['buyable'])}" if g.get("buyable") else "none buyable today")
|
| 267 |
+
+ (f"; {'the rest' if g.get('buyable') else 'all'} passed over — {g['why_not']}" if g.get("why_not") else "")
|
| 268 |
+ (f"; on the bench: {', '.join(g['bench'])}" if g.get("bench") else ""))
|
| 269 |
for a in res["alternatives"]:
|
| 270 |
fit = a.get("fit") or {}
|
src/revival.py
CHANGED
|
@@ -53,10 +53,17 @@ def triage(holdings: list[dict], decisions: dict, bought: set | None = None, sol
|
|
| 53 |
note = f"{cur}; price {up / (1 + up) * 100:.0f}% below estimated worth" \
|
| 54 |
if isinstance(up, (int, float)) else cur
|
| 55 |
d = {"ticker": t, "disposition": "average down", "note": note}
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
be = (h["qty"] * h["entry"] + add_qty * h["price"]) / (h["qty"] + add_qty)
|
| 59 |
-
d["note"] += (f";
|
| 60 |
f"{h['entry']:.2f} to {be:.2f}")
|
| 61 |
out.append(d)
|
| 62 |
elif dec["action"] in ("Sell", "Trim"):
|
|
@@ -72,9 +79,15 @@ def triage(holdings: list[dict], decisions: dict, bought: set | None = None, sol
|
|
| 72 |
"note": f"{cur}; weak backing and a negative expected payoff — the first source "
|
| 73 |
f"of funds when a better idea needs capital"})
|
| 74 |
elif dec["conviction"] >= 55 and isinstance(up, (int, float)) and up >= 0.15:
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
elif dec["conviction"] < 50:
|
| 79 |
out.append({"ticker": t, "disposition": "hold — too small to matter",
|
| 80 |
"note": f"{cur}; conviction is weak but the position is below the trading band — "
|
|
@@ -161,7 +174,8 @@ def switch_pairs(holdings: list[dict], decisions: dict, candidates: list[dict],
|
|
| 161 |
# ---------------- US tax: wash-sale awareness + tax-loss harvesting ----------------
|
| 162 |
|
| 163 |
def harvest_pairs(holdings: list[dict], decisions: dict, candidates: list[dict],
|
| 164 |
-
cand_hist=None, port_hist=None
|
|
|
|
| 165 |
"""US listings held at a loss ≥10% that the committee still likes (Keep/Buy More): sell to
|
| 166 |
book the loss, buy a highly correlated but NOT substantially identical substitute (a
|
| 167 |
same-sector name or sector ETF with ≥0.7 correlation), re-enter after 31 days if wanted.
|
|
@@ -173,7 +187,9 @@ def harvest_pairs(holdings: list[dict], decisions: dict, candidates: list[dict],
|
|
| 173 |
return out
|
| 174 |
for h in holdings:
|
| 175 |
t = h["symbol"]
|
| 176 |
-
|
|
|
|
|
|
|
| 177 |
continue
|
| 178 |
if not h.get("qty"):
|
| 179 |
continue
|
|
@@ -192,6 +208,8 @@ def harvest_pairs(holdings: list[dict], decisions: dict, candidates: list[dict],
|
|
| 192 |
# never a sector fund — XLY at 0.89 is a different bet, not a placeholder
|
| 193 |
if not (c.get("instrument") and c.get("broad")):
|
| 194 |
continue
|
|
|
|
|
|
|
| 195 |
elif not (c.get("instrument") or c.get("sector") == sec):
|
| 196 |
continue
|
| 197 |
r1 = cand_hist[ct].pct_change().dropna()
|
|
@@ -226,6 +244,7 @@ def tax_plan(holdings: list[dict], decisions: dict, orders: list[dict], book_usd
|
|
| 226 |
def _days(b):
|
| 227 |
y, mo, d = (int(x) for x in str(b)[:10].split("-"))
|
| 228 |
return (date.today() - date(y, mo, d)).days
|
|
|
|
| 229 |
for o in orders:
|
| 230 |
if o.get("side") != "SELL":
|
| 231 |
continue
|
|
@@ -250,8 +269,15 @@ def tax_plan(holdings: list[dict], decisions: dict, orders: list[dict], book_usd
|
|
| 250 |
notes.append(f"the lot bought {str(l['bought'])[:10]} turns long-term on {turn} — sell it after that date")
|
| 251 |
if h.get("qty") and book_usd:
|
| 252 |
gain = (float(h["price"]) - float(h["entry"])) * float(h["qty"]) * sold_frac * float(h.get("fx_usd") or 1.0)
|
| 253 |
-
|
| 254 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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:
|
|
@@ -263,6 +289,38 @@ def tax_plan(holdings: list[dict], decisions: dict, orders: list[dict], book_usd
|
|
| 263 |
return out[:8]
|
| 264 |
|
| 265 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
def wash_sale_notes(holdings: list[dict], pairs: list[dict], wrapper: str | None) -> list[dict]:
|
| 267 |
"""Switch pairs that exit a US loss into a substantially identical instrument would void the loss."""
|
| 268 |
if wrapper in ("isa", "sipp", "pension", "401k", "ira"):
|
|
@@ -290,9 +348,12 @@ def order_plan(holdings: list[dict], target: list[dict]) -> list[dict]:
|
|
| 290 |
band = min(MIN_TRADE_FRAC, max(0.005, 0.5 / max(len(target), 1)))
|
| 291 |
orders = []
|
| 292 |
force = getattr(order_plan, "force", None) or set() # Trim/Sell verdicts are never dropped by the band
|
|
|
|
| 293 |
for r in target:
|
| 294 |
d = r["delta"]
|
| 295 |
-
|
|
|
|
|
|
|
| 296 |
continue
|
| 297 |
o = {"side": "BUY" if d > 0 else "SELL", "ticker": r["ticker"],
|
| 298 |
"delta_pct": round(d, 4), "is_new": r.get("is_new", False),
|
|
@@ -388,15 +449,23 @@ _PLAN_SYSTEM = (
|
|
| 388 |
"they make the payoff concrete (e.g. 'the tax-light route gets most of the benefit for a "
|
| 389 |
"third of the tax'). Plain English a non-finance friend understands; no "
|
| 390 |
"jargon, no scores. You may ONLY reference tickers and numbers present in the plan JSON. "
|
| 391 |
-
"If staged_trims lists tickers, the plan cuts
|
| 392 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 393 |
"A position's share of the book and a sector's share are different numbers — never merge them "
|
| 394 |
"('META is 24% of the book; Communication Services is 38%', never 'META alone is 38% of the sector'). "
|
| 395 |
"Never call a book 'already diversified' when its effective positions are below half its holding count. "
|
| 396 |
"If the plan carries CASH (a fraction of the book left unallocated), present it as deliberate dry "
|
| 397 |
"powder for the WATCHLIST entries, never as indecision; name one watchlist condition. If TAX_PLAN has "
|
| 398 |
"notes, one move may summarise how the sells are executed for tax. "
|
| 399 |
-
"Each order carries its sector: only a BUY marked is_new adds a sector the book lacks — adding "
|
| 400 |
"to an existing holding never 'fills a gap', so do not describe it that way. A holding below its "
|
| 401 |
"entry price is never a 'winner': adds to losing positions are 'averaging down where value backs "
|
| 402 |
"it', never 'adding to winners'. "
|
|
@@ -502,6 +571,7 @@ def build_plan(holdings, decisions, target, candidates, health, total_pl, cards,
|
|
| 502 |
}
|
| 503 |
if construction:
|
| 504 |
order_plan.force = {t for t, d in decisions.items() if d.get("action") in ("Trim", "Sell")} # noqa
|
|
|
|
| 505 |
order_plan.quote_types = construction.get("quote_types") or {} # noqa — module-level hint for duty rules
|
| 506 |
order_plan.sector_of = construction.get("sector_of") or {} # noqa — sectors on orders for the narrator
|
| 507 |
plan["orders"] = order_plan(holdings, target) # rebuild with duty awareness
|
|
@@ -509,9 +579,13 @@ def build_plan(holdings, decisions, target, candidates, health, total_pl, cards,
|
|
| 509 |
plan["staged_trims"] = list(main_sc.get("staged_trims") or [])
|
| 510 |
buys = [o["ticker"] for o in plan["orders"] if o["side"] == "BUY"]
|
| 511 |
sells = [o["ticker"] for o in plan["orders"] if o["side"] == "SELL"]
|
| 512 |
-
|
|
|
|
| 513 |
plan["cash"] = float(main_sc.get("cash") or 0.0)
|
| 514 |
-
|
|
|
|
|
|
|
|
|
|
| 515 |
if construction:
|
| 516 |
plan.update({k: v for k, v in construction.items() if k not in ("quote_types", "sector_of")})
|
| 517 |
pt = (construction.get("post_trade") or {})
|
|
@@ -524,16 +598,24 @@ def build_plan(holdings, decisions, target, candidates, health, total_pl, cards,
|
|
| 524 |
# estimate uses thinner inputs and quoting a different number than the gauge confuses
|
| 525 |
try:
|
| 526 |
plan["outlook"]["current"]["est_health"] = health
|
|
|
|
|
|
|
|
|
|
| 527 |
except Exception:
|
| 528 |
pass
|
|
|
|
| 529 |
wrapper = str((context or {}).get("wrapper") or "").lower() or None
|
| 530 |
plan["switch_pairs"] = wash_sale_notes(holdings, plan["switch_pairs"], wrapper)
|
| 531 |
book_usd_tp = sum(h["market_value"] for h in holdings) if all(h.get("market_value") for h in holdings) else None
|
| 532 |
plan["tax_plan"] = [] if wrapper in ("isa", "sipp", "pension", "401k", "ira") else \
|
| 533 |
tax_plan(holdings, decisions, plan["orders"], book_usd_tp)
|
|
|
|
| 534 |
if construction and wrapper not in ("isa", "sipp", "pension", "401k", "ira"):
|
|
|
|
|
|
|
| 535 |
plan["harvest_pairs"] = harvest_pairs(holdings, decisions, construction.get("harvest_candidates") or candidates,
|
| 536 |
-
construction.get("cand_hist"), construction.get("port_hist")
|
|
|
|
| 537 |
for k in ("cand_hist", "port_hist", "harvest_candidates"):
|
| 538 |
plan.pop(k, None)
|
| 539 |
# Buffett's punch card: when nothing clears the hurdle, "do nothing" is the recommendation
|
|
@@ -541,7 +623,9 @@ def build_plan(holdings, decisions, target, candidates, health, total_pl, cards,
|
|
| 541 |
and all(decisions[h["symbol"]]["action"] == "Keep" for h in holdings))
|
| 542 |
skip = bool((construction or {}).get("skip_narrative"))
|
| 543 |
plan.pop("skip_narrative", None)
|
| 544 |
-
|
|
|
|
|
|
|
| 545 |
plan["pitch"] = (story or {}).get("pitch") or (
|
| 546 |
"This portfolio needs surgery, not encouragement — here is the path back." if mode == "revival"
|
| 547 |
else "This portfolio is working — these moves make it stronger without changing its character.")
|
|
|
|
| 53 |
note = f"{cur}; price {up / (1 + up) * 100:.0f}% below estimated worth" \
|
| 54 |
if isinstance(up, (int, float)) else cur
|
| 55 |
d = {"ticker": t, "disposition": "average down", "note": note}
|
| 56 |
+
# break-even from the ACTUAL planned add (the order's size), not a generic 25% —
|
| 57 |
+
# "adding 25% more" once sat beside an order that quintupled the position
|
| 58 |
+
add_frac = None
|
| 59 |
+
if isinstance(bought, dict) and isinstance(bought.get(t), (int, float)) and h.get("weight"):
|
| 60 |
+
add_frac = float(bought[t]) / float(h["weight"])
|
| 61 |
+
elif bought is None:
|
| 62 |
+
add_frac = 0.25
|
| 63 |
+
if h.get("qty") and add_frac and add_frac > 0:
|
| 64 |
+
add_qty = h["qty"] * add_frac
|
| 65 |
be = (h["qty"] * h["entry"] + add_qty * h["price"]) / (h["qty"] + add_qty)
|
| 66 |
+
d["note"] += (f"; the planned add ({add_frac * 100:.0f}% more shares) lowers break-even from "
|
| 67 |
f"{h['entry']:.2f} to {be:.2f}")
|
| 68 |
out.append(d)
|
| 69 |
elif dec["action"] in ("Sell", "Trim"):
|
|
|
|
| 79 |
"note": f"{cur}; weak backing and a negative expected payoff — the first source "
|
| 80 |
f"of funds when a better idea needs capital"})
|
| 81 |
elif dec["conviction"] >= 55 and isinstance(up, (int, float)) and up >= 0.15:
|
| 82 |
+
# never "top up when fresh cash arrives" beside a plan that is already holding cash
|
| 83 |
+
out.append({"ticker": t, "disposition": "hold — top-up candidate",
|
| 84 |
+
"note": f"{cur}; price {up / (1 + up) * 100:.0f}% below estimated worth, but the committee's "
|
| 85 |
+
f"backing ({dec['conviction']:.0f}/100) is short of a Buy More — first call on the "
|
| 86 |
+
f"plan's dry powder if conviction rises"})
|
| 87 |
+
elif dec["conviction"] < 50 and float(h.get("weight") or 0) >= 0.015:
|
| 88 |
+
out.append({"ticker": t, "disposition": "hold — under review",
|
| 89 |
+
"note": f"{cur}; backing is weak ({dec['conviction']:.0f}/100) but not a sell case — "
|
| 90 |
+
f"no new money, and the first source of funds when a better idea appears"})
|
| 91 |
elif dec["conviction"] < 50:
|
| 92 |
out.append({"ticker": t, "disposition": "hold — too small to matter",
|
| 93 |
"note": f"{cur}; conviction is weak but the position is below the trading band — "
|
|
|
|
| 174 |
# ---------------- US tax: wash-sale awareness + tax-loss harvesting ----------------
|
| 175 |
|
| 176 |
def harvest_pairs(holdings: list[dict], decisions: dict, candidates: list[dict],
|
| 177 |
+
cand_hist=None, port_hist=None, buying: set | None = None,
|
| 178 |
+
allow_funds: bool = True) -> list[dict]:
|
| 179 |
"""US listings held at a loss ≥10% that the committee still likes (Keep/Buy More): sell to
|
| 180 |
book the loss, buy a highly correlated but NOT substantially identical substitute (a
|
| 181 |
same-sector name or sector ETF with ≥0.7 correlation), re-enter after 31 days if wanted.
|
|
|
|
| 187 |
return out
|
| 188 |
for h in holdings:
|
| 189 |
t = h["symbol"]
|
| 190 |
+
# a name the plan is BUYING is never harvested: selling it at a loss within 30 days of the
|
| 191 |
+
# add is a wash sale (TSM was once both "average down" and "sell TSM, buy XLK")
|
| 192 |
+
if "." in t or (h.get("pl_pct") or 0) > -0.10 or decisions[t]["action"] != "Keep" or t in (buying or set()):
|
| 193 |
continue
|
| 194 |
if not h.get("qty"):
|
| 195 |
continue
|
|
|
|
| 208 |
# never a sector fund — XLY at 0.89 is a different bet, not a placeholder
|
| 209 |
if not (c.get("instrument") and c.get("broad")):
|
| 210 |
continue
|
| 211 |
+
elif c.get("instrument") and not allow_funds:
|
| 212 |
+
continue # a stock-picker's book is never parked in an index fund
|
| 213 |
elif not (c.get("instrument") or c.get("sector") == sec):
|
| 214 |
continue
|
| 215 |
r1 = cand_hist[ct].pct_change().dropna()
|
|
|
|
| 244 |
def _days(b):
|
| 245 |
y, mo, d = (int(x) for x in str(b)[:10].split("-"))
|
| 246 |
return (date.today() - date(y, mo, d)).days
|
| 247 |
+
net = realised_pnl(holdings, orders)
|
| 248 |
for o in orders:
|
| 249 |
if o.get("side") != "SELL":
|
| 250 |
continue
|
|
|
|
| 269 |
notes.append(f"the lot bought {str(l['bought'])[:10]} turns long-term on {turn} — sell it after that date")
|
| 270 |
if h.get("qty") and book_usd:
|
| 271 |
gain = (float(h["price"]) - float(h["entry"])) * float(h["qty"]) * sold_frac * float(h.get("fx_usd") or 1.0)
|
| 272 |
+
# the split-year advice only matters when the plan's own losses don't already cover it
|
| 273 |
+
if gain > 0.01 * book_usd and (not h.get("bought") or _days(h["bought"]) >= 365) \
|
| 274 |
+
and net["net"] > 0.02 * book_usd:
|
| 275 |
+
notes.append(f"≈${gain:,.0f} long-term gain — " + (
|
| 276 |
+
f"the plan's losses absorb ≈${net['losses']:,.0f} of gains this year; consider realising the "
|
| 277 |
+
f"rest in January (new tax year)" if net["losses"] else
|
| 278 |
+
"consider splitting the sale across two tax years (December / January)"))
|
| 279 |
+
elif gain > 0.01 * book_usd:
|
| 280 |
+
notes.append(f"≈${gain:,.0f} gain — largely offset by the losses the same plan books this year")
|
| 281 |
if h.get("qty") and float(h["price"]) < float(h["entry"]):
|
| 282 |
loss = (float(h["entry"]) - float(h["price"])) * float(h["qty"]) * sold_frac * float(h.get("fx_usd") or 1.0)
|
| 283 |
if book_usd and loss > 0.005 * book_usd:
|
|
|
|
| 289 |
return out[:8]
|
| 290 |
|
| 291 |
|
| 292 |
+
def realised_pnl(holdings: list[dict], orders: list[dict]) -> dict:
|
| 293 |
+
"""Gains and losses the SELL orders realise (USD), and the net — the number a manager leads with."""
|
| 294 |
+
by = {h["symbol"]: h for h in holdings}
|
| 295 |
+
g = l = 0.0
|
| 296 |
+
for o in orders:
|
| 297 |
+
h = by.get(o.get("ticker"))
|
| 298 |
+
if o.get("side") != "SELL" or not h or not h.get("qty") or "." in h["symbol"]:
|
| 299 |
+
continue
|
| 300 |
+
frac = min(1.0, abs(float(o.get("delta_pct") or 0)) / max(float(h["weight"]), 1e-9))
|
| 301 |
+
x = (float(h["price"]) - float(h["entry"])) * float(h["qty"]) * frac * float(h.get("fx_usd") or 1.0)
|
| 302 |
+
if x >= 0:
|
| 303 |
+
g += x
|
| 304 |
+
else:
|
| 305 |
+
l += -x
|
| 306 |
+
return {"gains": round(g), "losses": round(l), "net": round(g - l)}
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def tax_summary(holdings: list[dict], orders: list[dict], wrapper: str | None) -> str | None:
|
| 310 |
+
if wrapper in ("isa", "sipp", "pension", "401k", "ira"):
|
| 311 |
+
return None
|
| 312 |
+
r = realised_pnl(holdings, orders)
|
| 313 |
+
if not (r["gains"] or r["losses"]):
|
| 314 |
+
return None
|
| 315 |
+
head = (f"the sales realise ≈${r['gains']:,.0f} of gains and ≈${r['losses']:,.0f} of losses — "
|
| 316 |
+
+ (f"a net taxable gain of ≈${r['net']:,.0f}" if r["net"] > 0 else
|
| 317 |
+
f"a net loss of ≈${-r['net']:,.0f} (up to $3,000 a year offsets ordinary income; the rest carries forward)"))
|
| 318 |
+
if r["gains"] and r["net"] < 0.25 * r["gains"]:
|
| 319 |
+
head += "; the losses cover most of the gains, so the plan is close to tax-neutral this year"
|
| 320 |
+
return head + ("" if wrapper else ". Assumes a US taxable account with long-held positions — "
|
| 321 |
+
"in an IRA/401(k) or ISA none of this applies")
|
| 322 |
+
|
| 323 |
+
|
| 324 |
def wash_sale_notes(holdings: list[dict], pairs: list[dict], wrapper: str | None) -> list[dict]:
|
| 325 |
"""Switch pairs that exit a US loss into a substantially identical instrument would void the loss."""
|
| 326 |
if wrapper in ("isa", "sipp", "pension", "401k", "ira"):
|
|
|
|
| 348 |
band = min(MIN_TRADE_FRAC, max(0.005, 0.5 / max(len(target), 1)))
|
| 349 |
orders = []
|
| 350 |
force = getattr(order_plan, "force", None) or set() # Trim/Sell verdicts are never dropped by the band
|
| 351 |
+
force_buy = getattr(order_plan, "force_buy", None) or set()
|
| 352 |
for r in target:
|
| 353 |
d = r["delta"]
|
| 354 |
+
# Trim/Sell verdicts and Buy More adds are never dropped by the band — a staged
|
| 355 |
+
# average-down (NVO 1.1% → 2.2%) is smaller than the band but is the verdict's trade
|
| 356 |
+
if abs(d) < band and not (d < 0 and r["ticker"] in force) and not (d > 0 and r["ticker"] in force_buy):
|
| 357 |
continue
|
| 358 |
o = {"side": "BUY" if d > 0 else "SELL", "ticker": r["ticker"],
|
| 359 |
"delta_pct": round(d, 4), "is_new": r.get("is_new", False),
|
|
|
|
| 449 |
"they make the payoff concrete (e.g. 'the tax-light route gets most of the benefit for a "
|
| 450 |
"third of the tax'). Plain English a non-finance friend understands; no "
|
| 451 |
"jargon, no scores. You may ONLY reference tickers and numbers present in the plan JSON. "
|
| 452 |
+
"If staged_trims lists tickers, the plan cuts only THOSE part-way now (the rest of each cut is a "
|
| 453 |
+
"second stage after the trades settle) — name them exactly; never list a ticker that is not in it. "
|
| 454 |
+
"When a move groups trades under a sector ('trim Communication Services'), include ONLY orders whose "
|
| 455 |
+
"sector field is that sector. If ALERTS is non-empty or HEALTH is below 60, never say the book "
|
| 456 |
+
"'already works' or that 'we are not fixing a problem' — name the problem the plan fixes, while "
|
| 457 |
+
"crediting what is good. If the plan SELLS a holding in a sector and BUYS a new name in the same "
|
| 458 |
+
"sector, call it an upgrade within that sector, never 'finally adding' a sector. If TAX_SUMMARY is "
|
| 459 |
+
"present, the tax move cites its net figure. Every ticker you describe as bought, added or rotated "
|
| 460 |
+
"INTO must be a BUY in orders; WATCHLIST names are only ever 'on the bench'. Never call an add 'the "
|
| 461 |
+
"only' or 'the one' add unless orders hold exactly one BUY. "
|
| 462 |
"A position's share of the book and a sector's share are different numbers — never merge them "
|
| 463 |
"('META is 24% of the book; Communication Services is 38%', never 'META alone is 38% of the sector'). "
|
| 464 |
"Never call a book 'already diversified' when its effective positions are below half its holding count. "
|
| 465 |
"If the plan carries CASH (a fraction of the book left unallocated), present it as deliberate dry "
|
| 466 |
"powder for the WATCHLIST entries, never as indecision; name one watchlist condition. If TAX_PLAN has "
|
| 467 |
"notes, one move may summarise how the sells are executed for tax. "
|
| 468 |
+
"Each order carries its sector: only a BUY marked is_new whose sector no remaining holding shares adds a sector the book lacks — adding "
|
| 469 |
"to an existing holding never 'fills a gap', so do not describe it that way. A holding below its "
|
| 470 |
"entry price is never a 'winner': adds to losing positions are 'averaging down where value backs "
|
| 471 |
"it', never 'adding to winners'. "
|
|
|
|
| 571 |
}
|
| 572 |
if construction:
|
| 573 |
order_plan.force = {t for t, d in decisions.items() if d.get("action") in ("Trim", "Sell")} # noqa
|
| 574 |
+
order_plan.force_buy = {t for t, d in decisions.items() if d.get("action") == "Buy More"} # noqa
|
| 575 |
order_plan.quote_types = construction.get("quote_types") or {} # noqa — module-level hint for duty rules
|
| 576 |
order_plan.sector_of = construction.get("sector_of") or {} # noqa — sectors on orders for the narrator
|
| 577 |
plan["orders"] = order_plan(holdings, target) # rebuild with duty awareness
|
|
|
|
| 579 |
plan["staged_trims"] = list(main_sc.get("staged_trims") or [])
|
| 580 |
buys = [o["ticker"] for o in plan["orders"] if o["side"] == "BUY"]
|
| 581 |
sells = [o["ticker"] for o in plan["orders"] if o["side"] == "SELL"]
|
| 582 |
+
buy_delta = {o["ticker"]: float(o.get("delta_pct") or 0) for o in plan["orders"] if o["side"] == "BUY"}
|
| 583 |
+
plan["triage"] = triage(holdings, decisions, buy_delta, set(sells)) # dispositions agree with the trade list
|
| 584 |
plan["cash"] = float(main_sc.get("cash") or 0.0)
|
| 585 |
+
# a switch only names a replacement the order list actually buys — "rotate BNTX into MO"
|
| 586 |
+
# once ran beside a trade list that left MO on the watchlist, unfunded
|
| 587 |
+
plan["switch_pairs"] = [sp for sp in switch_pairs(holdings, decisions, candidates, needs, prefer=buys)
|
| 588 |
+
if sp.get("in") in set(buys)]
|
| 589 |
if construction:
|
| 590 |
plan.update({k: v for k, v in construction.items() if k not in ("quote_types", "sector_of")})
|
| 591 |
pt = (construction.get("post_trade") or {})
|
|
|
|
| 598 |
# estimate uses thinner inputs and quoting a different number than the gauge confuses
|
| 599 |
try:
|
| 600 |
plan["outlook"]["current"]["est_health"] = health
|
| 601 |
+
cb = (construction or {}).get("current_beta")
|
| 602 |
+
if isinstance(cb, (int, float)): # the same realised beta the scorecard and findings quote (1.14, not 1.16)
|
| 603 |
+
plan["outlook"]["current"]["beta"] = cb
|
| 604 |
except Exception:
|
| 605 |
pass
|
| 606 |
+
plan.pop("current_beta", None)
|
| 607 |
wrapper = str((context or {}).get("wrapper") or "").lower() or None
|
| 608 |
plan["switch_pairs"] = wash_sale_notes(holdings, plan["switch_pairs"], wrapper)
|
| 609 |
book_usd_tp = sum(h["market_value"] for h in holdings) if all(h.get("market_value") for h in holdings) else None
|
| 610 |
plan["tax_plan"] = [] if wrapper in ("isa", "sipp", "pension", "401k", "ira") else \
|
| 611 |
tax_plan(holdings, decisions, plan["orders"], book_usd_tp)
|
| 612 |
+
plan["tax_summary"] = tax_summary(holdings, plan["orders"], wrapper)
|
| 613 |
if construction and wrapper not in ("isa", "sipp", "pension", "401k", "ira"):
|
| 614 |
+
has_funds = any(str((h.get("data") or {}).get("quote_type") or "").upper() in ("ETF", "MUTUALFUND", "FUND")
|
| 615 |
+
for h in holdings)
|
| 616 |
plan["harvest_pairs"] = harvest_pairs(holdings, decisions, construction.get("harvest_candidates") or candidates,
|
| 617 |
+
construction.get("cand_hist"), construction.get("port_hist"),
|
| 618 |
+
buying=set(buys), allow_funds=has_funds)
|
| 619 |
for k in ("cand_hist", "port_hist", "harvest_candidates"):
|
| 620 |
plan.pop(k, None)
|
| 621 |
# Buffett's punch card: when nothing clears the hurdle, "do nothing" is the recommendation
|
|
|
|
| 623 |
and all(decisions[h["symbol"]]["action"] == "Keep" for h in holdings))
|
| 624 |
skip = bool((construction or {}).get("skip_narrative"))
|
| 625 |
plan.pop("skip_narrative", None)
|
| 626 |
+
alerts = [c["check"] for c in (cards or []) if c.get("status") == "ALERT"]
|
| 627 |
+
story = None if skip else narrative(_for_narrative(plan) | {"n_holdings": len(holdings), "ALERTS": alerts,
|
| 628 |
+
"HEALTH": health, "TAX_SUMMARY": plan.get("tax_summary")})
|
| 629 |
plan["pitch"] = (story or {}).get("pitch") or (
|
| 630 |
"This portfolio needs surgery, not encouragement — here is the path back." if mode == "revival"
|
| 631 |
else "This portfolio is working — these moves make it stronger without changing its character.")
|
static/app.js
CHANGED
|
@@ -483,9 +483,9 @@ function renderResults(R) {
|
|
| 483 |
if (alts.length && needLabels.length)
|
| 484 |
av.appendChild(el("div", "needs-line", `<b>What this portfolio needs:</b> ${esc(needLabels.join(" · "))}`));
|
| 485 |
for (const g of ((R.plan || {}).gap_search || [])) {
|
| 486 |
-
av.appendChild(el("div", "needs-line dim", `<b>${esc(g.sector)}:</b> ${g.screened}
|
| 487 |
(g.buyable && g.buyable.length ? `buyable today: ${esc(g.buyable.join(", "))}` : "none buyable today") +
|
| 488 |
-
(g.why_not ? `
|
| 489 |
}
|
| 490 |
for (const a of alts) {
|
| 491 |
const tags = (a.signals || []).filter(s => s.includes("smart") || s.includes("quant") || s.includes("local") || s.includes("US-listed")).map(s =>
|
|
@@ -779,6 +779,7 @@ function renderConstruction(plan) {
|
|
| 779 |
(p12.base !== undefined && p12.base !== null ? `<tr><td><b>After the plan</b></td><td>${pct(p12.bear)}</td><td>${pct(p12.base)}</td><td>${pct(p12.bull)}</td><td>${pct(p12.coverage, false)}</td></tr>` : "") +
|
| 780 |
`</tbody></table>`;
|
| 781 |
}
|
|
|
|
| 782 |
if ((plan.tax_plan || []).length) {
|
| 783 |
html += `<h4>Tax plan — how the sells are executed</h4><ul class="plain">` +
|
| 784 |
plan.tax_plan.map(x => `<li><b>${esc(x.ticker)}</b> ${esc(x.note)}</li>`).join("") + `</ul>`;
|
|
@@ -837,7 +838,7 @@ function renderRisk(R) {
|
|
| 837 |
if (ft.tilts) chips.push(`<b>Style tilts</b> (${pct(ft.coverage, false)} of book): ` +
|
| 838 |
Object.entries(ft.tilts).map(([k, v]) => `${esc(k)} <span class="${v >= 0 ? "up" : "dn"}">${v >= 0 ? "+" : ""}${Number(v).toFixed(2)}</span>`).join(" · "));
|
| 839 |
const fb = rk.factor_betas || {};
|
| 840 |
-
if (fb.betas) chips.push(`<b>Measured factor betas</b> (vs ${esc(bn)}, ${fb.n_days} days; market beta ${fb.market_beta}): ` +
|
| 841 |
Object.entries(fb.betas).map(([k, v]) => `${esc(k.replace("_", " "))} <span class="${v >= 0 ? "up" : "dn"}">${v >= 0 ? "+" : ""}${Number(v).toFixed(2)}</span>`).join(" · "));
|
| 842 |
const br = rk.benchmark_relative || {};
|
| 843 |
if (br.upside_capture !== undefined || br.sortino !== undefined) {
|
|
|
|
| 483 |
if (alts.length && needLabels.length)
|
| 484 |
av.appendChild(el("div", "needs-line", `<b>What this portfolio needs:</b> ${esc(needLabels.join(" · "))}`));
|
| 485 |
for (const g of ((R.plan || {}).gap_search || [])) {
|
| 486 |
+
av.appendChild(el("div", "needs-line dim", `<b>${esc(g.sector)}:</b> ${g.screened} name${g.screened === 1 ? "" : "s"} screened — ` +
|
| 487 |
(g.buyable && g.buyable.length ? `buyable today: ${esc(g.buyable.join(", "))}` : "none buyable today") +
|
| 488 |
+
(g.why_not ? `; ${g.buyable && g.buyable.length ? "the rest" : "all"} passed over — ${esc(g.why_not)}` : "") + (g.bench && g.bench.length ? `; on the bench with entry conditions: ${esc(g.bench.join(", "))}` : "")));
|
| 489 |
}
|
| 490 |
for (const a of alts) {
|
| 491 |
const tags = (a.signals || []).filter(s => s.includes("smart") || s.includes("quant") || s.includes("local") || s.includes("US-listed")).map(s =>
|
|
|
|
| 779 |
(p12.base !== undefined && p12.base !== null ? `<tr><td><b>After the plan</b></td><td>${pct(p12.bear)}</td><td>${pct(p12.base)}</td><td>${pct(p12.bull)}</td><td>${pct(p12.coverage, false)}</td></tr>` : "") +
|
| 780 |
`</tbody></table>`;
|
| 781 |
}
|
| 782 |
+
if (plan.tax_summary) html += `<h4>Tax, net</h4><p>${esc(plan.tax_summary)}</p>`;
|
| 783 |
if ((plan.tax_plan || []).length) {
|
| 784 |
html += `<h4>Tax plan — how the sells are executed</h4><ul class="plain">` +
|
| 785 |
plan.tax_plan.map(x => `<li><b>${esc(x.ticker)}</b> ${esc(x.note)}</li>`).join("") + `</ul>`;
|
|
|
|
| 838 |
if (ft.tilts) chips.push(`<b>Style tilts</b> (${pct(ft.coverage, false)} of book): ` +
|
| 839 |
Object.entries(ft.tilts).map(([k, v]) => `${esc(k)} <span class="${v >= 0 ? "up" : "dn"}">${v >= 0 ? "+" : ""}${Number(v).toFixed(2)}</span>`).join(" · "));
|
| 840 |
const fb = rk.factor_betas || {};
|
| 841 |
+
if (fb.betas) chips.push(`<b>Measured factor betas</b> (vs ${esc(bn)}, ${fb.n_days} days; factor-model market beta ${fb.market_beta}): ` +
|
| 842 |
Object.entries(fb.betas).map(([k, v]) => `${esc(k.replace("_", " "))} <span class="${v >= 0 ? "up" : "dn"}">${v >= 0 ? "+" : ""}${Number(v).toFixed(2)}</span>`).join(" · "));
|
| 843 |
const br = rk.benchmark_relative || {};
|
| 844 |
if (br.upside_capture !== undefined || br.sortino !== undefined) {
|
tests/test_construct.py
CHANGED
|
@@ -158,8 +158,22 @@ def test_shortfall_slows_the_trim_instead_of_inflating_starters():
|
|
| 158 |
w = CX.optimize_target(cur, mu, cov, U, bounds, sec, 0.9, 0.9, {}, tax_weight=0.0)
|
| 159 |
assert w["N1"] <= 0.10 + 1e-6 and w["N2"] <= 0.10 + 1e-6 # starters capped
|
| 160 |
assert w["K1"] <= 0.30 + 1e-6 and w["K2"] <= 0.30 + 1e-6 # frozen Keeps not lifted
|
| 161 |
-
|
| 162 |
-
assert "BIG"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
bounds_s = dict(bounds, BIG=(0.0, 0.0)) # a SELL is never un-sold by feasibility
|
| 164 |
ws = CX.optimize_target(cur, mu, cov, U, bounds_s, sec, 0.9, 0.9, {}, tax_weight=0.0)
|
| 165 |
assert ws["BIG"] < 1e-6
|
|
@@ -183,9 +197,9 @@ def test_staged_trim_state_never_leaks_into_the_next_book():
|
|
| 183 |
from the previous run were 'trimmed in stages'."""
|
| 184 |
U = ["BIG", "K1", "K2", "N1", "N2"]
|
| 185 |
cov = np.eye(5) * 0.04
|
| 186 |
-
cur = {"BIG": 0.
|
| 187 |
mu = {t: 0.05 for t in U}
|
| 188 |
-
bounds = {"BIG": (0.0, 0.15), "K1": (0.
|
| 189 |
sec = {t: t for t in U}
|
| 190 |
CX.optimize_target(cur, mu, cov, U, bounds, sec, 0.9, 0.9, {}, tax_weight=0.0)
|
| 191 |
assert "BIG" in CX.optimize_target.relaxed
|
|
@@ -244,3 +258,12 @@ def test_feasibility_ladder_never_lifts_a_hard_profile_cap():
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
w = CX.optimize_target(cur, mu, cov, U, bounds, sec, 0.9, 0.9, {}, tax_weight=0.0)
|
| 159 |
assert w["N1"] <= 0.10 + 1e-6 and w["N2"] <= 0.10 + 1e-6 # starters capped
|
| 160 |
assert w["K1"] <= 0.30 + 1e-6 and w["K2"] <= 0.30 + 1e-6 # frozen Keeps not lifted
|
| 161 |
+
# a 5% shortfall is held as dry powder: the Trim is COMPLETED, not halved
|
| 162 |
+
assert abs(w["BIG"] - 0.15) < 1e-4 and 0.0 < CX.optimize_target.cash <= CX.CASH_SOFT
|
| 163 |
+
assert "BIG" not in CX.optimize_target.relaxed
|
| 164 |
+
# a shortfall far past the cash comfort level stages the valuation trim (keeping ≥ half its cut)
|
| 165 |
+
cur2 = {"BIG": 0.60, "K1": 0.20, "K2": 0.20, "N1": 0.0, "N2": 0.0}
|
| 166 |
+
b2 = {"BIG": (0.0, 0.15), "K1": (0.16, 0.20), "K2": (0.16, 0.20), "N1": (0.0, 0.07), "N2": (0.0, 0.07)}
|
| 167 |
+
w2 = CX.optimize_target(cur2, mu, cov, U, b2, sec, 0.9, 0.9, {}, tax_weight=0.0)
|
| 168 |
+
assert "BIG" in CX.optimize_target.relaxed and 0.15 < w2["BIG"] <= 0.375 + 1e-6
|
| 169 |
+
assert CX.optimize_target.cash <= CX.CASH_SOFT + 1e-6
|
| 170 |
+
# …but a SIZE trim (above the name cap) is completed while cash stays under 25%
|
| 171 |
+
CX.optimize_target.size_trims = {"BIG"}
|
| 172 |
+
try:
|
| 173 |
+
w3 = CX.optimize_target(cur2, mu, cov, U, b2, sec, 0.9, 0.9, {}, tax_weight=0.0)
|
| 174 |
+
finally:
|
| 175 |
+
CX.optimize_target.size_trims = set()
|
| 176 |
+
assert abs(w3["BIG"] - 0.15) < 1e-4 and CX.optimize_target.cash > CX.CASH_SOFT
|
| 177 |
bounds_s = dict(bounds, BIG=(0.0, 0.0)) # a SELL is never un-sold by feasibility
|
| 178 |
ws = CX.optimize_target(cur, mu, cov, U, bounds_s, sec, 0.9, 0.9, {}, tax_weight=0.0)
|
| 179 |
assert ws["BIG"] < 1e-6
|
|
|
|
| 197 |
from the previous run were 'trimmed in stages'."""
|
| 198 |
U = ["BIG", "K1", "K2", "N1", "N2"]
|
| 199 |
cov = np.eye(5) * 0.04
|
| 200 |
+
cur = {"BIG": 0.60, "K1": 0.20, "K2": 0.20, "N1": 0.0, "N2": 0.0}
|
| 201 |
mu = {t: 0.05 for t in U}
|
| 202 |
+
bounds = {"BIG": (0.0, 0.15), "K1": (0.16, 0.20), "K2": (0.16, 0.20), "N1": (0.0, 0.07), "N2": (0.0, 0.07)}
|
| 203 |
sec = {t: t for t in U}
|
| 204 |
CX.optimize_target(cur, mu, cov, U, bounds, sec, 0.9, 0.9, {}, tax_weight=0.0)
|
| 205 |
assert "BIG" in CX.optimize_target.relaxed
|
|
|
|
| 258 |
finally:
|
| 259 |
CX.optimize_target.hard = set()
|
| 260 |
assert w["SHY"] <= 0.08 + 1e-6 and w["N"] > 0.07 # the starter is lifted, the ballast cap is not
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def test_average_down_is_staged_and_not_lifted():
|
| 264 |
+
from src import construct as CX
|
| 265 |
+
hs = [{"symbol": "NVO", "weight": 0.011, "pl_pct": -0.47}, {"symbol": "CRM", "weight": 0.025, "pl_pct": 0.05}]
|
| 266 |
+
dec = {"NVO": {"action": "Buy More"}, "CRM": {"action": "Buy More"}}
|
| 267 |
+
b = CX.build_bounds(hs, dec, [], {"NVO": 0.15, "CRM": 0.15})
|
| 268 |
+
assert b["NVO"][1] <= 0.022 + 1e-9 # a loser at most doubles in one step
|
| 269 |
+
assert b["CRM"][1] >= 0.05 - 1e-9 # a winner may still grow by the usual rule
|
tests/test_recommend.py
CHANGED
|
@@ -389,3 +389,48 @@ def test_drift_band_holds_a_backed_winner_and_bounds_freeze_it():
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def test_foreign_filer_altman_uses_one_currency():
|
| 395 |
+
from src import fundamentals as F
|
| 396 |
+
# Alibaba-shaped row: CNY statements, USD market cap; P/S ties the two (fx ≈ 6.8)
|
| 397 |
+
c = {"assets": 1.91e12, "liabilities": 7.83e11, "workingcapital": 1.34e11, "retearn": 7.08e11,
|
| 398 |
+
"ebit": 1.43e11, "revenue": 1.02e12, "marketcap": 3.12e11, "ps": 2.08}
|
| 399 |
+
assert 6.5 < F.fx_local(c) < 7.0
|
| 400 |
+
assert F.altman_z(c, None) > 2.99 # safe, not "distress" (1.6 when the currencies mixed)
|
| 401 |
+
assert F.fx_local({"revenue": 1e9, "ps": 3.0, "marketcap": 3e9}) == 1.0
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def test_tripwires_are_never_already_tripped():
|
| 405 |
+
from src import fundamentals as F
|
| 406 |
+
us = {"econ": {"lynch_category": "fast grower", "roic": 0.06}}
|
| 407 |
+
tr = F.sell_triggers({"rev_growth": 0.11}, us)
|
| 408 |
+
assert "below 5%" in tr[0] and "15%" not in tr[0]
|
| 409 |
+
assert "climb back above 10%" in " ".join(tr)
|
| 410 |
+
us2 = {"econ": {"lynch_category": "stalwart"}}
|
| 411 |
+
assert "PEG above 2.5" not in F.sell_triggers({"peg": 5.2}, us2)[0]
|
| 412 |
+
assert F._rev_words(-161.4) == "EPS estimates swung from a profit to a loss in 90 days"
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def test_tax_summary_nets_gains_and_losses():
|
| 416 |
+
from src import revival as REV
|
| 417 |
+
hs = [{"symbol": "W", "weight": 0.5, "price": 200.0, "entry": 100.0, "qty": 100},
|
| 418 |
+
{"symbol": "L", "weight": 0.5, "price": 50.0, "entry": 140.0, "qty": 100}]
|
| 419 |
+
orders = [{"side": "SELL", "ticker": "W", "delta_pct": -0.25}, {"side": "SELL", "ticker": "L", "delta_pct": -0.5}]
|
| 420 |
+
r = REV.realised_pnl(hs, orders)
|
| 421 |
+
assert r == {"gains": 5000, "losses": 9000, "net": -4000}
|
| 422 |
+
txt = REV.tax_summary(hs, orders, None)
|
| 423 |
+
assert "net loss" in txt and "Assumes a US taxable account" in txt
|
| 424 |
+
assert REV.tax_summary(hs, orders, "ira") is None
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def test_a_buy_more_add_is_never_dropped_by_the_band():
|
| 428 |
+
from src import revival as REV
|
| 429 |
+
hs = [{"symbol": f"H{i}", "weight": 1 / 40, "market_value": 1000.0, "price": 10.0, "qty": 100} for i in range(40)]
|
| 430 |
+
target = [{"ticker": "H0", "delta": 0.011, "target_w": 0.036}, {"ticker": "H1", "delta": 0.011, "target_w": 0.036}]
|
| 431 |
+
REV.order_plan.force, REV.order_plan.force_buy = set(), {"H0"}
|
| 432 |
+
try:
|
| 433 |
+
got = {o["ticker"] for o in REV.order_plan(hs, target)}
|
| 434 |
+
finally:
|
| 435 |
+
REV.order_plan.force_buy = set()
|
| 436 |
+
assert got == {"H0"} # the Buy More add survives; a stray 1.1% delta on another name does not
|