Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
-
# app.py
|
| 2 |
-
import os, io, math, time, warnings
|
| 3 |
warnings.filterwarnings("ignore")
|
| 4 |
|
| 5 |
from typing import List, Tuple, Dict, Optional
|
|
@@ -20,15 +20,14 @@ MAX_TICKERS = 30
|
|
| 20 |
DEFAULT_LOOKBACK_YEARS = 10
|
| 21 |
MARKET_TICKER = "VOO"
|
| 22 |
|
| 23 |
-
SYNTH_ROWS = 1000
|
| 24 |
EMBED_MODEL_NAME = "FinLang/finance-embeddings-investopedia"
|
| 25 |
-
EMBED_ALPHA = 0.6
|
| 26 |
-
MMR_LAMBDA = 0.7
|
| 27 |
|
| 28 |
-
# Globals updated by horizon control
|
| 29 |
HORIZON_YEARS = 10
|
| 30 |
RF_CODE = "DGS10"
|
| 31 |
-
RF_ANN = 0.0375
|
| 32 |
|
| 33 |
# ---------------- helpers ----------------
|
| 34 |
def fred_series_for_horizon(years: float) -> str:
|
|
@@ -44,8 +43,7 @@ def fred_series_for_horizon(years: float) -> str:
|
|
| 44 |
def fetch_fred_yield_annual(code: str) -> float:
|
| 45 |
url = f"https://fred.stlouisfed.org/graph/fredgraph.csv?id={code}"
|
| 46 |
try:
|
| 47 |
-
r = requests.get(url, timeout=10)
|
| 48 |
-
r.raise_for_status()
|
| 49 |
df = pd.read_csv(io.StringIO(r.text))
|
| 50 |
s = pd.to_numeric(df.iloc[:, 1], errors="coerce").dropna()
|
| 51 |
return float(s.iloc[-1] / 100.0) if len(s) else 0.03
|
|
@@ -56,57 +54,35 @@ def fetch_prices_monthly(tickers: List[str], years: int) -> pd.DataFrame:
|
|
| 56 |
tickers = list(dict.fromkeys([t.upper().strip() for t in tickers if t]))
|
| 57 |
start = (pd.Timestamp.today(tz="UTC") - pd.DateOffset(years=int(years), days=7)).date()
|
| 58 |
end = pd.Timestamp.today(tz="UTC").date()
|
| 59 |
-
|
| 60 |
df = yf.download(
|
| 61 |
-
tickers,
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
interval="1mo",
|
| 65 |
-
auto_adjust=True,
|
| 66 |
-
actions=False,
|
| 67 |
-
progress=False,
|
| 68 |
-
group_by="column",
|
| 69 |
-
threads=False,
|
| 70 |
)
|
| 71 |
-
|
| 72 |
-
# Normalize to wide (Close) frame
|
| 73 |
-
if isinstance(df, pd.Series):
|
| 74 |
-
df = df.to_frame()
|
| 75 |
if isinstance(df.columns, pd.MultiIndex):
|
| 76 |
lvl0 = [str(x) for x in df.columns.get_level_values(0).unique()]
|
| 77 |
-
if "Close" in lvl0:
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
df = df["Adj Close"]
|
| 81 |
-
else:
|
| 82 |
-
df = df.xs(df.columns.levels[0][-1], axis=1, level=0, drop_level=True)
|
| 83 |
-
|
| 84 |
cols = [c for c in tickers if c in df.columns]
|
| 85 |
-
|
| 86 |
-
return out
|
| 87 |
|
| 88 |
def monthly_returns(prices: pd.DataFrame) -> pd.DataFrame:
|
| 89 |
return prices.pct_change().dropna()
|
| 90 |
|
| 91 |
def yahoo_search(query: str):
|
| 92 |
-
if not query or not str(query).strip():
|
| 93 |
-
return []
|
| 94 |
url = "https://query1.finance.yahoo.com/v1/finance/search"
|
| 95 |
params = {"q": query.strip(), "quotesCount": 10, "newsCount": 0}
|
| 96 |
headers = {"User-Agent": "Mozilla/5.0"}
|
| 97 |
try:
|
| 98 |
-
r = requests.get(url, params=params, headers=headers, timeout=10)
|
| 99 |
-
r.
|
| 100 |
-
data = r.json()
|
| 101 |
-
out = []
|
| 102 |
for q in data.get("quotes", []):
|
| 103 |
-
sym = q.get("symbol")
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
if sym and sym.isascii():
|
| 107 |
-
out.append(f"{sym} | {name} | {exch}")
|
| 108 |
-
if not out:
|
| 109 |
-
out = [f"{query.strip().upper()} | typed symbol | n/a"]
|
| 110 |
return out[:10]
|
| 111 |
except Exception:
|
| 112 |
return [f"{query.strip().upper()} | typed symbol | n/a"]
|
|
@@ -115,17 +91,16 @@ def validate_tickers(symbols: List[str], years: int) -> List[str]:
|
|
| 115 |
base = [s for s in dict.fromkeys([t.upper().strip() for t in symbols]) if s]
|
| 116 |
px = fetch_prices_monthly(base + [MARKET_TICKER], years)
|
| 117 |
ok = [s for s in base if s in px.columns]
|
| 118 |
-
if MARKET_TICKER not in px.columns:
|
| 119 |
-
return [] # we need a market proxy to align CAPM
|
| 120 |
return ok
|
| 121 |
|
| 122 |
-
# ----------
|
| 123 |
def get_aligned_monthly_returns(symbols: List[str], years: int) -> pd.DataFrame:
|
| 124 |
-
uniq = [c for c in dict.fromkeys(symbols)
|
| 125 |
-
|
| 126 |
-
px = fetch_prices_monthly(
|
| 127 |
rets = monthly_returns(px)
|
| 128 |
-
cols = [c for c in uniq if c in rets.columns]
|
| 129 |
R = rets[cols].dropna(how="any")
|
| 130 |
return R.loc[:, ~R.columns.duplicated()]
|
| 131 |
|
|
@@ -136,16 +111,13 @@ def estimate_all_moments_aligned(symbols: List[str], years: int, rf_ann: float):
|
|
| 136 |
rf_m = rf_ann / 12.0
|
| 137 |
|
| 138 |
m = R[MARKET_TICKER]
|
| 139 |
-
if isinstance(m, pd.DataFrame):
|
| 140 |
-
m = m.iloc[:, 0].squeeze()
|
| 141 |
-
|
| 142 |
mu_m_ann = float(m.mean() * 12.0)
|
| 143 |
sigma_m_ann = float(m.std(ddof=1) * math.sqrt(12.0))
|
| 144 |
erp_ann = float(mu_m_ann - rf_ann)
|
| 145 |
|
| 146 |
ex_m = m - rf_m
|
| 147 |
-
var_m = float(np.var(ex_m.values, ddof=1))
|
| 148 |
-
var_m = max(var_m, 1e-9)
|
| 149 |
|
| 150 |
betas: Dict[str, float] = {}
|
| 151 |
for s in [c for c in R.columns if c != MARKET_TICKER]:
|
|
@@ -154,140 +126,84 @@ def estimate_all_moments_aligned(symbols: List[str], years: int, rf_ann: float):
|
|
| 154 |
betas[s] = cov_sm / var_m
|
| 155 |
betas[MARKET_TICKER] = 1.0
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
|
| 161 |
-
return {"betas": betas, "
|
| 162 |
|
| 163 |
def capm_er(beta: float, rf_ann: float, erp_ann: float) -> float:
|
| 164 |
return float(rf_ann + beta * erp_ann)
|
| 165 |
|
| 166 |
def portfolio_stats(weights: Dict[str, float],
|
| 167 |
-
|
| 168 |
betas: Dict[str, float],
|
| 169 |
rf_ann: float,
|
| 170 |
erp_ann: float) -> Tuple[float, float, float]:
|
| 171 |
tickers = list(weights.keys())
|
| 172 |
w = np.array([weights[t] for t in tickers], dtype=float)
|
| 173 |
gross = float(np.sum(np.abs(w)))
|
| 174 |
-
if gross <= 1e-12:
|
| 175 |
-
return 0.0, rf_ann, 0.0
|
| 176 |
w_expo = w / gross
|
| 177 |
beta_p = float(np.dot([betas.get(t, 0.0) for t in tickers], w_expo))
|
| 178 |
mu_capm = capm_er(beta_p, rf_ann, erp_ann)
|
| 179 |
-
cov =
|
| 180 |
-
|
| 181 |
-
# treat market ticker (if any) as index asset with β=1; variance from cov_ann is on asset-only block
|
| 182 |
-
# when MARKET_TICKER is in weights, its variance contribution is ignored in cov (ok; σ_hist is approximate)
|
| 183 |
-
sigma_hist = 0.0
|
| 184 |
-
if cov.size and all(t != MARKET_TICKER for t in tickers):
|
| 185 |
-
sigma_hist = float(max(w_expo.T @ cov @ w_expo, 0.0)) ** 0.5
|
| 186 |
-
else:
|
| 187 |
-
# fallback: use weighted average variance/cov if market present; approximate via available submatrix
|
| 188 |
-
sub_t = [t for t in tickers if t != MARKET_TICKER]
|
| 189 |
-
if sub_t:
|
| 190 |
-
sub_w = np.array([weights[t] for t in sub_t], dtype=float)
|
| 191 |
-
sub_w = sub_w / max(np.sum(np.abs(sub_w)), 1e-12)
|
| 192 |
-
sub_cov = cov_ann.reindex(index=sub_t, columns=sub_t).fillna(0.0).to_numpy()
|
| 193 |
-
sigma_hist = float(max(sub_w.T @ sub_cov @ sub_w, 0.0)) ** 0.5
|
| 194 |
-
else:
|
| 195 |
-
sigma_hist = 0.0
|
| 196 |
return beta_p, mu_capm, sigma_hist
|
| 197 |
|
| 198 |
def efficient_same_sigma(sigma_target: float, rf_ann: float, erp_ann: float, sigma_mkt: float):
|
| 199 |
-
if sigma_mkt <= 1e-12:
|
| 200 |
-
return 0.0, 1.0, rf_ann
|
| 201 |
a = sigma_target / sigma_mkt
|
| 202 |
-
return a, 1.0 - a, rf_ann + a * erp_ann
|
| 203 |
|
| 204 |
def efficient_same_return(mu_target: float, rf_ann: float, erp_ann: float, sigma_mkt: float):
|
| 205 |
-
if abs(erp_ann) <= 1e-12:
|
| 206 |
-
return 0.0, 1.0, rf_ann
|
| 207 |
a = (mu_target - rf_ann) / erp_ann
|
| 208 |
-
return a, 1.0 - a, abs(a) * sigma_mkt
|
| 209 |
|
| 210 |
# -------------- plotting --------------
|
| 211 |
-
def _pct(x):
|
| 212 |
-
return np.asarray(x, dtype=float) * 100.0
|
| 213 |
-
|
| 214 |
-
def plot_cml_hybrid(
|
| 215 |
-
rf_ann, erp_ann, sigma_mkt,
|
| 216 |
-
sigma_hist_port, mu_capm_port,
|
| 217 |
-
mu_eff_same_sigma, sigma_eff_same_return,
|
| 218 |
-
sugg_mu=None, sugg_sigma_hist=None
|
| 219 |
-
) -> Image.Image:
|
| 220 |
-
fig = plt.figure(figsize=(6.5, 4.2), dpi=120)
|
| 221 |
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
|
|
|
|
|
|
| 227 |
xs = np.linspace(0.0, xmax, 240)
|
| 228 |
cml = rf_ann + (erp_ann / max(sigma_mkt, 1e-9)) * xs if sigma_mkt > 1e-12 else np.full_like(xs, rf_ann)
|
| 229 |
-
|
| 230 |
-
# CML and fixtures
|
| 231 |
plt.plot(_pct(xs), _pct(cml), label="CML (Market/Bills)", linewidth=1.8)
|
| 232 |
plt.scatter([_pct(0)], [_pct(rf_ann)], label="Risk-free", zorder=3)
|
| 233 |
plt.scatter([_pct(sigma_mkt)], [_pct(rf_ann + erp_ann)], label="Market", zorder=3)
|
| 234 |
-
|
| 235 |
-
# Your CAPM point (x = historical σ, y = CAPM E[r])
|
| 236 |
plt.scatter([_pct(sigma_hist_port)], [_pct(mu_capm_port)], label="Your CAPM point", marker="o", zorder=4)
|
| 237 |
-
|
| 238 |
-
# Efficient points
|
| 239 |
plt.scatter([_pct(sigma_hist_port)], [_pct(mu_eff_same_sigma)], label="Efficient (same σ)", marker="^", zorder=4)
|
| 240 |
plt.scatter([_pct(sigma_eff_same_return)], [_pct(mu_capm_port)], label="Efficient (same E[r])", marker="s", zorder=4)
|
| 241 |
-
|
| 242 |
-
# Selected suggestion
|
| 243 |
if (sugg_mu is not None) and (sugg_sigma_hist is not None):
|
| 244 |
plt.scatter([_pct(sugg_sigma_hist)], [_pct(sugg_mu)], label="Selected Suggestion", marker="X", s=70, zorder=5)
|
| 245 |
-
|
| 246 |
-
plt.
|
| 247 |
-
|
| 248 |
-
plt.legend(loc="best", fontsize=8)
|
| 249 |
-
plt.tight_layout()
|
| 250 |
-
|
| 251 |
-
buf = io.BytesIO()
|
| 252 |
-
plt.savefig(buf, format="png")
|
| 253 |
-
plt.close(fig)
|
| 254 |
-
buf.seek(0)
|
| 255 |
return Image.open(buf)
|
| 256 |
|
| 257 |
-
# -------------- synthetic dataset --------------
|
| 258 |
def build_synthetic_dataset(universe: List[str],
|
| 259 |
-
|
| 260 |
betas: Dict[str, float],
|
| 261 |
rf_ann: float,
|
| 262 |
erp_ann: float,
|
| 263 |
-
sigma_mkt: float,
|
| 264 |
n_rows: int = SYNTH_ROWS) -> pd.DataFrame:
|
| 265 |
rng = np.random.default_rng(12345)
|
| 266 |
-
|
| 267 |
-
if not assets:
|
| 268 |
-
assets = [MARKET_TICKER]
|
| 269 |
-
|
| 270 |
rows = []
|
| 271 |
for _ in range(n_rows):
|
| 272 |
k = int(rng.integers(low=2, high=min(8, len(universe)) + 1))
|
| 273 |
picks = list(rng.choice(universe, size=k, replace=False))
|
| 274 |
-
|
| 275 |
-
# long-only for clarity in suggestions
|
| 276 |
w = rng.dirichlet(np.ones(k))
|
| 277 |
-
|
| 278 |
-
# beta and CAPM E[r]
|
| 279 |
beta_p = float(np.dot([betas.get(t, 0.0) for t in picks], w))
|
| 280 |
mu_capm = capm_er(beta_p, rf_ann, erp_ann)
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
sub = [t for t in picks if t != MARKET_TICKER]
|
| 284 |
-
if sub:
|
| 285 |
-
sub_w = np.array([w[i] for i, t in enumerate(picks) if t != MARKET_TICKER], dtype=float)
|
| 286 |
-
sub_cov = covA.reindex(index=sub, columns=sub).fillna(0.0).to_numpy()
|
| 287 |
-
sigma_hist = float(max(sub_w.T @ sub_cov @ sub_w, 0.0)) ** 0.5
|
| 288 |
-
else:
|
| 289 |
-
sigma_hist = 0.0
|
| 290 |
-
|
| 291 |
rows.append({
|
| 292 |
"tickers": ",".join(picks),
|
| 293 |
"weights": ",".join(f"{x:.6f}" for x in w),
|
|
@@ -299,22 +215,17 @@ def build_synthetic_dataset(universe: List[str],
|
|
| 299 |
|
| 300 |
def _band_bounds_sigma_hist(sigma_mkt: float, band: str) -> Tuple[float, float]:
|
| 301 |
band = (band or "Medium").strip().lower()
|
| 302 |
-
if band.startswith("low"):
|
| 303 |
-
|
| 304 |
-
if band.startswith("high"):
|
| 305 |
-
return 1.2 * sigma_mkt, 3.0 * sigma_mkt
|
| 306 |
return 0.8 * sigma_mkt, 1.2 * sigma_mkt
|
| 307 |
|
| 308 |
def _summarize_three(df: pd.DataFrame) -> pd.DataFrame:
|
| 309 |
-
if df.empty:
|
| 310 |
-
return pd.DataFrame(columns=["pick", "CAPM E[r] %", "σ (hist) %", "tickers"])
|
| 311 |
out = df.copy()
|
| 312 |
-
out = out.assign(**{
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
})[["CAPM E[r] %", "σ (hist) %", "tickers"]].reset_index(drop=True)
|
| 317 |
-
out.insert(0, "pick", [1, 2, 3][: len(out)])
|
| 318 |
return out
|
| 319 |
|
| 320 |
# -------------- embeddings & re-ranking --------------
|
|
@@ -323,8 +234,7 @@ _TICKER_EMBED_CACHE: Dict[str, np.ndarray] = {}
|
|
| 323 |
|
| 324 |
def _load_embed_model():
|
| 325 |
global _EMBED_MODEL
|
| 326 |
-
if _EMBED_MODEL is not None:
|
| 327 |
-
return _EMBED_MODEL
|
| 328 |
try:
|
| 329 |
from sentence_transformers import SentenceTransformer
|
| 330 |
_EMBED_MODEL = SentenceTransformer(EMBED_MODEL_NAME)
|
|
@@ -334,131 +244,85 @@ def _load_embed_model():
|
|
| 334 |
|
| 335 |
def _embed_texts(texts: List[str]) -> np.ndarray:
|
| 336 |
model = _load_embed_model()
|
| 337 |
-
if model is None:
|
| 338 |
-
return np.zeros((len(texts), 384), dtype=float) # fallback dim
|
| 339 |
return np.array(model.encode(texts), dtype=float)
|
| 340 |
|
| 341 |
def _ticker_vec(t: str) -> np.ndarray:
|
| 342 |
t = t.upper().strip()
|
| 343 |
-
if t in _TICKER_EMBED_CACHE:
|
| 344 |
-
|
| 345 |
-
v = _embed_texts([f"ticker {t}"])[0]
|
| 346 |
-
_TICKER_EMBED_CACHE[t] = v
|
| 347 |
-
return v
|
| 348 |
|
| 349 |
def _portfolio_embedding(tickers: List[str], weights: List[float]) -> np.ndarray:
|
| 350 |
-
if not tickers:
|
| 351 |
-
|
| 352 |
-
w = np.
|
| 353 |
-
s = float(np.sum(np.abs(w)))
|
| 354 |
-
if s <= 1e-12:
|
| 355 |
-
w = np.ones(len(tickers), dtype=float) / len(tickers)
|
| 356 |
-
else:
|
| 357 |
-
w = w / s
|
| 358 |
vs = np.stack([_ticker_vec(t) for t in tickers], axis=0)
|
| 359 |
-
v = (w[:,
|
| 360 |
-
n
|
| 361 |
-
return v / (n if n > 1e-12 else 1.0)
|
| 362 |
|
| 363 |
def _cos_sim(a: np.ndarray, b: np.ndarray) -> float:
|
| 364 |
na = float(np.linalg.norm(a)); nb = float(np.linalg.norm(b))
|
| 365 |
-
if na
|
| 366 |
-
return float(np.dot(a,
|
| 367 |
-
|
| 368 |
-
def _exposure_similarity(user_map: Dict[str,
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
return float(sum(min(u[t], c[t]) for t in common))
|
| 378 |
-
|
| 379 |
-
def rerank_band_with_embeddings(user_df: pd.DataFrame,
|
| 380 |
-
band_df: pd.DataFrame,
|
| 381 |
-
alpha: float = EMBED_ALPHA,
|
| 382 |
-
mmr_lambda: float = MMR_LAMBDA,
|
| 383 |
-
top_k: int = 3) -> pd.DataFrame:
|
| 384 |
try:
|
| 385 |
-
# user portfolio embedding
|
| 386 |
u_t = user_df["ticker"].astype(str).str.upper().tolist()
|
| 387 |
u_w = pd.to_numeric(user_df["amount_usd"], errors="coerce").fillna(0.0).tolist()
|
| 388 |
u_map = {t: float(w) for t, w in zip(u_t, u_w)}
|
| 389 |
u_embed = _portfolio_embedding(u_t, u_w)
|
| 390 |
|
| 391 |
-
|
| 392 |
-
cand_rows = []
|
| 393 |
-
cand_embeds = []
|
| 394 |
for _, r in band_df.iterrows():
|
| 395 |
ts = [t.strip().upper() for t in str(r["tickers"]).split(",")]
|
| 396 |
ws = [float(x) for x in str(r["weights"]).split(",")]
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
c_embed = _portfolio_embedding(ts, ws)
|
| 403 |
-
cand_embeds.append(c_embed)
|
| 404 |
-
|
| 405 |
expo_sim = _exposure_similarity(u_map, c_map)
|
| 406 |
emb_sim = _cos_sim(u_embed, c_embed)
|
| 407 |
-
score = alpha
|
| 408 |
-
|
| 409 |
cand_rows.append((score, r))
|
| 410 |
|
| 411 |
-
if not cand_rows:
|
| 412 |
-
return band_df.head(top_k).reset_index(drop=True)
|
| 413 |
|
| 414 |
-
# MMR selection
|
| 415 |
cand_embeds = np.stack(cand_embeds, axis=0)
|
| 416 |
-
order = np.argsort([-s for s,
|
| 417 |
-
picked = []
|
| 418 |
-
picked_idx = []
|
| 419 |
-
|
| 420 |
for i in order:
|
| 421 |
-
if len(picked)
|
| 422 |
s_i, row_i = cand_rows[i]
|
| 423 |
if not picked:
|
| 424 |
-
picked.append(row_i)
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
sim_to_picked = 0.0
|
| 429 |
-
for j in picked_idx:
|
| 430 |
-
sim_to_picked = max(sim_to_picked, _cos_sim(cand_embeds[i], cand_embeds[j]))
|
| 431 |
-
mmr = mmr_lambda * s_i - (1.0 - mmr_lambda) * sim_to_picked
|
| 432 |
-
# simple thresholding vs worst current; try greedy insert
|
| 433 |
-
picked.append(row_i)
|
| 434 |
-
picked_idx.append(i)
|
| 435 |
-
|
| 436 |
out = pd.DataFrame([r for r in picked]).drop_duplicates().head(top_k).reset_index(drop=True)
|
| 437 |
-
if out.empty:
|
| 438 |
-
|
| 439 |
-
out.insert(0, "pick", [1, 2, 3][: len(out)])
|
| 440 |
return out
|
| 441 |
except Exception:
|
| 442 |
-
# graceful fallback
|
| 443 |
out = band_df.sort_values("mu_capm", ascending=False).head(top_k).reset_index(drop=True)
|
| 444 |
-
out.insert(0,
|
| 445 |
return out
|
| 446 |
|
| 447 |
# -------------- UI helpers --------------
|
| 448 |
-
def empty_positions_df():
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
def empty_holdings_df():
|
| 452 |
-
return pd.DataFrame(columns=["ticker", "weight_%", "amount_$"])
|
| 453 |
|
| 454 |
def set_horizon(years: float):
|
| 455 |
-
y = max(1.0, min(100.0, float(years)))
|
| 456 |
-
code = fred_series_for_horizon(y)
|
| 457 |
-
rf = fetch_fred_yield_annual(code)
|
| 458 |
global HORIZON_YEARS, RF_CODE, RF_ANN
|
| 459 |
-
HORIZON_YEARS = y
|
| 460 |
-
RF_CODE = code
|
| 461 |
-
RF_ANN = rf
|
| 462 |
return f"Risk-free series {code}. Latest annual rate {rf:.2%}."
|
| 463 |
|
| 464 |
def search_tickers_cb(q: str):
|
|
@@ -468,38 +332,33 @@ def search_tickers_cb(q: str):
|
|
| 468 |
|
| 469 |
def add_symbol(selection: str, table: Optional[pd.DataFrame]):
|
| 470 |
if not selection:
|
| 471 |
-
return table if isinstance(table,
|
| 472 |
symbol = selection.split("|")[0].strip().upper()
|
| 473 |
-
|
| 474 |
current = []
|
| 475 |
-
if isinstance(table,
|
| 476 |
current = [str(x).upper() for x in table["ticker"].tolist() if str(x) != "nan"]
|
| 477 |
tickers = current if symbol in current else current + [symbol]
|
| 478 |
-
|
| 479 |
val = validate_tickers(tickers, years=DEFAULT_LOOKBACK_YEARS)
|
| 480 |
tickers = [t for t in tickers if t in val]
|
| 481 |
-
|
| 482 |
amt_map = {}
|
| 483 |
-
if isinstance(table,
|
| 484 |
for _, r in table.iterrows():
|
| 485 |
-
t = str(r.get("ticker",
|
| 486 |
if t in tickers:
|
| 487 |
-
amt_map[t] = float(pd.to_numeric(r.get("amount_usd",
|
| 488 |
-
|
| 489 |
-
new_table = pd.DataFrame({"ticker": tickers, "amount_usd": [amt_map.get(t, 0.0) for t in tickers]})
|
| 490 |
if len(new_table) > MAX_TICKERS:
|
| 491 |
-
new_table = new_table.iloc[:MAX_TICKERS]
|
| 492 |
-
return new_table, f"Reached max of {MAX_TICKERS}."
|
| 493 |
return new_table, f"Added {symbol}."
|
| 494 |
|
| 495 |
def lock_ticker_column(tb: Optional[pd.DataFrame]):
|
| 496 |
-
if not isinstance(tb,
|
| 497 |
-
return pd.DataFrame(columns=["ticker",
|
| 498 |
tickers = [str(x).upper() for x in tb["ticker"].tolist()]
|
| 499 |
amounts = pd.to_numeric(tb["amount_usd"], errors="coerce").fillna(0.0).tolist()
|
| 500 |
val = validate_tickers(tickers, years=DEFAULT_LOOKBACK_YEARS)
|
| 501 |
tickers = [t for t in tickers if t in val]
|
| 502 |
-
amounts = amounts[:len(tickers)] + [0.0]
|
| 503 |
return pd.DataFrame({"ticker": tickers, "amount_usd": amounts})
|
| 504 |
|
| 505 |
# -------------- compute core --------------
|
|
@@ -508,107 +367,68 @@ UNIVERSE: List[str] = [MARKET_TICKER, "QQQ", "VTI", "SOXX", "IBIT"]
|
|
| 508 |
def _pick_to_holdings(row: pd.Series, budget: float) -> pd.DataFrame:
|
| 509 |
ts = [t.strip().upper() for t in str(row["tickers"]).split(",")]
|
| 510 |
ws = [float(x) for x in str(row["weights"]).split(",")]
|
| 511 |
-
s = sum(max(0.0,
|
| 512 |
-
ws = [max(0.0,
|
| 513 |
-
return pd.DataFrame(
|
| 514 |
-
|
| 515 |
-
columns=["ticker", "weight_%", "amount_$"]
|
| 516 |
-
)
|
| 517 |
|
| 518 |
-
def compute_all(
|
| 519 |
-
|
| 520 |
-
table: Optional[pd.DataFrame],
|
| 521 |
-
use_embeddings: bool
|
| 522 |
-
):
|
| 523 |
-
# sanitize input table
|
| 524 |
-
if isinstance(table, pd.DataFrame):
|
| 525 |
-
df = table.copy()
|
| 526 |
-
else:
|
| 527 |
-
df = pd.DataFrame(columns=["ticker", "amount_usd"])
|
| 528 |
df = df.dropna(how="all")
|
| 529 |
if "ticker" not in df.columns: df["ticker"] = []
|
| 530 |
if "amount_usd" not in df.columns: df["amount_usd"] = []
|
| 531 |
df["ticker"] = df["ticker"].astype(str).str.upper().str.strip()
|
| 532 |
df["amount_usd"] = pd.to_numeric(df["amount_usd"], errors="coerce").fillna(0.0)
|
| 533 |
-
|
| 534 |
symbols = [t for t in df["ticker"].tolist() if t]
|
| 535 |
-
if len(symbols)
|
| 536 |
-
raise gr.Error("Add at least one ticker.")
|
| 537 |
-
|
| 538 |
symbols = validate_tickers(symbols, years_lookback)
|
| 539 |
-
if len(symbols)
|
| 540 |
-
raise gr.Error("Could not validate any tickers.")
|
| 541 |
|
| 542 |
global UNIVERSE
|
| 543 |
-
UNIVERSE = list(sorted(set([s for s in symbols
|
| 544 |
|
| 545 |
df = df[df["ticker"].isin(symbols)].copy()
|
| 546 |
amounts = {r["ticker"]: float(r["amount_usd"]) for _, r in df.iterrows()}
|
| 547 |
rf_ann = RF_ANN
|
| 548 |
|
| 549 |
-
# moments
|
| 550 |
moms = estimate_all_moments_aligned(symbols, years_lookback, rf_ann)
|
| 551 |
-
betas,
|
| 552 |
|
| 553 |
-
# weights
|
| 554 |
gross = sum(abs(v) for v in amounts.values())
|
| 555 |
-
if gross <= 1e-12:
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
weights = {k: v / gross for k, v in amounts.items()}
|
| 559 |
|
| 560 |
-
|
| 561 |
-
beta_p, mu_capm, sigma_hist = portfolio_stats(weights, covA, betas, rf_ann, erp_ann)
|
| 562 |
|
| 563 |
-
# efficient counterparts (market/bills)
|
| 564 |
a_sigma, b_sigma, mu_eff_sigma = efficient_same_sigma(sigma_hist, rf_ann, erp_ann, sigma_mkt)
|
| 565 |
a_mu, b_mu, sigma_eff_mu = efficient_same_return(mu_capm, rf_ann, erp_ann, sigma_mkt)
|
| 566 |
|
| 567 |
-
|
| 568 |
-
synth = build_synthetic_dataset(UNIVERSE, covA, betas, rf_ann, erp_ann, sigma_mkt, n_rows=SYNTH_ROWS)
|
| 569 |
csv_path = os.path.join(DATA_DIR, f"investor_profiles_{int(time.time())}.csv")
|
| 570 |
-
try:
|
| 571 |
-
|
| 572 |
-
except Exception:
|
| 573 |
-
csv_path = None # not fatal
|
| 574 |
|
| 575 |
-
# band splits
|
| 576 |
def band_top3(band: str) -> pd.DataFrame:
|
| 577 |
lo, hi = _band_bounds_sigma_hist(sigma_mkt, band)
|
| 578 |
-
pick = synth[(synth["sigma_hist"]
|
| 579 |
-
if pick.empty:
|
| 580 |
-
pick = synth.copy()
|
| 581 |
-
# pre-sort by quality then re-rank with embeddings/MMR for diversity
|
| 582 |
pick = pick.sort_values("mu_capm", ascending=False).head(50).reset_index(drop=True)
|
| 583 |
if use_embeddings:
|
| 584 |
user_df = pd.DataFrame({"ticker": list(weights.keys()), "amount_usd": [amounts[t] for t in weights.keys()]})
|
| 585 |
top3 = rerank_band_with_embeddings(user_df, pick, EMBED_ALPHA, MMR_LAMBDA, top_k=3)
|
| 586 |
else:
|
| 587 |
-
top3 = pick.head(3).reset_index(drop=True)
|
| 588 |
-
top3.insert(0, "pick", [1, 2, 3][: len(top3)])
|
| 589 |
return top3
|
| 590 |
|
| 591 |
-
top3_low
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
# positions table
|
| 601 |
-
pos_table = pd.DataFrame(
|
| 602 |
-
[{
|
| 603 |
-
"ticker": t,
|
| 604 |
-
"amount_usd": amounts.get(t, 0.0),
|
| 605 |
-
"weight_exposure": weights.get(t, 0.0),
|
| 606 |
-
"beta": 1.0 if t == MARKET_TICKER else betas.get(t, np.nan)
|
| 607 |
-
} for t in symbols],
|
| 608 |
-
columns=["ticker", "amount_usd", "weight_exposure", "beta"]
|
| 609 |
-
)
|
| 610 |
|
| 611 |
-
# summary text
|
| 612 |
info = "\n".join([
|
| 613 |
"### Inputs",
|
| 614 |
f"- Lookback years {years_lookback}",
|
|
@@ -626,141 +446,91 @@ def compute_all(
|
|
| 626 |
f"- Same σ as your portfolio: Market {a_sigma:.2f}, Bills {b_sigma:.2f} → E[r] {mu_eff_sigma:.2%}",
|
| 627 |
f"- Same E[r] as your portfolio: Market {a_mu:.2f}, Bills {b_mu:.2f} → σ {sigma_eff_mu:.2%}",
|
| 628 |
"",
|
| 629 |
-
"
|
| 630 |
])
|
| 631 |
|
| 632 |
uni_msg = f"Universe set to: {', '.join(UNIVERSE)}"
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
def compute_and_render(
|
| 645 |
-
years_lookback: int,
|
| 646 |
-
table: Optional[pd.DataFrame],
|
| 647 |
-
use_embeddings: bool,
|
| 648 |
-
which_band: str,
|
| 649 |
-
pick_idx: int
|
| 650 |
-
):
|
| 651 |
outs = compute_all(years_lookback, table, use_embeddings)
|
| 652 |
-
|
| 653 |
-
# choose band & pick
|
| 654 |
band = (which_band or "Medium").strip().title()
|
| 655 |
idx = max(1, min(3, int(pick_idx))) - 1
|
| 656 |
-
|
| 657 |
-
if band == "Low":
|
| 658 |
-
top3 = outs["top3_low"]
|
| 659 |
-
elif band == "High":
|
| 660 |
-
top3 = outs["top3_high"]
|
| 661 |
-
else:
|
| 662 |
-
top3 = outs["top3_med"]
|
| 663 |
|
| 664 |
if top3.empty:
|
| 665 |
-
sugg_mu = None; sugg_sigma_hist = None
|
| 666 |
-
holdings = empty_holdings_df()
|
| 667 |
else:
|
| 668 |
row = top3.iloc[min(idx, len(top3)-1)]
|
| 669 |
-
sugg_mu = float(row["mu_capm"])
|
| 670 |
-
sugg_sigma_hist = float(row["sigma_hist"])
|
| 671 |
holdings = _pick_to_holdings(row, outs["budget"])
|
| 672 |
|
| 673 |
-
# plot
|
| 674 |
img = plot_cml_hybrid(
|
| 675 |
outs["rf_ann"], outs["erp_ann"], outs["sigma_mkt"],
|
| 676 |
outs["sigma_hist"], outs["mu_capm"],
|
| 677 |
outs["mu_eff_same_sigma"], outs["sigma_eff_same_return"],
|
| 678 |
sugg_mu, sugg_sigma_hist
|
| 679 |
)
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
img, # plot
|
| 683 |
-
outs["info"], # summary
|
| 684 |
-
outs["uni_msg"], # universe msg
|
| 685 |
-
outs["pos_table"], # positions
|
| 686 |
-
holdings, # selected holdings
|
| 687 |
-
outs["csv_path"], # dataset file
|
| 688 |
-
outs["low_sum"], # low tab summary (3 picks)
|
| 689 |
-
outs["med_sum"], # medium tab summary
|
| 690 |
-
outs["high_sum"] # high tab summary
|
| 691 |
-
)
|
| 692 |
|
| 693 |
# -------------- UI --------------
|
| 694 |
with gr.Blocks(title="Efficient Portfolio Advisor") as demo:
|
| 695 |
gr.Markdown(
|
| 696 |
"## Efficient Portfolio Advisor\n"
|
| 697 |
-
"
|
| 698 |
-
"
|
| 699 |
-
"
|
| 700 |
-
"Suggestions are generated from 1,000 candidate mixes and bucketed by risk (σ)."
|
| 701 |
)
|
| 702 |
-
|
| 703 |
with gr.Row():
|
| 704 |
with gr.Column(scale=1):
|
| 705 |
-
q = gr.Textbox(label="Search symbol")
|
| 706 |
-
search_note = gr.Markdown()
|
| 707 |
matches = gr.Dropdown(choices=[], label="Matches")
|
| 708 |
with gr.Row():
|
| 709 |
-
search_btn = gr.Button("Search")
|
| 710 |
-
add_btn = gr.Button("Add selected to portfolio")
|
| 711 |
-
|
| 712 |
gr.Markdown("### Portfolio positions (enter $ amounts; negatives allowed)")
|
| 713 |
-
table = gr.Dataframe(
|
| 714 |
-
value=pd.DataFrame(columns=["ticker", "amount_usd"]),
|
| 715 |
-
interactive=True
|
| 716 |
-
)
|
| 717 |
-
|
| 718 |
horizon = gr.Number(label="Horizon in years (1–100)", value=HORIZON_YEARS, precision=0)
|
| 719 |
lookback = gr.Slider(1, 15, value=DEFAULT_LOOKBACK_YEARS, step=1, label="Lookback years")
|
| 720 |
use_emb = gr.Checkbox(value=True, label="Use finance embeddings + MMR for diverse picks")
|
| 721 |
-
|
| 722 |
gr.Markdown("### Suggestions")
|
| 723 |
with gr.Tabs():
|
| 724 |
with gr.Tab("Low"):
|
| 725 |
low_summary = gr.Dataframe(value=empty_holdings_df(), interactive=False, label="Top 3 (Low risk)")
|
| 726 |
-
pick_low = gr.Radio(choices=["1",
|
| 727 |
with gr.Tab("Medium"):
|
| 728 |
med_summary = gr.Dataframe(value=empty_holdings_df(), interactive=False, label="Top 3 (Medium risk)")
|
| 729 |
-
pick_med = gr.Radio(choices=["1",
|
| 730 |
with gr.Tab("High"):
|
| 731 |
high_summary = gr.Dataframe(value=empty_holdings_df(), interactive=False, label="Top 3 (High risk)")
|
| 732 |
-
pick_high = gr.Radio(choices=["1",
|
| 733 |
-
|
| 734 |
run_btn = gr.Button("Compute (build dataset & suggest)")
|
| 735 |
-
|
| 736 |
with gr.Column(scale=1):
|
| 737 |
plot = gr.Image(label="Capital Market Line (CAPM)", type="pil")
|
| 738 |
summary = gr.Markdown(label="Inputs & Results")
|
| 739 |
universe_msg = gr.Textbox(label="Universe status", interactive=False)
|
| 740 |
-
positions = gr.Dataframe(
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
selected_table = gr.Dataframe(
|
| 744 |
-
value=empty_holdings_df(),
|
| 745 |
-
interactive=False,
|
| 746 |
-
label="Selected suggestion holdings (% / $)"
|
| 747 |
-
)
|
| 748 |
dl = gr.File(label="Generated dataset CSV", value=None, visible=True)
|
| 749 |
|
| 750 |
-
# wire: search / add / locking / horizon
|
| 751 |
search_btn.click(fn=search_tickers_cb, inputs=q, outputs=[search_note, matches])
|
| 752 |
add_btn.click(fn=add_symbol, inputs=[matches, table], outputs=[table, search_note])
|
| 753 |
table.change(fn=lock_ticker_column, inputs=table, outputs=table)
|
| 754 |
horizon.change(fn=set_horizon, inputs=horizon, outputs=universe_msg)
|
| 755 |
|
| 756 |
-
# main compute (defaults to Medium, pick 1)
|
| 757 |
run_btn.click(
|
| 758 |
fn=compute_and_render,
|
| 759 |
inputs=[lookback, table, use_emb, gr.State("Medium"), gr.State(1)],
|
| 760 |
outputs=[plot, summary, universe_msg, positions, selected_table, dl, low_summary, med_summary, high_summary]
|
| 761 |
)
|
| 762 |
-
|
| 763 |
-
# band radios trigger recompute with their band + index
|
| 764 |
pick_low.change(
|
| 765 |
fn=compute_and_render,
|
| 766 |
inputs=[lookback, table, use_emb, gr.State("Low"), pick_low],
|
|
@@ -777,16 +547,9 @@ with gr.Blocks(title="Efficient Portfolio Advisor") as demo:
|
|
| 777 |
outputs=[plot, summary, universe_msg, positions, selected_table, dl, low_summary, med_summary, high_summary]
|
| 778 |
)
|
| 779 |
|
| 780 |
-
# initialize risk-free at launch
|
| 781 |
RF_CODE = fred_series_for_horizon(HORIZON_YEARS)
|
| 782 |
RF_ANN = fetch_fred_yield_annual(RF_CODE)
|
| 783 |
|
| 784 |
if __name__ == "__main__":
|
| 785 |
-
# Gradio 5.x: no concurrency_count on .queue()
|
| 786 |
demo.queue()
|
| 787 |
-
demo.launch(
|
| 788 |
-
server_name="0.0.0.0",
|
| 789 |
-
server_port=int(os.environ.get("PORT", 7860)),
|
| 790 |
-
show_api=False,
|
| 791 |
-
share=False,
|
| 792 |
-
)
|
|
|
|
| 1 |
+
# app.py (CML-safe: sigma uses full cov incl. market)
|
| 2 |
+
import os, io, math, time, warnings
|
| 3 |
warnings.filterwarnings("ignore")
|
| 4 |
|
| 5 |
from typing import List, Tuple, Dict, Optional
|
|
|
|
| 20 |
DEFAULT_LOOKBACK_YEARS = 10
|
| 21 |
MARKET_TICKER = "VOO"
|
| 22 |
|
| 23 |
+
SYNTH_ROWS = 1000
|
| 24 |
EMBED_MODEL_NAME = "FinLang/finance-embeddings-investopedia"
|
| 25 |
+
EMBED_ALPHA = 0.6
|
| 26 |
+
MMR_LAMBDA = 0.7
|
| 27 |
|
|
|
|
| 28 |
HORIZON_YEARS = 10
|
| 29 |
RF_CODE = "DGS10"
|
| 30 |
+
RF_ANN = 0.0375
|
| 31 |
|
| 32 |
# ---------------- helpers ----------------
|
| 33 |
def fred_series_for_horizon(years: float) -> str:
|
|
|
|
| 43 |
def fetch_fred_yield_annual(code: str) -> float:
|
| 44 |
url = f"https://fred.stlouisfed.org/graph/fredgraph.csv?id={code}"
|
| 45 |
try:
|
| 46 |
+
r = requests.get(url, timeout=10); r.raise_for_status()
|
|
|
|
| 47 |
df = pd.read_csv(io.StringIO(r.text))
|
| 48 |
s = pd.to_numeric(df.iloc[:, 1], errors="coerce").dropna()
|
| 49 |
return float(s.iloc[-1] / 100.0) if len(s) else 0.03
|
|
|
|
| 54 |
tickers = list(dict.fromkeys([t.upper().strip() for t in tickers if t]))
|
| 55 |
start = (pd.Timestamp.today(tz="UTC") - pd.DateOffset(years=int(years), days=7)).date()
|
| 56 |
end = pd.Timestamp.today(tz="UTC").date()
|
|
|
|
| 57 |
df = yf.download(
|
| 58 |
+
tickers, start=start, end=end, interval="1mo",
|
| 59 |
+
auto_adjust=True, actions=False, progress=False,
|
| 60 |
+
group_by="column", threads=False,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
)
|
| 62 |
+
if isinstance(df, pd.Series): df = df.to_frame()
|
|
|
|
|
|
|
|
|
|
| 63 |
if isinstance(df.columns, pd.MultiIndex):
|
| 64 |
lvl0 = [str(x) for x in df.columns.get_level_values(0).unique()]
|
| 65 |
+
if "Close" in lvl0: df = df["Close"]
|
| 66 |
+
elif "Adj Close" in lvl0: df = df["Adj Close"]
|
| 67 |
+
else: df = df.xs(df.columns.levels[0][-1], axis=1, level=0, drop_level=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
cols = [c for c in tickers if c in df.columns]
|
| 69 |
+
return df[cols].dropna(how="all").fillna(method="ffill")
|
|
|
|
| 70 |
|
| 71 |
def monthly_returns(prices: pd.DataFrame) -> pd.DataFrame:
|
| 72 |
return prices.pct_change().dropna()
|
| 73 |
|
| 74 |
def yahoo_search(query: str):
|
| 75 |
+
if not query or not str(query).strip(): return []
|
|
|
|
| 76 |
url = "https://query1.finance.yahoo.com/v1/finance/search"
|
| 77 |
params = {"q": query.strip(), "quotesCount": 10, "newsCount": 0}
|
| 78 |
headers = {"User-Agent": "Mozilla/5.0"}
|
| 79 |
try:
|
| 80 |
+
r = requests.get(url, params=params, headers=headers, timeout=10); r.raise_for_status()
|
| 81 |
+
data = r.json(); out = []
|
|
|
|
|
|
|
| 82 |
for q in data.get("quotes", []):
|
| 83 |
+
sym = q.get("symbol"); name = q.get("shortname") or q.get("longname") or ""; exch = q.get("exchDisp") or ""
|
| 84 |
+
if sym and sym.isascii(): out.append(f"{sym} | {name} | {exch}")
|
| 85 |
+
if not out: out = [f"{query.strip().upper()} | typed symbol | n/a"]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
return out[:10]
|
| 87 |
except Exception:
|
| 88 |
return [f"{query.strip().upper()} | typed symbol | n/a"]
|
|
|
|
| 91 |
base = [s for s in dict.fromkeys([t.upper().strip() for t in symbols]) if s]
|
| 92 |
px = fetch_prices_monthly(base + [MARKET_TICKER], years)
|
| 93 |
ok = [s for s in base if s in px.columns]
|
| 94 |
+
if MARKET_TICKER not in px.columns: return []
|
|
|
|
| 95 |
return ok
|
| 96 |
|
| 97 |
+
# ---------- aligned moments & covariances (incl. market) ----------
|
| 98 |
def get_aligned_monthly_returns(symbols: List[str], years: int) -> pd.DataFrame:
|
| 99 |
+
uniq = [c for c in dict.fromkeys(symbols)]
|
| 100 |
+
if MARKET_TICKER not in uniq: uniq.append(MARKET_TICKER)
|
| 101 |
+
px = fetch_prices_monthly(uniq, years)
|
| 102 |
rets = monthly_returns(px)
|
| 103 |
+
cols = [c for c in uniq if c in rets.columns]
|
| 104 |
R = rets[cols].dropna(how="any")
|
| 105 |
return R.loc[:, ~R.columns.duplicated()]
|
| 106 |
|
|
|
|
| 111 |
rf_m = rf_ann / 12.0
|
| 112 |
|
| 113 |
m = R[MARKET_TICKER]
|
| 114 |
+
if isinstance(m, pd.DataFrame): m = m.iloc[:, 0].squeeze()
|
|
|
|
|
|
|
| 115 |
mu_m_ann = float(m.mean() * 12.0)
|
| 116 |
sigma_m_ann = float(m.std(ddof=1) * math.sqrt(12.0))
|
| 117 |
erp_ann = float(mu_m_ann - rf_ann)
|
| 118 |
|
| 119 |
ex_m = m - rf_m
|
| 120 |
+
var_m = float(np.var(ex_m.values, ddof=1)); var_m = max(var_m, 1e-9)
|
|
|
|
| 121 |
|
| 122 |
betas: Dict[str, float] = {}
|
| 123 |
for s in [c for c in R.columns if c != MARKET_TICKER]:
|
|
|
|
| 126 |
betas[s] = cov_sm / var_m
|
| 127 |
betas[MARKET_TICKER] = 1.0
|
| 128 |
|
| 129 |
+
# FULL covariance including MARKET_TICKER (crucial to keep points ≤ CML)
|
| 130 |
+
cov_all_ann = pd.DataFrame(np.cov(R.values.T, ddof=1) * 12.0,
|
| 131 |
+
index=R.columns, columns=R.columns)
|
| 132 |
|
| 133 |
+
return {"betas": betas, "cov_all_ann": cov_all_ann, "erp_ann": erp_ann, "sigma_m_ann": sigma_m_ann}
|
| 134 |
|
| 135 |
def capm_er(beta: float, rf_ann: float, erp_ann: float) -> float:
|
| 136 |
return float(rf_ann + beta * erp_ann)
|
| 137 |
|
| 138 |
def portfolio_stats(weights: Dict[str, float],
|
| 139 |
+
cov_all_ann: pd.DataFrame,
|
| 140 |
betas: Dict[str, float],
|
| 141 |
rf_ann: float,
|
| 142 |
erp_ann: float) -> Tuple[float, float, float]:
|
| 143 |
tickers = list(weights.keys())
|
| 144 |
w = np.array([weights[t] for t in tickers], dtype=float)
|
| 145 |
gross = float(np.sum(np.abs(w)))
|
| 146 |
+
if gross <= 1e-12: return 0.0, rf_ann, 0.0
|
|
|
|
| 147 |
w_expo = w / gross
|
| 148 |
beta_p = float(np.dot([betas.get(t, 0.0) for t in tickers], w_expo))
|
| 149 |
mu_capm = capm_er(beta_p, rf_ann, erp_ann)
|
| 150 |
+
cov = cov_all_ann.reindex(index=tickers, columns=tickers).fillna(0.0).to_numpy()
|
| 151 |
+
sigma_hist = float(max(w_expo.T @ cov @ w_expo, 0.0)) ** 0.5
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
return beta_p, mu_capm, sigma_hist
|
| 153 |
|
| 154 |
def efficient_same_sigma(sigma_target: float, rf_ann: float, erp_ann: float, sigma_mkt: float):
|
| 155 |
+
if sigma_mkt <= 1e-12: return 0.0, 1.0, rf_ann
|
|
|
|
| 156 |
a = sigma_target / sigma_mkt
|
| 157 |
+
return a, 1.0 - a, rf_ann + a * erp_ann
|
| 158 |
|
| 159 |
def efficient_same_return(mu_target: float, rf_ann: float, erp_ann: float, sigma_mkt: float):
|
| 160 |
+
if abs(erp_ann) <= 1e-12: return 0.0, 1.0, rf_ann
|
|
|
|
| 161 |
a = (mu_target - rf_ann) / erp_ann
|
| 162 |
+
return a, 1.0 - a, abs(a) * sigma_mkt
|
| 163 |
|
| 164 |
# -------------- plotting --------------
|
| 165 |
+
def _pct(x): return np.asarray(x, dtype=float) * 100.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
|
| 167 |
+
def plot_cml_hybrid(rf_ann, erp_ann, sigma_mkt,
|
| 168 |
+
sigma_hist_port, mu_capm_port,
|
| 169 |
+
mu_eff_same_sigma, sigma_eff_same_return,
|
| 170 |
+
sugg_mu=None, sugg_sigma_hist=None) -> Image.Image:
|
| 171 |
+
fig = plt.figure(figsize=(6.5, 4.2), dpi=120)
|
| 172 |
+
xmax = max(0.3, sigma_mkt * 2.2, (sigma_hist_port or 0.0) * 1.6,
|
| 173 |
+
(sigma_eff_same_return or 0.0) * 1.6, (sugg_sigma_hist or 0.0) * 1.6)
|
| 174 |
xs = np.linspace(0.0, xmax, 240)
|
| 175 |
cml = rf_ann + (erp_ann / max(sigma_mkt, 1e-9)) * xs if sigma_mkt > 1e-12 else np.full_like(xs, rf_ann)
|
|
|
|
|
|
|
| 176 |
plt.plot(_pct(xs), _pct(cml), label="CML (Market/Bills)", linewidth=1.8)
|
| 177 |
plt.scatter([_pct(0)], [_pct(rf_ann)], label="Risk-free", zorder=3)
|
| 178 |
plt.scatter([_pct(sigma_mkt)], [_pct(rf_ann + erp_ann)], label="Market", zorder=3)
|
|
|
|
|
|
|
| 179 |
plt.scatter([_pct(sigma_hist_port)], [_pct(mu_capm_port)], label="Your CAPM point", marker="o", zorder=4)
|
|
|
|
|
|
|
| 180 |
plt.scatter([_pct(sigma_hist_port)], [_pct(mu_eff_same_sigma)], label="Efficient (same σ)", marker="^", zorder=4)
|
| 181 |
plt.scatter([_pct(sigma_eff_same_return)], [_pct(mu_capm_port)], label="Efficient (same E[r])", marker="s", zorder=4)
|
|
|
|
|
|
|
| 182 |
if (sugg_mu is not None) and (sugg_sigma_hist is not None):
|
| 183 |
plt.scatter([_pct(sugg_sigma_hist)], [_pct(sugg_mu)], label="Selected Suggestion", marker="X", s=70, zorder=5)
|
| 184 |
+
plt.xlabel("σ (historical, annualized, %)"); plt.ylabel("CAPM E[r] (annual, %)")
|
| 185 |
+
plt.legend(loc="best", fontsize=8); plt.tight_layout()
|
| 186 |
+
buf = io.BytesIO(); plt.savefig(buf, format="png"); plt.close(fig); buf.seek(0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
return Image.open(buf)
|
| 188 |
|
| 189 |
+
# -------------- synthetic dataset (σ uses FULL cov) --------------
|
| 190 |
def build_synthetic_dataset(universe: List[str],
|
| 191 |
+
cov_all_ann: pd.DataFrame,
|
| 192 |
betas: Dict[str, float],
|
| 193 |
rf_ann: float,
|
| 194 |
erp_ann: float,
|
|
|
|
| 195 |
n_rows: int = SYNTH_ROWS) -> pd.DataFrame:
|
| 196 |
rng = np.random.default_rng(12345)
|
| 197 |
+
if MARKET_TICKER not in universe: universe = list(universe) + [MARKET_TICKER]
|
|
|
|
|
|
|
|
|
|
| 198 |
rows = []
|
| 199 |
for _ in range(n_rows):
|
| 200 |
k = int(rng.integers(low=2, high=min(8, len(universe)) + 1))
|
| 201 |
picks = list(rng.choice(universe, size=k, replace=False))
|
|
|
|
|
|
|
| 202 |
w = rng.dirichlet(np.ones(k))
|
|
|
|
|
|
|
| 203 |
beta_p = float(np.dot([betas.get(t, 0.0) for t in picks], w))
|
| 204 |
mu_capm = capm_er(beta_p, rf_ann, erp_ann)
|
| 205 |
+
sub_cov = cov_all_ann.reindex(index=picks, columns=picks).fillna(0.0).to_numpy()
|
| 206 |
+
sigma_hist = float(max(w.T @ sub_cov @ w, 0.0)) ** 0.5
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
rows.append({
|
| 208 |
"tickers": ",".join(picks),
|
| 209 |
"weights": ",".join(f"{x:.6f}" for x in w),
|
|
|
|
| 215 |
|
| 216 |
def _band_bounds_sigma_hist(sigma_mkt: float, band: str) -> Tuple[float, float]:
|
| 217 |
band = (band or "Medium").strip().lower()
|
| 218 |
+
if band.startswith("low"): return 0.0, 0.8 * sigma_mkt
|
| 219 |
+
if band.startswith("high"): return 1.2 * sigma_mkt, 3.0 * sigma_mkt
|
|
|
|
|
|
|
| 220 |
return 0.8 * sigma_mkt, 1.2 * sigma_mkt
|
| 221 |
|
| 222 |
def _summarize_three(df: pd.DataFrame) -> pd.DataFrame:
|
| 223 |
+
if df.empty: return pd.DataFrame(columns=["pick","CAPM E[r] %","σ (hist) %","tickers"])
|
|
|
|
| 224 |
out = df.copy()
|
| 225 |
+
out = out.assign(**{"CAPM E[r] %": (out["mu_capm"]*100).round(2),
|
| 226 |
+
"σ (hist) %": (out["sigma_hist"]*100).round(2),
|
| 227 |
+
"tickers": out["tickers"]})[["CAPM E[r] %","σ (hist) %","tickers"]]
|
| 228 |
+
out = out.reset_index(drop=True); out.insert(0, "pick", [1,2,3][:len(out)])
|
|
|
|
|
|
|
| 229 |
return out
|
| 230 |
|
| 231 |
# -------------- embeddings & re-ranking --------------
|
|
|
|
| 234 |
|
| 235 |
def _load_embed_model():
|
| 236 |
global _EMBED_MODEL
|
| 237 |
+
if _EMBED_MODEL is not None: return _EMBED_MODEL
|
|
|
|
| 238 |
try:
|
| 239 |
from sentence_transformers import SentenceTransformer
|
| 240 |
_EMBED_MODEL = SentenceTransformer(EMBED_MODEL_NAME)
|
|
|
|
| 244 |
|
| 245 |
def _embed_texts(texts: List[str]) -> np.ndarray:
|
| 246 |
model = _load_embed_model()
|
| 247 |
+
if model is None: return np.zeros((len(texts), 384), dtype=float)
|
|
|
|
| 248 |
return np.array(model.encode(texts), dtype=float)
|
| 249 |
|
| 250 |
def _ticker_vec(t: str) -> np.ndarray:
|
| 251 |
t = t.upper().strip()
|
| 252 |
+
if t in _TICKER_EMBED_CACHE: return _TICKER_EMBED_CACHE[t]
|
| 253 |
+
v = _embed_texts([f"ticker {t}"])[0]; _TICKER_EMBED_CACHE[t] = v; return v
|
|
|
|
|
|
|
|
|
|
| 254 |
|
| 255 |
def _portfolio_embedding(tickers: List[str], weights: List[float]) -> np.ndarray:
|
| 256 |
+
if not tickers: return np.zeros(384, dtype=float)
|
| 257 |
+
w = np.array(weights, dtype=float); s = float(np.sum(np.abs(w)))
|
| 258 |
+
w = (np.ones(len(tickers))/len(tickers)) if s<=1e-12 else (w/s)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
vs = np.stack([_ticker_vec(t) for t in tickers], axis=0)
|
| 260 |
+
v = (w[:,None]*vs).sum(axis=0); n = float(np.linalg.norm(v))
|
| 261 |
+
return v/(n if n>1e-12 else 1.0)
|
|
|
|
| 262 |
|
| 263 |
def _cos_sim(a: np.ndarray, b: np.ndarray) -> float:
|
| 264 |
na = float(np.linalg.norm(a)); nb = float(np.linalg.norm(b))
|
| 265 |
+
if na<=1e-12 or nb<=1e-12: return 0.0
|
| 266 |
+
return float(np.dot(a,b)/(na*nb))
|
| 267 |
+
|
| 268 |
+
def _exposure_similarity(user_map: Dict[str,float], cand_map: Dict[str,float]) -> float:
|
| 269 |
+
s_user = sum(abs(x) for x in user_map.values()); s_c = sum(abs(x) for x in cand_map.values())
|
| 270 |
+
if s_user<=1e-12 or s_c<=1e-12: return 0.0
|
| 271 |
+
u = {k:abs(v)/s_user for k,v in user_map.items()}
|
| 272 |
+
c = {k:abs(v)/s_c for k,v in cand_map.items()}
|
| 273 |
+
common = set(u)&set(c); return float(sum(min(u[t],c[t]) for t in common))
|
| 274 |
+
|
| 275 |
+
def rerank_band_with_embeddings(user_df: pd.DataFrame, band_df: pd.DataFrame,
|
| 276 |
+
alpha: float = EMBED_ALPHA, mmr_lambda: float = MMR_LAMBDA, top_k: int = 3) -> pd.DataFrame:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
try:
|
|
|
|
| 278 |
u_t = user_df["ticker"].astype(str).str.upper().tolist()
|
| 279 |
u_w = pd.to_numeric(user_df["amount_usd"], errors="coerce").fillna(0.0).tolist()
|
| 280 |
u_map = {t: float(w) for t, w in zip(u_t, u_w)}
|
| 281 |
u_embed = _portfolio_embedding(u_t, u_w)
|
| 282 |
|
| 283 |
+
cand_rows = []; cand_embeds = []
|
|
|
|
|
|
|
| 284 |
for _, r in band_df.iterrows():
|
| 285 |
ts = [t.strip().upper() for t in str(r["tickers"]).split(",")]
|
| 286 |
ws = [float(x) for x in str(r["weights"]).split(",")]
|
| 287 |
+
s = sum(max(0.0,w) for w in ws) or 1.0
|
| 288 |
+
ws = [max(0.0,w)/s for w in ws]
|
| 289 |
+
c_map = {t:w for t,w in zip(ts,ws)}
|
| 290 |
+
c_embed = _portfolio_embedding(ts, ws); cand_embeds.append(c_embed)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
expo_sim = _exposure_similarity(u_map, c_map)
|
| 292 |
emb_sim = _cos_sim(u_embed, c_embed)
|
| 293 |
+
score = alpha*expo_sim + (1.0-alpha)*emb_sim
|
|
|
|
| 294 |
cand_rows.append((score, r))
|
| 295 |
|
| 296 |
+
if not cand_rows: return band_df.head(top_k).reset_index(drop=True)
|
|
|
|
| 297 |
|
|
|
|
| 298 |
cand_embeds = np.stack(cand_embeds, axis=0)
|
| 299 |
+
order = np.argsort([-s for s,_ in cand_rows])
|
| 300 |
+
picked = []; picked_idx = []
|
|
|
|
|
|
|
| 301 |
for i in order:
|
| 302 |
+
if len(picked)>=top_k: break
|
| 303 |
s_i, row_i = cand_rows[i]
|
| 304 |
if not picked:
|
| 305 |
+
picked.append(row_i); picked_idx.append(i); continue
|
| 306 |
+
sim_to_picked = max(_cos_sim(cand_embeds[i], cand_embeds[j]) for j in picked_idx)
|
| 307 |
+
mmr = mmr_lambda*s_i - (1.0-mmr_lambda)*sim_to_picked # noqa: F841 (kept for clarity)
|
| 308 |
+
picked.append(row_i); picked_idx.append(i)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
out = pd.DataFrame([r for r in picked]).drop_duplicates().head(top_k).reset_index(drop=True)
|
| 310 |
+
if out.empty: out = band_df.head(top_k).reset_index(drop=True)
|
| 311 |
+
out.insert(0,"pick",[1,2,3][:len(out)])
|
|
|
|
| 312 |
return out
|
| 313 |
except Exception:
|
|
|
|
| 314 |
out = band_df.sort_values("mu_capm", ascending=False).head(top_k).reset_index(drop=True)
|
| 315 |
+
out.insert(0,"pick",[1,2,3][:len(out)])
|
| 316 |
return out
|
| 317 |
|
| 318 |
# -------------- UI helpers --------------
|
| 319 |
+
def empty_positions_df(): return pd.DataFrame(columns=["ticker","amount_usd","weight_exposure","beta"])
|
| 320 |
+
def empty_holdings_df(): return pd.DataFrame(columns=["ticker","weight_%","amount_$"])
|
|
|
|
|
|
|
|
|
|
| 321 |
|
| 322 |
def set_horizon(years: float):
|
| 323 |
+
y = max(1.0, min(100.0, float(years))); code = fred_series_for_horizon(y); rf = fetch_fred_yield_annual(code)
|
|
|
|
|
|
|
| 324 |
global HORIZON_YEARS, RF_CODE, RF_ANN
|
| 325 |
+
HORIZON_YEARS, RF_CODE, RF_ANN = y, code, rf
|
|
|
|
|
|
|
| 326 |
return f"Risk-free series {code}. Latest annual rate {rf:.2%}."
|
| 327 |
|
| 328 |
def search_tickers_cb(q: str):
|
|
|
|
| 332 |
|
| 333 |
def add_symbol(selection: str, table: Optional[pd.DataFrame]):
|
| 334 |
if not selection:
|
| 335 |
+
return table if isinstance(table,pd.DataFrame) else pd.DataFrame(columns=["ticker","amount_usd"]), "Pick a row in Matches first."
|
| 336 |
symbol = selection.split("|")[0].strip().upper()
|
|
|
|
| 337 |
current = []
|
| 338 |
+
if isinstance(table,pd.DataFrame) and not table.empty:
|
| 339 |
current = [str(x).upper() for x in table["ticker"].tolist() if str(x) != "nan"]
|
| 340 |
tickers = current if symbol in current else current + [symbol]
|
|
|
|
| 341 |
val = validate_tickers(tickers, years=DEFAULT_LOOKBACK_YEARS)
|
| 342 |
tickers = [t for t in tickers if t in val]
|
|
|
|
| 343 |
amt_map = {}
|
| 344 |
+
if isinstance(table,pd.DataFrame) and not table.empty:
|
| 345 |
for _, r in table.iterrows():
|
| 346 |
+
t = str(r.get("ticker","")).upper()
|
| 347 |
if t in tickers:
|
| 348 |
+
amt_map[t] = float(pd.to_numeric(r.get("amount_usd",0.0), errors="coerce") or 0.0)
|
| 349 |
+
new_table = pd.DataFrame({"ticker": tickers, "amount_usd": [amt_map.get(t,0.0) for t in tickers]})
|
|
|
|
| 350 |
if len(new_table) > MAX_TICKERS:
|
| 351 |
+
new_table = new_table.iloc[:MAX_TICKERS]; return new_table, f"Reached max of {MAX_TICKERS}."
|
|
|
|
| 352 |
return new_table, f"Added {symbol}."
|
| 353 |
|
| 354 |
def lock_ticker_column(tb: Optional[pd.DataFrame]):
|
| 355 |
+
if not isinstance(tb,pd.DataFrame) or tb.empty:
|
| 356 |
+
return pd.DataFrame(columns=["ticker","amount_usd"])
|
| 357 |
tickers = [str(x).upper() for x in tb["ticker"].tolist()]
|
| 358 |
amounts = pd.to_numeric(tb["amount_usd"], errors="coerce").fillna(0.0).tolist()
|
| 359 |
val = validate_tickers(tickers, years=DEFAULT_LOOKBACK_YEARS)
|
| 360 |
tickers = [t for t in tickers if t in val]
|
| 361 |
+
amounts = amounts[:len(tickers)] + [0.0]*max(0, len(tickers)-len(amounts))
|
| 362 |
return pd.DataFrame({"ticker": tickers, "amount_usd": amounts})
|
| 363 |
|
| 364 |
# -------------- compute core --------------
|
|
|
|
| 367 |
def _pick_to_holdings(row: pd.Series, budget: float) -> pd.DataFrame:
|
| 368 |
ts = [t.strip().upper() for t in str(row["tickers"]).split(",")]
|
| 369 |
ws = [float(x) for x in str(row["weights"]).split(",")]
|
| 370 |
+
s = sum(max(0.0,w) for w in ws) or 1.0
|
| 371 |
+
ws = [max(0.0,w)/s for w in ws]
|
| 372 |
+
return pd.DataFrame([{"ticker": t, "weight_%": round(w*100,2), "amount_$": round(w*budget,0)} for t,w in zip(ts,ws)],
|
| 373 |
+
columns=["ticker","weight_%","amount_$"])
|
|
|
|
|
|
|
| 374 |
|
| 375 |
+
def compute_all(years_lookback: int, table: Optional[pd.DataFrame], use_embeddings: bool):
|
| 376 |
+
df = table.copy() if isinstance(table,pd.DataFrame) else pd.DataFrame(columns=["ticker","amount_usd"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 377 |
df = df.dropna(how="all")
|
| 378 |
if "ticker" not in df.columns: df["ticker"] = []
|
| 379 |
if "amount_usd" not in df.columns: df["amount_usd"] = []
|
| 380 |
df["ticker"] = df["ticker"].astype(str).str.upper().str.strip()
|
| 381 |
df["amount_usd"] = pd.to_numeric(df["amount_usd"], errors="coerce").fillna(0.0)
|
|
|
|
| 382 |
symbols = [t for t in df["ticker"].tolist() if t]
|
| 383 |
+
if len(symbols)==0: raise gr.Error("Add at least one ticker.")
|
|
|
|
|
|
|
| 384 |
symbols = validate_tickers(symbols, years_lookback)
|
| 385 |
+
if len(symbols)==0: raise gr.Error("Could not validate any tickers.")
|
|
|
|
| 386 |
|
| 387 |
global UNIVERSE
|
| 388 |
+
UNIVERSE = list(sorted(set([s for s in symbols] + [MARKET_TICKER])))[:MAX_TICKERS]
|
| 389 |
|
| 390 |
df = df[df["ticker"].isin(symbols)].copy()
|
| 391 |
amounts = {r["ticker"]: float(r["amount_usd"]) for _, r in df.iterrows()}
|
| 392 |
rf_ann = RF_ANN
|
| 393 |
|
|
|
|
| 394 |
moms = estimate_all_moments_aligned(symbols, years_lookback, rf_ann)
|
| 395 |
+
betas, cov_all_ann, erp_ann, sigma_mkt = moms["betas"], moms["cov_all_ann"], moms["erp_ann"], moms["sigma_m_ann"]
|
| 396 |
|
|
|
|
| 397 |
gross = sum(abs(v) for v in amounts.values())
|
| 398 |
+
if gross <= 1e-12: raise gr.Error("All amounts are zero.")
|
| 399 |
+
weights = {k: v/gross for k,v in amounts.items()}
|
|
|
|
|
|
|
| 400 |
|
| 401 |
+
beta_p, mu_capm, sigma_hist = portfolio_stats(weights, cov_all_ann, betas, rf_ann, erp_ann)
|
|
|
|
| 402 |
|
|
|
|
| 403 |
a_sigma, b_sigma, mu_eff_sigma = efficient_same_sigma(sigma_hist, rf_ann, erp_ann, sigma_mkt)
|
| 404 |
a_mu, b_mu, sigma_eff_mu = efficient_same_return(mu_capm, rf_ann, erp_ann, sigma_mkt)
|
| 405 |
|
| 406 |
+
synth = build_synthetic_dataset(UNIVERSE, cov_all_ann, betas, rf_ann, erp_ann, n_rows=SYNTH_ROWS)
|
|
|
|
| 407 |
csv_path = os.path.join(DATA_DIR, f"investor_profiles_{int(time.time())}.csv")
|
| 408 |
+
try: synth.to_csv(csv_path, index=False)
|
| 409 |
+
except Exception: csv_path = None
|
|
|
|
|
|
|
| 410 |
|
|
|
|
| 411 |
def band_top3(band: str) -> pd.DataFrame:
|
| 412 |
lo, hi = _band_bounds_sigma_hist(sigma_mkt, band)
|
| 413 |
+
pick = synth[(synth["sigma_hist"]>=lo) & (synth["sigma_hist"]<=hi)].copy()
|
| 414 |
+
if pick.empty: pick = synth.copy()
|
|
|
|
|
|
|
| 415 |
pick = pick.sort_values("mu_capm", ascending=False).head(50).reset_index(drop=True)
|
| 416 |
if use_embeddings:
|
| 417 |
user_df = pd.DataFrame({"ticker": list(weights.keys()), "amount_usd": [amounts[t] for t in weights.keys()]})
|
| 418 |
top3 = rerank_band_with_embeddings(user_df, pick, EMBED_ALPHA, MMR_LAMBDA, top_k=3)
|
| 419 |
else:
|
| 420 |
+
top3 = pick.head(3).reset_index(drop=True); top3.insert(0,"pick",[1,2,3][:len(top3)])
|
|
|
|
| 421 |
return top3
|
| 422 |
|
| 423 |
+
top3_low, top3_med, top3_high = band_top3("Low"), band_top3("Medium"), band_top3("High")
|
| 424 |
+
low_sum, med_sum, high_sum = _summarize_three(top3_low), _summarize_three(top3_med), _summarize_three(top3_high)
|
| 425 |
+
|
| 426 |
+
pos_table = pd.DataFrame([{
|
| 427 |
+
"ticker": t, "amount_usd": amounts.get(t,0.0),
|
| 428 |
+
"weight_exposure": weights.get(t,0.0),
|
| 429 |
+
"beta": 1.0 if t==MARKET_TICKER else betas.get(t, np.nan)
|
| 430 |
+
} for t in symbols], columns=["ticker","amount_usd","weight_exposure","beta"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 431 |
|
|
|
|
| 432 |
info = "\n".join([
|
| 433 |
"### Inputs",
|
| 434 |
f"- Lookback years {years_lookback}",
|
|
|
|
| 446 |
f"- Same σ as your portfolio: Market {a_sigma:.2f}, Bills {b_sigma:.2f} → E[r] {mu_eff_sigma:.2%}",
|
| 447 |
f"- Same E[r] as your portfolio: Market {a_mu:.2f}, Bills {b_mu:.2f} → σ {sigma_eff_mu:.2%}",
|
| 448 |
"",
|
| 449 |
+
"_All points are guaranteed on/under the CML because σ uses the full covariance (incl. market)._"
|
| 450 |
])
|
| 451 |
|
| 452 |
uni_msg = f"Universe set to: {', '.join(UNIVERSE)}"
|
| 453 |
+
return dict(rf_ann=rf_ann, erp_ann=erp_ann, sigma_mkt=sigma_mkt,
|
| 454 |
+
mu_capm=mu_capm, sigma_hist=sigma_hist,
|
| 455 |
+
mu_eff_same_sigma=mu_eff_sigma, sigma_eff_same_return=sigma_eff_mu,
|
| 456 |
+
pos_table=pos_table, info=info, uni_msg=uni_msg, csv_path=csv_path,
|
| 457 |
+
low_sum=low_sum, med_sum=med_sum, high_sum=high_sum,
|
| 458 |
+
top3_low=top3_low, top3_med=top3_med, top3_high=top3_high,
|
| 459 |
+
budget=sum(abs(v) for v in amounts.values()))
|
| 460 |
+
|
| 461 |
+
def compute_and_render(years_lookback: int, table: Optional[pd.DataFrame], use_embeddings: bool,
|
| 462 |
+
which_band: str, pick_idx: int):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 463 |
outs = compute_all(years_lookback, table, use_embeddings)
|
|
|
|
|
|
|
| 464 |
band = (which_band or "Medium").strip().title()
|
| 465 |
idx = max(1, min(3, int(pick_idx))) - 1
|
| 466 |
+
top3 = outs["top3_med"] if band=="Medium" else (outs["top3_low"] if band=="Low" else outs["top3_high"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 467 |
|
| 468 |
if top3.empty:
|
| 469 |
+
sugg_mu = None; sugg_sigma_hist = None; holdings = empty_holdings_df()
|
|
|
|
| 470 |
else:
|
| 471 |
row = top3.iloc[min(idx, len(top3)-1)]
|
| 472 |
+
sugg_mu = float(row["mu_capm"]); sugg_sigma_hist = float(row["sigma_hist"])
|
|
|
|
| 473 |
holdings = _pick_to_holdings(row, outs["budget"])
|
| 474 |
|
|
|
|
| 475 |
img = plot_cml_hybrid(
|
| 476 |
outs["rf_ann"], outs["erp_ann"], outs["sigma_mkt"],
|
| 477 |
outs["sigma_hist"], outs["mu_capm"],
|
| 478 |
outs["mu_eff_same_sigma"], outs["sigma_eff_same_return"],
|
| 479 |
sugg_mu, sugg_sigma_hist
|
| 480 |
)
|
| 481 |
+
return (img, outs["info"], outs["uni_msg"], outs["pos_table"],
|
| 482 |
+
holdings, outs["csv_path"], outs["low_sum"], outs["med_sum"], outs["high_sum"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 483 |
|
| 484 |
# -------------- UI --------------
|
| 485 |
with gr.Blocks(title="Efficient Portfolio Advisor") as demo:
|
| 486 |
gr.Markdown(
|
| 487 |
"## Efficient Portfolio Advisor\n"
|
| 488 |
+
"Plot uses **x = historical σ** and **y = CAPM E[r] = rf + β·ERP**. "
|
| 489 |
+
"Efficient (same σ) and (same E[r]) market/bills points are shown. "
|
| 490 |
+
"Suggestions come from 1,000 mixes; embeddings + MMR add diversity."
|
|
|
|
| 491 |
)
|
|
|
|
| 492 |
with gr.Row():
|
| 493 |
with gr.Column(scale=1):
|
| 494 |
+
q = gr.Textbox(label="Search symbol"); search_note = gr.Markdown()
|
|
|
|
| 495 |
matches = gr.Dropdown(choices=[], label="Matches")
|
| 496 |
with gr.Row():
|
| 497 |
+
search_btn = gr.Button("Search"); add_btn = gr.Button("Add selected to portfolio")
|
|
|
|
|
|
|
| 498 |
gr.Markdown("### Portfolio positions (enter $ amounts; negatives allowed)")
|
| 499 |
+
table = gr.Dataframe(value=pd.DataFrame(columns=["ticker","amount_usd"]), interactive=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 500 |
horizon = gr.Number(label="Horizon in years (1–100)", value=HORIZON_YEARS, precision=0)
|
| 501 |
lookback = gr.Slider(1, 15, value=DEFAULT_LOOKBACK_YEARS, step=1, label="Lookback years")
|
| 502 |
use_emb = gr.Checkbox(value=True, label="Use finance embeddings + MMR for diverse picks")
|
|
|
|
| 503 |
gr.Markdown("### Suggestions")
|
| 504 |
with gr.Tabs():
|
| 505 |
with gr.Tab("Low"):
|
| 506 |
low_summary = gr.Dataframe(value=empty_holdings_df(), interactive=False, label="Top 3 (Low risk)")
|
| 507 |
+
pick_low = gr.Radio(choices=["1","2","3"], value="1", label="Select a pick in Low")
|
| 508 |
with gr.Tab("Medium"):
|
| 509 |
med_summary = gr.Dataframe(value=empty_holdings_df(), interactive=False, label="Top 3 (Medium risk)")
|
| 510 |
+
pick_med = gr.Radio(choices=["1","2","3"], value="1", label="Select a pick in Medium")
|
| 511 |
with gr.Tab("High"):
|
| 512 |
high_summary = gr.Dataframe(value=empty_holdings_df(), interactive=False, label="Top 3 (High risk)")
|
| 513 |
+
pick_high = gr.Radio(choices=["1","2","3"], value="1", label="Select a pick in High")
|
|
|
|
| 514 |
run_btn = gr.Button("Compute (build dataset & suggest)")
|
|
|
|
| 515 |
with gr.Column(scale=1):
|
| 516 |
plot = gr.Image(label="Capital Market Line (CAPM)", type="pil")
|
| 517 |
summary = gr.Markdown(label="Inputs & Results")
|
| 518 |
universe_msg = gr.Textbox(label="Universe status", interactive=False)
|
| 519 |
+
positions = gr.Dataframe(value=empty_positions_df(), interactive=False, label="Computed positions")
|
| 520 |
+
selected_table = gr.Dataframe(value=empty_holdings_df(), interactive=False,
|
| 521 |
+
label="Selected suggestion holdings (% / $)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 522 |
dl = gr.File(label="Generated dataset CSV", value=None, visible=True)
|
| 523 |
|
|
|
|
| 524 |
search_btn.click(fn=search_tickers_cb, inputs=q, outputs=[search_note, matches])
|
| 525 |
add_btn.click(fn=add_symbol, inputs=[matches, table], outputs=[table, search_note])
|
| 526 |
table.change(fn=lock_ticker_column, inputs=table, outputs=table)
|
| 527 |
horizon.change(fn=set_horizon, inputs=horizon, outputs=universe_msg)
|
| 528 |
|
|
|
|
| 529 |
run_btn.click(
|
| 530 |
fn=compute_and_render,
|
| 531 |
inputs=[lookback, table, use_emb, gr.State("Medium"), gr.State(1)],
|
| 532 |
outputs=[plot, summary, universe_msg, positions, selected_table, dl, low_summary, med_summary, high_summary]
|
| 533 |
)
|
|
|
|
|
|
|
| 534 |
pick_low.change(
|
| 535 |
fn=compute_and_render,
|
| 536 |
inputs=[lookback, table, use_emb, gr.State("Low"), pick_low],
|
|
|
|
| 547 |
outputs=[plot, summary, universe_msg, positions, selected_table, dl, low_summary, med_summary, high_summary]
|
| 548 |
)
|
| 549 |
|
|
|
|
| 550 |
RF_CODE = fred_series_for_horizon(HORIZON_YEARS)
|
| 551 |
RF_ANN = fetch_fred_yield_annual(RF_CODE)
|
| 552 |
|
| 553 |
if __name__ == "__main__":
|
|
|
|
| 554 |
demo.queue()
|
| 555 |
+
demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)), show_api=False, share=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|