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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, io, math, json, traceback, warnings
|
| 2 |
+
warnings.filterwarnings("ignore")
|
| 3 |
+
|
| 4 |
+
from typing import List, Tuple, Dict, Optional
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import matplotlib.pyplot as plt
|
| 9 |
+
from PIL import Image
|
| 10 |
+
import gradio as gr
|
| 11 |
+
import requests
|
| 12 |
+
import yfinance as yf
|
| 13 |
+
|
| 14 |
+
from sentence_transformers import SentenceTransformer, util as st_util
|
| 15 |
+
|
| 16 |
+
# =========================
|
| 17 |
+
# Config
|
| 18 |
+
# =========================
|
| 19 |
+
DATA_DIR = "data"
|
| 20 |
+
os.makedirs(DATA_DIR, exist_ok=True)
|
| 21 |
+
|
| 22 |
+
DEFAULT_LOOKBACK_YEARS = 5
|
| 23 |
+
MAX_TICKERS = 30
|
| 24 |
+
MARKET_TICKER = "VOO" # proxy for market portfolio
|
| 25 |
+
BILLS_TICKER = "BILLS" # synthetic cash / T-Bills bucket
|
| 26 |
+
|
| 27 |
+
EMBED_MODEL_NAME = "BAAI/bge-base-en-v1.5" # fully local, no API keys
|
| 28 |
+
|
| 29 |
+
POS_COLS = ["ticker", "amount_usd", "weight_exposure", "beta"]
|
| 30 |
+
SUG_COLS = ["ticker", "weight_%", "amount_$"]
|
| 31 |
+
EFF_COLS = ["asset", "weight_%", "amount_$"]
|
| 32 |
+
|
| 33 |
+
N_SYNTH = 1000 # synthetic dataset size
|
| 34 |
+
MMR_K = 40 # shortlist size before MMR
|
| 35 |
+
MMR_LAMBDA = 0.65 # similarity vs diversity tradeoff
|
| 36 |
+
|
| 37 |
+
DEBUG = True # if True, surface tracebacks in the UI summary when something fails
|
| 38 |
+
|
| 39 |
+
# ---------------- FRED mapping (risk-free source) ----------------
|
| 40 |
+
FRED_MAP = [
|
| 41 |
+
(1, "DGS1"),
|
| 42 |
+
(2, "DGS2"),
|
| 43 |
+
(3, "DGS3"),
|
| 44 |
+
(5, "DGS5"),
|
| 45 |
+
(7, "DGS7"),
|
| 46 |
+
(10, "DGS10"),
|
| 47 |
+
(20, "DGS20"),
|
| 48 |
+
(30, "DGS30"),
|
| 49 |
+
(100,"DGS30"),
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
def fred_series_for_horizon(years: float) -> str:
|
| 53 |
+
y = max(1.0, min(100.0, float(years)))
|
| 54 |
+
for cutoff, code in FRED_MAP:
|
| 55 |
+
if y <= cutoff:
|
| 56 |
+
return code
|
| 57 |
+
return "DGS30"
|
| 58 |
+
|
| 59 |
+
def fetch_fred_yield_annual(code: str) -> float:
|
| 60 |
+
url = f"https://fred.stlouisfed.org/graph/fredgraph.csv?id={code}"
|
| 61 |
+
try:
|
| 62 |
+
r = requests.get(url, timeout=10)
|
| 63 |
+
r.raise_for_status()
|
| 64 |
+
df = pd.read_csv(io.StringIO(r.text))
|
| 65 |
+
s = pd.to_numeric(df.iloc[:, 1], errors="coerce").dropna()
|
| 66 |
+
return float(s.iloc[-1] / 100.0) if len(s) else 0.03
|
| 67 |
+
except Exception:
|
| 68 |
+
return 0.03
|
| 69 |
+
|
| 70 |
+
# =========================
|
| 71 |
+
# Data helpers
|
| 72 |
+
# =========================
|
| 73 |
+
def _to_cols_close(df: pd.DataFrame, tickers: List[str]) -> pd.DataFrame:
|
| 74 |
+
"""
|
| 75 |
+
Coerce yfinance download to single-level columns of closes/adj closes.
|
| 76 |
+
Handles Series, single-level, and MultiIndex frames safely.
|
| 77 |
+
"""
|
| 78 |
+
if df is None or df.empty:
|
| 79 |
+
return pd.DataFrame()
|
| 80 |
+
|
| 81 |
+
# If Series (one ticker)
|
| 82 |
+
if isinstance(df, pd.Series):
|
| 83 |
+
df = df.to_frame("Close")
|
| 84 |
+
|
| 85 |
+
# MultiIndex columns: (ticker, field)
|
| 86 |
+
if isinstance(df.columns, pd.MultiIndex):
|
| 87 |
+
fields = df.columns.get_level_values(1).unique().tolist()
|
| 88 |
+
field = "Adj Close" if "Adj Close" in fields else ("Close" if "Close" in fields else fields[0])
|
| 89 |
+
out = {}
|
| 90 |
+
for t in dict.fromkeys(tickers):
|
| 91 |
+
col = (t, field)
|
| 92 |
+
if col in df.columns:
|
| 93 |
+
out[t] = pd.to_numeric(df[col], errors="coerce")
|
| 94 |
+
return pd.DataFrame(out)
|
| 95 |
+
|
| 96 |
+
# Single-level columns: try common names
|
| 97 |
+
if "Adj Close" in df.columns:
|
| 98 |
+
col = pd.to_numeric(df["Adj Close"], errors="coerce")
|
| 99 |
+
col.name = tickers[0] if tickers else "SINGLE"
|
| 100 |
+
return col.to_frame()
|
| 101 |
+
if "Close" in df.columns:
|
| 102 |
+
col = pd.to_numeric(df["Close"], errors="coerce")
|
| 103 |
+
col.name = tickers[0] if tickers else "SINGLE"
|
| 104 |
+
return col.to_frame()
|
| 105 |
+
|
| 106 |
+
# Fallback to first numeric column
|
| 107 |
+
num_cols = [c for c in df.columns if pd.api.types.is_numeric_dtype(df[c])]
|
| 108 |
+
if num_cols:
|
| 109 |
+
col = pd.to_numeric(df[num_cols[0]], errors="coerce")
|
| 110 |
+
col.name = tickers[0] if tickers else "SINGLE"
|
| 111 |
+
return col.to_frame()
|
| 112 |
+
|
| 113 |
+
return pd.DataFrame()
|
| 114 |
+
|
| 115 |
+
def fetch_prices_monthly(tickers: List[str], years: int) -> pd.DataFrame:
|
| 116 |
+
tickers = [t for t in dict.fromkeys(tickers) if t]
|
| 117 |
+
if not tickers:
|
| 118 |
+
return pd.DataFrame()
|
| 119 |
+
|
| 120 |
+
start = (pd.Timestamp.today(tz="UTC") - pd.DateOffset(years=int(years), days=7)).date()
|
| 121 |
+
end = pd.Timestamp.today(tz="UTC").date()
|
| 122 |
+
|
| 123 |
+
df_raw = yf.download(
|
| 124 |
+
tickers, start=start, end=end,
|
| 125 |
+
interval="1mo", auto_adjust=True, progress=False, group_by="ticker",
|
| 126 |
+
threads=True,
|
| 127 |
+
)
|
| 128 |
+
df = _to_cols_close(df_raw, tickers)
|
| 129 |
+
if df.empty:
|
| 130 |
+
return df
|
| 131 |
+
df = df.dropna(how="all").fillna(method="ffill")
|
| 132 |
+
# Keep only requested columns if present
|
| 133 |
+
keep = [t for t in tickers if t in df.columns]
|
| 134 |
+
if not keep and df.shape[1] == 1:
|
| 135 |
+
# Single column; rename if needed
|
| 136 |
+
df.columns = [tickers[0]]
|
| 137 |
+
keep = [tickers[0]]
|
| 138 |
+
return df[keep] if keep else pd.DataFrame()
|
| 139 |
+
|
| 140 |
+
def monthly_returns(prices: pd.DataFrame) -> pd.DataFrame:
|
| 141 |
+
if prices is None or prices.empty:
|
| 142 |
+
return pd.DataFrame()
|
| 143 |
+
return prices.pct_change().dropna(how="all")
|
| 144 |
+
|
| 145 |
+
def validate_tickers(symbols: List[str], years: int) -> List[str]:
|
| 146 |
+
"""Return subset of symbols that have monthly data."""
|
| 147 |
+
symbols = [s.strip().upper() for s in symbols if s and isinstance(s, str)]
|
| 148 |
+
if not symbols:
|
| 149 |
+
return []
|
| 150 |
+
base = [s for s in symbols if s != MARKET_TICKER]
|
| 151 |
+
px = fetch_prices_monthly(base + [MARKET_TICKER], years)
|
| 152 |
+
if px.empty:
|
| 153 |
+
return [s for s in symbols if s == MARKET_TICKER] # maybe only market survives
|
| 154 |
+
ok = [s for s in symbols if s in px.columns]
|
| 155 |
+
return ok
|
| 156 |
+
|
| 157 |
+
# =========================
|
| 158 |
+
# Moments & CAPM
|
| 159 |
+
# =========================
|
| 160 |
+
def annualize_mean(m): return np.asarray(m, dtype=float) * 12.0
|
| 161 |
+
def annualize_sigma(s): return np.asarray(s, dtype=float) * math.sqrt(12.0)
|
| 162 |
+
|
| 163 |
+
def get_aligned_monthly_returns(symbols: List[str], years: int) -> pd.DataFrame:
|
| 164 |
+
uniq = [c for c in dict.fromkeys(symbols)]
|
| 165 |
+
if MARKET_TICKER not in uniq:
|
| 166 |
+
uniq.append(MARKET_TICKER)
|
| 167 |
+
px = fetch_prices_monthly(uniq, years)
|
| 168 |
+
rets = monthly_returns(px)
|
| 169 |
+
if rets.empty:
|
| 170 |
+
return pd.DataFrame()
|
| 171 |
+
cols = [c for c in uniq if c in rets.columns]
|
| 172 |
+
R = rets[cols].dropna(how="any")
|
| 173 |
+
return R.loc[:, ~R.columns.duplicated()]
|
| 174 |
+
|
| 175 |
+
def estimate_all_moments_aligned(symbols: List[str], years: int, rf_ann: float):
|
| 176 |
+
R = get_aligned_monthly_returns(symbols + [MARKET_TICKER], years)
|
| 177 |
+
if R.empty or MARKET_TICKER not in R.columns or R.shape[0] < 3:
|
| 178 |
+
raise ValueError("Not enough aligned data to estimate moments.")
|
| 179 |
+
rf_m = rf_ann / 12.0
|
| 180 |
+
|
| 181 |
+
m = R[MARKET_TICKER]
|
| 182 |
+
if isinstance(m, pd.DataFrame):
|
| 183 |
+
m = m.iloc[:, 0].squeeze()
|
| 184 |
+
|
| 185 |
+
mu_m_ann = float(annualize_mean(m.mean()))
|
| 186 |
+
sigma_m_ann = float(annualize_sigma(m.std(ddof=1)))
|
| 187 |
+
erp_ann = float(mu_m_ann - rf_ann)
|
| 188 |
+
|
| 189 |
+
ex_m = m - rf_m
|
| 190 |
+
var_m = float(np.var(ex_m.values, ddof=1))
|
| 191 |
+
var_m = max(var_m, 1e-9)
|
| 192 |
+
|
| 193 |
+
betas: Dict[str, float] = {}
|
| 194 |
+
for s in [c for c in R.columns if c != MARKET_TICKER]:
|
| 195 |
+
ex_s = R[s] - rf_m
|
| 196 |
+
cov_sm = float(np.cov(ex_s.values, ex_m.values, ddof=1)[0, 1])
|
| 197 |
+
betas[s] = cov_sm / var_m
|
| 198 |
+
betas[MARKET_TICKER] = 1.0
|
| 199 |
+
|
| 200 |
+
asset_cols = [c for c in R.columns if c != MARKET_TICKER]
|
| 201 |
+
cov_m = np.cov(R[asset_cols].values.T, ddof=1) if asset_cols else np.zeros((0, 0))
|
| 202 |
+
covA = pd.DataFrame(cov_m * 12.0, index=asset_cols, columns=asset_cols)
|
| 203 |
+
|
| 204 |
+
return {"betas": betas, "cov_ann": covA, "erp_ann": erp_ann, "sigma_m_ann": sigma_m_ann}
|
| 205 |
+
|
| 206 |
+
def capm_er(beta: float, rf_ann: float, erp_ann: float) -> float:
|
| 207 |
+
return float(rf_ann + beta * erp_ann)
|
| 208 |
+
|
| 209 |
+
def portfolio_stats(weights: Dict[str, float],
|
| 210 |
+
cov_ann: pd.DataFrame,
|
| 211 |
+
betas: Dict[str, float],
|
| 212 |
+
rf_ann: float,
|
| 213 |
+
erp_ann: float) -> Tuple[float, float, float]:
|
| 214 |
+
tickers = list(weights.keys())
|
| 215 |
+
if not tickers:
|
| 216 |
+
return 0.0, rf_ann, 0.0
|
| 217 |
+
w = np.array([weights[t] for t in tickers], dtype=float)
|
| 218 |
+
gross = float(np.sum(np.abs(w)))
|
| 219 |
+
if gross <= 1e-12:
|
| 220 |
+
return 0.0, rf_ann, 0.0
|
| 221 |
+
w_expo = w / gross
|
| 222 |
+
beta_p = float(np.dot([betas.get(t, 0.0) for t in tickers], w_expo))
|
| 223 |
+
er_capm = capm_er(beta_p, rf_ann, erp_ann)
|
| 224 |
+
cov = cov_ann.reindex(index=tickers, columns=tickers).fillna(0.0).to_numpy()
|
| 225 |
+
sigma_p = math.sqrt(max(float(w_expo.T @ cov @ w_expo), 0.0))
|
| 226 |
+
return beta_p, er_capm, sigma_p
|
| 227 |
+
|
| 228 |
+
# =========================
|
| 229 |
+
# Efficient (CML) alternatives
|
| 230 |
+
# =========================
|
| 231 |
+
def efficient_same_sigma(sigma_target: float, rf_ann: float, erp_ann: float, sigma_mkt: float):
|
| 232 |
+
if sigma_mkt <= 1e-12:
|
| 233 |
+
return 0.0, 1.0, rf_ann
|
| 234 |
+
a = sigma_target / sigma_mkt
|
| 235 |
+
return a, 1.0 - a, rf_ann + a * erp_ann
|
| 236 |
+
|
| 237 |
+
def efficient_same_return(mu_target: float, rf_ann: float, erp_ann: float, sigma_mkt: float):
|
| 238 |
+
if abs(erp_ann) <= 1e-12:
|
| 239 |
+
return 0.0, 1.0, 0.0
|
| 240 |
+
a = (mu_target - rf_ann) / erp_ann
|
| 241 |
+
return a, 1.0 - a, abs(a) * sigma_mkt
|
| 242 |
+
|
| 243 |
+
# =========================
|
| 244 |
+
# Plot
|
| 245 |
+
# =========================
|
| 246 |
+
def _pct_arr(x):
|
| 247 |
+
return np.asarray(x, dtype=float) * 100.0
|
| 248 |
+
|
| 249 |
+
def plot_cml(rf_ann, erp_ann, sigma_mkt,
|
| 250 |
+
pt_sigma_hist, pt_mu_capm,
|
| 251 |
+
same_sigma_sigma, same_sigma_mu,
|
| 252 |
+
same_mu_sigma, same_mu_mu) -> Image.Image:
|
| 253 |
+
fig = plt.figure(figsize=(6.6, 4.4), dpi=130)
|
| 254 |
+
|
| 255 |
+
xmax = max(0.3, sigma_mkt * 2.0, pt_sigma_hist * 1.4, same_mu_sigma * 1.4, same_sigma_sigma * 1.4)
|
| 256 |
+
xs = np.linspace(0, xmax, 160)
|
| 257 |
+
slope = erp_ann / max(sigma_mkt, 1e-12)
|
| 258 |
+
cml = rf_ann + slope * xs
|
| 259 |
+
|
| 260 |
+
plt.plot(_pct_arr(xs), _pct_arr(cml), label="CML via VOO", linewidth=1.8)
|
| 261 |
+
plt.scatter([0.0], [_pct_arr(rf_ann)], label="Risk-free", zorder=5)
|
| 262 |
+
plt.scatter([_pct_arr(sigma_mkt)], [_pct_arr(rf_ann + erp_ann)], label="Market (VOO)", zorder=5)
|
| 263 |
+
plt.scatter([_pct_arr(pt_sigma_hist)], [_pct_arr(pt_mu_capm)], label="Your portfolio (CAPM)", zorder=6)
|
| 264 |
+
plt.scatter([_pct_arr(same_sigma_sigma)], [_pct_arr(same_sigma_mu)], label="Efficient: same σ", zorder=5)
|
| 265 |
+
plt.scatter([_pct_arr(same_mu_sigma)], [_pct_arr(same_mu_mu)], label="Efficient: same μ", zorder=5)
|
| 266 |
+
|
| 267 |
+
# Guides
|
| 268 |
+
plt.plot([_pct_arr(pt_sigma_hist), _pct_arr(same_sigma_sigma)],
|
| 269 |
+
[_pct_arr(pt_mu_capm), _pct_arr(same_sigma_mu)],
|
| 270 |
+
ls="--", lw=1.1, alpha=0.7, color="gray")
|
| 271 |
+
plt.plot([_pct_arr(pt_sigma_hist), _pct_arr(same_mu_sigma)],
|
| 272 |
+
[_pct_arr(pt_mu_capm), _pct_arr(same_mu_mu)],
|
| 273 |
+
ls="--", lw=1.1, alpha=0.7, color="gray")
|
| 274 |
+
|
| 275 |
+
plt.xlabel("σ (annual, %)")
|
| 276 |
+
plt.ylabel("E[return] (annual, %)")
|
| 277 |
+
plt.legend(loc="best", fontsize=8)
|
| 278 |
+
plt.tight_layout()
|
| 279 |
+
|
| 280 |
+
buf = io.BytesIO()
|
| 281 |
+
plt.savefig(buf, format="png")
|
| 282 |
+
plt.close(fig)
|
| 283 |
+
buf.seek(0)
|
| 284 |
+
return Image.open(buf)
|
| 285 |
+
|
| 286 |
+
# =========================
|
| 287 |
+
# Synthetic dataset (for recommendations)
|
| 288 |
+
# =========================
|
| 289 |
+
def dirichlet_signed(k, rng):
|
| 290 |
+
signs = rng.choice([-1.0, 1.0], size=k, p=[0.25, 0.75])
|
| 291 |
+
raw = rng.dirichlet(np.ones(k))
|
| 292 |
+
gross = 1.0 + float(rng.gamma(2.0, 0.5))
|
| 293 |
+
return gross * signs * raw
|
| 294 |
+
|
| 295 |
+
def build_synth_dataset(universe: List[str],
|
| 296 |
+
cov_ann: pd.DataFrame,
|
| 297 |
+
betas: Dict[str, float],
|
| 298 |
+
rf_ann: float, erp_ann: float,
|
| 299 |
+
n_rows: int = N_SYNTH,
|
| 300 |
+
seed: int = 123) -> pd.DataFrame:
|
| 301 |
+
rng = np.random.default_rng(seed)
|
| 302 |
+
U = [u for u in universe if u != MARKET_TICKER] + [MARKET_TICKER]
|
| 303 |
+
rows = []
|
| 304 |
+
if not U:
|
| 305 |
+
return pd.DataFrame()
|
| 306 |
+
for i in range(n_rows):
|
| 307 |
+
k = int(rng.integers(low=max(1, min(2, len(U))), high=min(8, len(U)) + 1))
|
| 308 |
+
picks = list(rng.choice(U, size=k, replace=False))
|
| 309 |
+
w = dirichlet_signed(k, rng)
|
| 310 |
+
gross = float(np.sum(np.abs(w)))
|
| 311 |
+
if gross <= 1e-12:
|
| 312 |
+
continue
|
| 313 |
+
w_expo = w / gross
|
| 314 |
+
weights = {picks[j]: float(w_expo[j]) for j in range(k)}
|
| 315 |
+
beta_i, er_capm_i, sigma_i = portfolio_stats(weights, cov_ann, betas, rf_ann, erp_ann)
|
| 316 |
+
rows.append({
|
| 317 |
+
"id": int(i),
|
| 318 |
+
"tickers": ",".join(picks),
|
| 319 |
+
"weights": ",".join(f"{x:.6f}" for x in w_expo),
|
| 320 |
+
"beta": float(beta_i),
|
| 321 |
+
"er_capm": float(er_capm_i),
|
| 322 |
+
"sigma": float(sigma_i),
|
| 323 |
+
})
|
| 324 |
+
return pd.DataFrame(rows)
|
| 325 |
+
|
| 326 |
+
# =========================
|
| 327 |
+
# Embeddings + MMR selection
|
| 328 |
+
# =========================
|
| 329 |
+
_embedder = None
|
| 330 |
+
def get_embedder():
|
| 331 |
+
global _embedder
|
| 332 |
+
if _embedder is None:
|
| 333 |
+
_embedder = SentenceTransformer(EMBED_MODEL_NAME)
|
| 334 |
+
return _embedder
|
| 335 |
+
|
| 336 |
+
def row_to_sentence(row: pd.Series) -> str:
|
| 337 |
+
try:
|
| 338 |
+
ts = row["tickers"].split(",")
|
| 339 |
+
ws = [float(x) for x in row["weights"].split(",")]
|
| 340 |
+
pairs = ", ".join([f"{ts[i]} {ws[i]:+.2f}" for i in range(min(len(ts), len(ws)))])
|
| 341 |
+
except Exception:
|
| 342 |
+
pairs = ""
|
| 343 |
+
return (f"portfolio with sigma {row['sigma']:.4f}, "
|
| 344 |
+
f"capm_return {row['er_capm']:.4f}, "
|
| 345 |
+
f"beta {row['beta']:.3f}, "
|
| 346 |
+
f"exposures {pairs}")
|
| 347 |
+
|
| 348 |
+
def mmr_select(query_emb, cand_embs, k: int = 3, lambda_param: float = MMR_LAMBDA) -> List[int]:
|
| 349 |
+
if cand_embs.shape[0] <= k:
|
| 350 |
+
return list(range(cand_embs.shape[0]))
|
| 351 |
+
sim_to_query = st_util.cos_sim(query_emb, cand_embs).cpu().numpy().reshape(-1)
|
| 352 |
+
chosen = []
|
| 353 |
+
candidate_indices = list(range(cand_embs.shape[0]))
|
| 354 |
+
first = int(np.argmax(sim_to_query))
|
| 355 |
+
chosen.append(first)
|
| 356 |
+
candidate_indices.remove(first)
|
| 357 |
+
while len(chosen) < k and candidate_indices:
|
| 358 |
+
max_score = -1e9
|
| 359 |
+
max_idx = candidate_indices[0]
|
| 360 |
+
# compute diversity term against already chosen
|
| 361 |
+
chosen_stack = cand_embs[chosen]
|
| 362 |
+
for idx in candidate_indices:
|
| 363 |
+
sim_q = sim_to_query[idx]
|
| 364 |
+
sim_d = float(st_util.cos_sim(cand_embs[idx], chosen_stack).max().cpu().numpy())
|
| 365 |
+
mmr_score = lambda_param * sim_q - (1.0 - lambda_param) * sim_d
|
| 366 |
+
if mmr_score > max_score:
|
| 367 |
+
max_score = mmr_score
|
| 368 |
+
max_idx = idx
|
| 369 |
+
chosen.append(max_idx)
|
| 370 |
+
candidate_indices.remove(max_idx)
|
| 371 |
+
return chosen
|
| 372 |
+
|
| 373 |
+
# =========================
|
| 374 |
+
# Yahoo symbol search (for UX)
|
| 375 |
+
# =========================
|
| 376 |
+
def yahoo_search(query: str):
|
| 377 |
+
if not query or len(query.strip()) == 0:
|
| 378 |
+
return []
|
| 379 |
+
url = "https://query1.finance.yahoo.com/v1/finance/search"
|
| 380 |
+
params = {"q": query.strip(), "quotesCount": 10, "newsCount": 0}
|
| 381 |
+
headers = {"User-Agent": "Mozilla/5.0"}
|
| 382 |
+
try:
|
| 383 |
+
r = requests.get(url, params=params, headers=headers, timeout=10)
|
| 384 |
+
r.raise_for_status()
|
| 385 |
+
data = r.json()
|
| 386 |
+
out = []
|
| 387 |
+
for q in data.get("quotes", []):
|
| 388 |
+
sym = q.get("symbol")
|
| 389 |
+
name = q.get("shortname") or q.get("longname") or ""
|
| 390 |
+
exch = q.get("exchDisp") or ""
|
| 391 |
+
if sym and sym.isascii():
|
| 392 |
+
out.append(f"{sym} | {name} | {exch}")
|
| 393 |
+
if not out:
|
| 394 |
+
out = [f"{query.strip().upper()} | typed symbol | n/a"]
|
| 395 |
+
return out[:10]
|
| 396 |
+
except Exception:
|
| 397 |
+
return [f"{query.strip().upper()} | typed symbol | n/a"]
|
| 398 |
+
|
| 399 |
+
_last_matches = []
|
| 400 |
+
|
| 401 |
+
# =========================
|
| 402 |
+
# Formatting helpers
|
| 403 |
+
# =========================
|
| 404 |
+
def fmt_pct(x: float) -> str:
|
| 405 |
+
try:
|
| 406 |
+
return f"{float(x)*100:.2f}%"
|
| 407 |
+
except Exception:
|
| 408 |
+
return "n/a"
|
| 409 |
+
|
| 410 |
+
def fmt_money(x: float) -> str:
|
| 411 |
+
try:
|
| 412 |
+
return f"${float(x):,.0f}"
|
| 413 |
+
except Exception:
|
| 414 |
+
return "n/a"
|
| 415 |
+
|
| 416 |
+
# =========================
|
| 417 |
+
# Gradio callbacks
|
| 418 |
+
# =========================
|
| 419 |
+
HORIZON_YEARS = 5.0
|
| 420 |
+
RF_CODE = fred_series_for_horizon(HORIZON_YEARS)
|
| 421 |
+
RF_ANN = fetch_fred_yield_annual(RF_CODE)
|
| 422 |
+
|
| 423 |
+
def do_search(query):
|
| 424 |
+
global _last_matches
|
| 425 |
+
_last_matches = yahoo_search(query)
|
| 426 |
+
note = "Select a symbol from Matches, then click Add."
|
| 427 |
+
return note, gr.update(choices=_last_matches, value=None)
|
| 428 |
+
|
| 429 |
+
def add_symbol(selection: str, table: pd.DataFrame):
|
| 430 |
+
if selection and " | " in selection:
|
| 431 |
+
symbol = selection.split(" | ")[0].strip().upper()
|
| 432 |
+
elif isinstance(selection, str) and selection.strip():
|
| 433 |
+
symbol = selection.strip().upper()
|
| 434 |
+
else:
|
| 435 |
+
return table, "Pick a row from Matches first."
|
| 436 |
+
|
| 437 |
+
current = []
|
| 438 |
+
if isinstance(table, pd.DataFrame) and len(table) > 0 and "ticker" in table.columns:
|
| 439 |
+
current = [str(x).upper() for x in table["ticker"].tolist() if str(x) != "nan"]
|
| 440 |
+
|
| 441 |
+
tickers = current if symbol in current else current + [symbol]
|
| 442 |
+
tickers = [t for t in tickers if t]
|
| 443 |
+
|
| 444 |
+
val = validate_tickers(tickers, years=DEFAULT_LOOKBACK_YEARS)
|
| 445 |
+
tickers = [t for t in tickers if t in val]
|
| 446 |
+
|
| 447 |
+
amt_map = {}
|
| 448 |
+
if isinstance(table, pd.DataFrame) and len(table) > 0:
|
| 449 |
+
for _, r in table.iterrows():
|
| 450 |
+
t = str(r.get("ticker", "")).upper()
|
| 451 |
+
if t in tickers:
|
| 452 |
+
amt_map[t] = float(pd.to_numeric(r.get("amount_usd", 0.0), errors="coerce") or 0.0)
|
| 453 |
+
|
| 454 |
+
new_table = pd.DataFrame({"ticker": tickers, "amount_usd": [amt_map.get(t, 0.0) for t in tickers]})
|
| 455 |
+
msg = f"Added {symbol}" if symbol in tickers else f"{symbol} not valid or no data"
|
| 456 |
+
if len(new_table) > MAX_TICKERS:
|
| 457 |
+
new_table = new_table.iloc[:MAX_TICKERS]
|
| 458 |
+
msg = f"Reached max of {MAX_TICKERS}"
|
| 459 |
+
return new_table, msg
|
| 460 |
+
|
| 461 |
+
def lock_ticker_column(tb: pd.DataFrame):
|
| 462 |
+
if tb is None or len(tb) == 0:
|
| 463 |
+
return pd.DataFrame(columns=["ticker", "amount_usd"])
|
| 464 |
+
tickers = [str(x).upper() for x in tb["ticker"].tolist()]
|
| 465 |
+
amounts = pd.to_numeric(tb["amount_usd"], errors="coerce").fillna(0.0).tolist()
|
| 466 |
+
val = validate_tickers(tickers, years=DEFAULT_LOOKBACK_YEARS)
|
| 467 |
+
tickers = [t for t in tickers if t in val]
|
| 468 |
+
amounts = amounts[:len(tickers)] + [0.0] * max(0, len(tickers) - len(amounts))
|
| 469 |
+
return pd.DataFrame({"ticker": tickers, "amount_usd": amounts})
|
| 470 |
+
|
| 471 |
+
def set_horizon(years: float):
|
| 472 |
+
y = max(1.0, min(100.0, float(years)))
|
| 473 |
+
code = fred_series_for_horizon(y)
|
| 474 |
+
rf = fetch_fred_yield_annual(code)
|
| 475 |
+
global HORIZON_YEARS, RF_CODE, RF_ANN
|
| 476 |
+
HORIZON_YEARS = y
|
| 477 |
+
RF_CODE = code
|
| 478 |
+
RF_ANN = rf
|
| 479 |
+
return f"Risk-free series {code}. Latest annual rate {rf:.2%}. Computations will use this."
|
| 480 |
+
|
| 481 |
+
def _table_from_weights(weights: Dict[str, float], gross_amt: float) -> pd.DataFrame:
|
| 482 |
+
items = []
|
| 483 |
+
for t, w in weights.items():
|
| 484 |
+
pct = float(w)
|
| 485 |
+
amt = float(w) * gross_amt
|
| 486 |
+
items.append({"ticker": t, "weight_%": round(pct * 100.0, 2), "amount_$": round(amt, 2)})
|
| 487 |
+
df = pd.DataFrame(items, columns=SUG_COLS)
|
| 488 |
+
if df.empty:
|
| 489 |
+
return pd.DataFrame(columns=SUG_COLS)
|
| 490 |
+
df["absw"] = df["weight_%"].abs()
|
| 491 |
+
df = df.sort_values("absw", ascending=False).drop(columns=["absw"])
|
| 492 |
+
return df
|
| 493 |
+
|
| 494 |
+
def _weights_dict_from_row(r: pd.Series) -> Dict[str, float]:
|
| 495 |
+
ts = [t.strip().upper() for t in str(r.get("tickers","")).split(",") if t]
|
| 496 |
+
ws = []
|
| 497 |
+
for x in str(r.get("weights","")).split(","):
|
| 498 |
+
try:
|
| 499 |
+
ws.append(float(x))
|
| 500 |
+
except Exception:
|
| 501 |
+
ws.append(0.0)
|
| 502 |
+
wmap = {}
|
| 503 |
+
for i in range(min(len(ts), len(ws))):
|
| 504 |
+
wmap[ts[i]] = ws[i]
|
| 505 |
+
gross = sum(abs(v) for v in wmap.values())
|
| 506 |
+
if gross <= 1e-12:
|
| 507 |
+
return {}
|
| 508 |
+
return {k: v / gross for k, v in wmap.items()}
|
| 509 |
+
|
| 510 |
+
def compute(lookback_years: int,
|
| 511 |
+
table: Optional[pd.DataFrame],
|
| 512 |
+
risk_bucket: str,
|
| 513 |
+
horizon_years: float):
|
| 514 |
+
|
| 515 |
+
try:
|
| 516 |
+
# --- sanitize input table
|
| 517 |
+
if table is None or len(table) == 0:
|
| 518 |
+
empty = pd.DataFrame(columns=POS_COLS)
|
| 519 |
+
emptyS = pd.DataFrame(columns=SUG_COLS)
|
| 520 |
+
emptyE = pd.DataFrame(columns=EFF_COLS)
|
| 521 |
+
return (None, "Add at least one ticker", "", empty,
|
| 522 |
+
emptyS, emptyS, emptyS, emptyE, emptyE, "[]", 1, "No suggestions yet.")
|
| 523 |
+
|
| 524 |
+
df = table.copy().dropna(how="all")
|
| 525 |
+
if df.empty or "ticker" not in df.columns or "amount_usd" not in df.columns:
|
| 526 |
+
empty = pd.DataFrame(columns=POS_COLS)
|
| 527 |
+
emptyS = pd.DataFrame(columns=SUG_COLS)
|
| 528 |
+
emptyE = pd.DataFrame(columns=EFF_COLS)
|
| 529 |
+
return (None, "Positions table is empty or malformed.", "", empty,
|
| 530 |
+
emptyS, emptyS, emptyS, emptyE, emptyE, "[]", 1, "No suggestions yet.")
|
| 531 |
+
|
| 532 |
+
df["ticker"] = df["ticker"].astype(str).str.upper().str.strip()
|
| 533 |
+
df["amount_usd"] = pd.to_numeric(df["amount_usd"], errors="coerce").fillna(0.0)
|
| 534 |
+
|
| 535 |
+
symbols = [t for t in df["ticker"].tolist() if t]
|
| 536 |
+
symbols = validate_tickers(symbols, lookback_years)
|
| 537 |
+
if len(symbols) == 0:
|
| 538 |
+
empty = pd.DataFrame(columns=POS_COLS)
|
| 539 |
+
emptyS = pd.DataFrame(columns=SUG_COLS)
|
| 540 |
+
emptyE = pd.DataFrame(columns=EFF_COLS)
|
| 541 |
+
return (None, "Could not validate any tickers", "Universe invalid",
|
| 542 |
+
empty, emptyS, emptyS, emptyS, emptyE, emptyE, "[]", 1, "No suggestions.")
|
| 543 |
+
|
| 544 |
+
# --- universe & amounts
|
| 545 |
+
universe = sorted(set([s for s in symbols if s != MARKET_TICKER] + [MARKET_TICKER]))
|
| 546 |
+
df = df[df["ticker"].isin(symbols)].copy()
|
| 547 |
+
amounts = {r["ticker"]: float(r["amount_usd"]) for _, r in df.iterrows()}
|
| 548 |
+
gross_amt = sum(abs(v) for v in amounts.values())
|
| 549 |
+
if gross_amt <= 1e-9:
|
| 550 |
+
empty = pd.DataFrame(columns=POS_COLS)
|
| 551 |
+
emptyS = pd.DataFrame(columns=SUG_COLS)
|
| 552 |
+
emptyE = pd.DataFrame(columns=EFF_COLS)
|
| 553 |
+
return (None, "All amounts are zero", "Universe ok",
|
| 554 |
+
empty, emptyS, emptyS, emptyS, emptyE, emptyE, "[]", 1, "No suggestions.")
|
| 555 |
+
|
| 556 |
+
weights = {k: v / gross_amt for k, v in amounts.items()}
|
| 557 |
+
|
| 558 |
+
# --- risk free & moments
|
| 559 |
+
rf_code = fred_series_for_horizon(horizon_years)
|
| 560 |
+
rf_ann = fetch_fred_yield_annual(rf_code)
|
| 561 |
+
moms = estimate_all_moments_aligned(universe, lookback_years, rf_ann)
|
| 562 |
+
betas, covA, erp_ann, sigma_mkt = moms["betas"], moms["cov_ann"], moms["erp_ann"], moms["sigma_m_ann"]
|
| 563 |
+
|
| 564 |
+
# --- portfolio stats (CAPM return + historical sigma)
|
| 565 |
+
beta_p, er_capm_p, sigma_p = portfolio_stats(weights, covA, betas, rf_ann, erp_ann)
|
| 566 |
+
|
| 567 |
+
# --- efficient alternatives on CML
|
| 568 |
+
a_sigma, b_sigma, mu_eff_sigma = efficient_same_sigma(sigma_p, rf_ann, erp_ann, sigma_mkt)
|
| 569 |
+
a_mu, b_mu, sigma_eff_mu = efficient_same_return(er_capm_p, rf_ann, erp_ann, sigma_mkt)
|
| 570 |
+
|
| 571 |
+
eff_same_sigma_tbl = _table_from_weights({MARKET_TICKER: a_sigma, BILLS_TICKER: b_sigma}, gross_amt)
|
| 572 |
+
eff_same_mu_tbl = _table_from_weights({MARKET_TICKER: a_mu, BILLS_TICKER: b_mu}, gross_amt)
|
| 573 |
+
|
| 574 |
+
# --- build synthetic dataset (based ONLY on this universe)
|
| 575 |
+
synth = build_synth_dataset(universe, covA, betas, rf_ann, erp_ann, n_rows=N_SYNTH, seed=777)
|
| 576 |
+
if synth.empty:
|
| 577 |
+
# fall back to trivial 3 variants of (market/bills) if universe too thin
|
| 578 |
+
fallback = []
|
| 579 |
+
for a in [0.2, 0.5, 0.8]:
|
| 580 |
+
w = {MARKET_TICKER: a, BILLS_TICKER: 1-a}
|
| 581 |
+
beta_i, er_capm_i, sigma_i = portfolio_stats(w, pd.DataFrame(), {MARKET_TICKER:1.0}, rf_ann, erp_ann)
|
| 582 |
+
fallback.append({"tickers": ",".join(w.keys()),
|
| 583 |
+
"weights": ",".join(f"{v:.6f}" for v in w.values()),
|
| 584 |
+
"beta": beta_i, "er_capm": er_capm_i, "sigma": sigma_i})
|
| 585 |
+
synth = pd.DataFrame(fallback)
|
| 586 |
+
|
| 587 |
+
# --- risk buckets by sigma (absolute +/- 5% around median)
|
| 588 |
+
median_sigma = float(synth["sigma"].median())
|
| 589 |
+
low_max = max(float(synth["sigma"].min()), median_sigma - 0.05)
|
| 590 |
+
high_min = median_sigma + 0.05
|
| 591 |
+
|
| 592 |
+
if risk_bucket == "Low":
|
| 593 |
+
cand_df = synth[synth["sigma"] <= low_max].copy()
|
| 594 |
+
elif risk_bucket == "High":
|
| 595 |
+
cand_df = synth[synth["sigma"] >= high_min].copy()
|
| 596 |
+
else:
|
| 597 |
+
cand_df = synth[(synth["sigma"] > low_max) & (synth["sigma"] < high_min)].copy()
|
| 598 |
+
if len(cand_df) == 0:
|
| 599 |
+
cand_df = synth.copy()
|
| 600 |
+
|
| 601 |
+
# --- embeddings + MMR for 3 diverse picks
|
| 602 |
+
embed = get_embedder()
|
| 603 |
+
cand_sentences = cand_df.apply(row_to_sentence, axis=1).tolist()
|
| 604 |
+
cur_pairs = ", ".join([f"{k}:{v:+.2f}" for k, v in sorted(weights.items())])
|
| 605 |
+
q_sentence = f"user portfolio ({risk_bucket} risk); capm_target {er_capm_p:.4f}; sigma_hist {sigma_p:.4f}; exposures {cur_pairs}"
|
| 606 |
+
|
| 607 |
+
cand_embs = embed.encode(cand_sentences, convert_to_tensor=True, normalize_embeddings=True, batch_size=64, show_progress_bar=False)
|
| 608 |
+
q_emb = embed.encode([q_sentence], convert_to_tensor=True, normalize_embeddings=True)[0]
|
| 609 |
+
|
| 610 |
+
sims = st_util.cos_sim(q_emb, cand_embs)[0]
|
| 611 |
+
top_idx = sims.topk(k=min(MMR_K, len(cand_df))).indices.cpu().numpy().tolist()
|
| 612 |
+
shortlist_embs = cand_embs[top_idx]
|
| 613 |
+
mmr_local = mmr_select(q_emb, shortlist_embs, k=3, lambda_param=MMR_LAMBDA)
|
| 614 |
+
chosen = [top_idx[i] for i in mmr_local]
|
| 615 |
+
recs = cand_df.iloc[chosen].reset_index(drop=True)
|
| 616 |
+
|
| 617 |
+
# --- suggestion tables for 3 picks
|
| 618 |
+
sugg_tables = []
|
| 619 |
+
sugg_meta = []
|
| 620 |
+
for _, r in recs.iterrows():
|
| 621 |
+
wmap = _weights_dict_from_row(r)
|
| 622 |
+
sugg_tables.append(_table_from_weights(wmap, gross_amt))
|
| 623 |
+
sugg_meta.append({"er_capm": float(r["er_capm"]), "sigma": float(r["sigma"]), "beta": float(r["beta"])})
|
| 624 |
+
|
| 625 |
+
# --- plot
|
| 626 |
+
img = plot_cml(
|
| 627 |
+
rf_ann, erp_ann, sigma_mkt,
|
| 628 |
+
sigma_p, er_capm_p,
|
| 629 |
+
same_sigma_sigma=sigma_p, same_sigma_mu=mu_eff_sigma,
|
| 630 |
+
same_mu_sigma=sigma_eff_mu, same_mu_mu=er_capm_p
|
| 631 |
+
)
|
| 632 |
+
|
| 633 |
+
# --- positions table (computed)
|
| 634 |
+
rows = []
|
| 635 |
+
for t in universe:
|
| 636 |
+
if t == MARKET_TICKER:
|
| 637 |
+
continue
|
| 638 |
+
rows.append({
|
| 639 |
+
"ticker": t,
|
| 640 |
+
"amount_usd": round(amounts.get(t, 0.0), 2),
|
| 641 |
+
"weight_exposure": round(weights.get(t, 0.0), 6),
|
| 642 |
+
"beta": round(betas.get(t, np.nan), 4) if t != MARKET_TICKER else 1.0
|
| 643 |
+
})
|
| 644 |
+
pos_table = pd.DataFrame(rows, columns=POS_COLS)
|
| 645 |
+
|
| 646 |
+
# --- info summary
|
| 647 |
+
info_lines = []
|
| 648 |
+
info_lines.append("### Inputs")
|
| 649 |
+
info_lines.append(f"- Lookback years **{int(lookback_years)}**")
|
| 650 |
+
info_lines.append(f"- Horizon years **{int(round(horizon_years))}**")
|
| 651 |
+
info_lines.append(f"- Risk-free **{fmt_pct(rf_ann)}** from **{rf_code}**")
|
| 652 |
+
info_lines.append(f"- Market ERP **{fmt_pct(erp_ann)}**")
|
| 653 |
+
info_lines.append(f"- Market σ **{fmt_pct(sigma_mkt)}**")
|
| 654 |
+
info_lines.append("")
|
| 655 |
+
info_lines.append("### Your portfolio (plotted as CAPM return, historical σ)")
|
| 656 |
+
info_lines.append(f"- Beta **{beta_p:.2f}**")
|
| 657 |
+
info_lines.append(f"- σ (historical) **{fmt_pct(sigma_p)}**")
|
| 658 |
+
info_lines.append(f"- E[return] (CAPM / SML) **{fmt_pct(er_capm_p)}**")
|
| 659 |
+
info_lines.append("")
|
| 660 |
+
info_lines.append("### Efficient alternatives on CML")
|
| 661 |
+
info_lines.append(f"- Same σ → Market **{a_sigma:.2f}**, Bills **{b_sigma:.2f}**, Return **{fmt_pct(mu_eff_sigma)}**")
|
| 662 |
+
info_lines.append(f"- Same μ → Market **{a_mu:.2f}**, Bills **{b_mu:.2f}**, σ **{fmt_pct(sigma_eff_mu)}**")
|
| 663 |
+
info_lines.append("")
|
| 664 |
+
info_lines.append(f"### Dataset-based suggestions (risk: **{risk_bucket}**)")
|
| 665 |
+
info_lines.append("Use the selector to flip between **Pick #1 / #2 / #3**. Table shows % exposure and $ amounts.")
|
| 666 |
+
|
| 667 |
+
# pad to exactly 3 tables for outputs
|
| 668 |
+
while len(sugg_tables) < 3:
|
| 669 |
+
sugg_tables.append(pd.DataFrame(columns=SUG_COLS))
|
| 670 |
+
|
| 671 |
+
pick_idx_default = 1
|
| 672 |
+
pick_msg_default = (f"Pick #1 — E[μ] {fmt_pct(sugg_meta[0]['er_capm'])}, "
|
| 673 |
+
f"σ {fmt_pct(sugg_meta[0]['sigma'])}, β {sugg_meta[0]['beta']:.2f}") if sugg_meta else "No suggestion."
|
| 674 |
+
|
| 675 |
+
return (img,
|
| 676 |
+
"\n".join(info_lines),
|
| 677 |
+
f"Universe set to {', '.join(universe)}",
|
| 678 |
+
pos_table,
|
| 679 |
+
sugg_tables[0], sugg_tables[1], sugg_tables[2],
|
| 680 |
+
eff_same_sigma_tbl, eff_same_mu_tbl,
|
| 681 |
+
json.dumps(sugg_meta), pick_idx_default, pick_msg_default)
|
| 682 |
+
|
| 683 |
+
except Exception as e:
|
| 684 |
+
empty = pd.DataFrame(columns=POS_COLS)
|
| 685 |
+
emptyS = pd.DataFrame(columns=SUG_COLS)
|
| 686 |
+
emptyE = pd.DataFrame(columns=EFF_COLS)
|
| 687 |
+
msg = f"⚠️ Compute failed: {e}"
|
| 688 |
+
if DEBUG:
|
| 689 |
+
msg += "\n\n```\n" + traceback.format_exc() + "\n```"
|
| 690 |
+
return (None, msg, "Error", empty, emptyS, emptyS, emptyS, emptyE, emptyE, "[]", 1, "No suggestions.")
|
| 691 |
+
|
| 692 |
+
def on_pick_change(idx: int, meta_json: str):
|
| 693 |
+
try:
|
| 694 |
+
data = json.loads(meta_json)
|
| 695 |
+
except Exception:
|
| 696 |
+
data = []
|
| 697 |
+
if not data:
|
| 698 |
+
return "No suggestion."
|
| 699 |
+
i = int(idx) - 1
|
| 700 |
+
i = max(0, min(i, len(data)-1))
|
| 701 |
+
s = data[i]
|
| 702 |
+
return f"Pick #{i+1} — E[μ] {fmt_pct(s['er_capm'])}, σ {fmt_pct(s['sigma'])}, β {s['beta']:.2f}"
|
| 703 |
+
|
| 704 |
+
# =========================
|
| 705 |
+
# UI
|
| 706 |
+
# =========================
|
| 707 |
+
with gr.Blocks(title="Efficient Portfolio Advisor", css="#small-note {font-size: 12px; color:#666;}") as demo:
|
| 708 |
+
|
| 709 |
+
gr.Markdown("## Efficient Portfolio Advisor\n"
|
| 710 |
+
"Search symbols, enter **$ amounts**, set your **horizon**. "
|
| 711 |
+
"The plot shows your **CAPM expected return** vs **historical σ**, alongside the **CML**. "
|
| 712 |
+
"Recommendations are generated from a **synthetic dataset (1000 portfolios)** and ranked with **local embeddings (BGE-base)** for relevance + diversity.")
|
| 713 |
+
|
| 714 |
+
with gr.Tab("Build Portfolio"):
|
| 715 |
+
with gr.Row():
|
| 716 |
+
with gr.Column(scale=1):
|
| 717 |
+
q = gr.Textbox(label="Search symbol")
|
| 718 |
+
search_note = gr.Markdown(elem_id="small-note")
|
| 719 |
+
matches = gr.Dropdown(choices=[], label="Matches", value=None)
|
| 720 |
+
search_btn = gr.Button("Search")
|
| 721 |
+
add_btn = gr.Button("Add selected to portfolio")
|
| 722 |
+
|
| 723 |
+
gr.Markdown("### Positions (enter dollars; negatives allowed for shorts)")
|
| 724 |
+
table = gr.Dataframe(
|
| 725 |
+
headers=["ticker", "amount_usd"],
|
| 726 |
+
datatype=["str", "number"],
|
| 727 |
+
row_count=0,
|
| 728 |
+
col_count=(2, "fixed"),
|
| 729 |
+
wrap=True
|
| 730 |
+
)
|
| 731 |
+
|
| 732 |
+
with gr.Column(scale=1):
|
| 733 |
+
horizon = gr.Slider(1, 30, value=DEFAULT_LOOKBACK_YEARS, step=1, label="Investment horizon (years)")
|
| 734 |
+
lookback = gr.Slider(1, 10, value=DEFAULT_LOOKBACK_YEARS, step=1, label="Lookback (years) for β and σ")
|
| 735 |
+
risk_bucket = gr.Radio(["Low", "Medium", "High"], value="Medium", label="Recommendation risk level")
|
| 736 |
+
run_btn = gr.Button("Compute")
|
| 737 |
+
|
| 738 |
+
rf_msg = gr.Textbox(label="Risk-free source / status", interactive=False)
|
| 739 |
+
search_btn.click(fn=do_search, inputs=q, outputs=[search_note, matches])
|
| 740 |
+
add_btn.click(fn=add_symbol, inputs=[matches, table], outputs=[table, search_note])
|
| 741 |
+
table.change(fn=lock_ticker_column, inputs=table, outputs=table)
|
| 742 |
+
horizon.change(fn=set_horizon, inputs=horizon, outputs=[rf_msg]) # FIX: single output
|
| 743 |
+
|
| 744 |
+
with gr.Tab("Results"):
|
| 745 |
+
with gr.Row():
|
| 746 |
+
with gr.Column(scale=1):
|
| 747 |
+
plot = gr.Image(label="Capital Market Line", type="pil")
|
| 748 |
+
summary = gr.Markdown(label="Summary")
|
| 749 |
+
universe_msg = gr.Textbox(label="Universe status", interactive=False)
|
| 750 |
+
|
| 751 |
+
with gr.Column(scale=1):
|
| 752 |
+
positions = gr.Dataframe(
|
| 753 |
+
label="Computed positions",
|
| 754 |
+
headers=POS_COLS,
|
| 755 |
+
datatype=["str", "number", "number", "number"],
|
| 756 |
+
col_count=(len(POS_COLS), "fixed"),
|
| 757 |
+
interactive=False
|
| 758 |
+
)
|
| 759 |
+
|
| 760 |
+
gr.Markdown("### Recommendations (always from embeddings)")
|
| 761 |
+
with gr.Row():
|
| 762 |
+
sugg1 = gr.Dataframe(label="Pick #1", interactive=False)
|
| 763 |
+
sugg2 = gr.Dataframe(label="Pick #2", interactive=False)
|
| 764 |
+
sugg3 = gr.Dataframe(label="Pick #3", interactive=False)
|
| 765 |
+
|
| 766 |
+
with gr.Row():
|
| 767 |
+
pick_idx = gr.Slider(1, 3, value=1, step=1, label="Carousel: show Pick #")
|
| 768 |
+
pick_meta = gr.Textbox(value="[]", visible=False)
|
| 769 |
+
pick_msg = gr.Markdown("")
|
| 770 |
+
|
| 771 |
+
gr.Markdown("### Efficient alternatives on the CML")
|
| 772 |
+
eff_same_sigma_tbl = gr.Dataframe(label="Efficient: Same σ", interactive=False)
|
| 773 |
+
eff_same_mu_tbl = gr.Dataframe(label="Efficient: Same μ", interactive=False)
|
| 774 |
+
|
| 775 |
+
run_btn.click(
|
| 776 |
+
fn=compute,
|
| 777 |
+
inputs=[lookback, table, risk_bucket, horizon],
|
| 778 |
+
outputs=[
|
| 779 |
+
plot, summary, universe_msg, positions,
|
| 780 |
+
sugg1, sugg2, sugg3,
|
| 781 |
+
eff_same_sigma_tbl, eff_same_mu_tbl,
|
| 782 |
+
pick_meta, pick_idx, pick_msg
|
| 783 |
+
]
|
| 784 |
+
)
|
| 785 |
+
pick_idx.change(fn=on_pick_change, inputs=[pick_idx, pick_meta], outputs=pick_msg)
|
| 786 |
+
|
| 787 |
+
with gr.Tab("About"):
|
| 788 |
+
gr.Markdown(
|
| 789 |
+
"### Modality & Model\n"
|
| 790 |
+
"- **Modality**: Text (portfolio → text descriptions) powering **embeddings**\n"
|
| 791 |
+
"- **Embedding model**: `BAAI/bge-base-en-v1.5` (local, downloaded once; no API)\n\n"
|
| 792 |
+
"### Use case\n"
|
| 793 |
+
"Given a portfolio, we build a synthetic dataset of 1,000 alternative mixes **using the same tickers**, "
|
| 794 |
+
"compute each mix’s **CAPM return, σ, and β**, and rank candidates with embeddings to return **3 diverse, relevant suggestions** "
|
| 795 |
+
"for **Low / Medium / High** risk.\n\n"
|
| 796 |
+
"### Theory links\n"
|
| 797 |
+
"- Portfolio expected return in the plot uses **CAPM (SML)**, while σ is historical.\n"
|
| 798 |
+
"- The **CML** and the two **efficient alternatives** (same σ, same μ) use a mix of **Market (VOO)** and **Bills**."
|
| 799 |
+
)
|
| 800 |
+
|
| 801 |
+
if __name__ == "__main__":
|
| 802 |
+
demo.launch()
|