math-backend / report_builders /html_tables.py
engineportf's picture
Upload folder using huggingface_hub
558db1e verified
Raw
History Blame Contribute Delete
3.12 kB
def build_main_table(weights, current_weights, exp_rets, prices, betas, spread_map, vol, capital, has_curr, curr):
table_rows = ""
all_tickers_tbl = sorted(set(weights[abs(weights)>0.005].index) | (set(current_weights[abs(current_weights)>0.005].index) if has_curr and current_weights is not None else set()))
for t in all_tickers_tbl:
if t != 'CASH' and (t not in exp_rets.index or t not in prices): continue
w_tgt = float(weights.get(t, 0))
w_cur = float(current_weights.get(t, 0)) if (has_curr and current_weights is not None) else 0.0
if abs(w_tgt) < 0.005 and abs(w_cur) < 0.005: continue
amt = capital * w_tgt
if t == 'CASH':
# RFR is handled outside if needed, or passed as 0 for CASH in table
price = 1.0; sh = amt; er = 0.0; b = 0.0; sp = 0.0; vol_val = 0.0
else:
price = prices.get(t, 0); sh = round(amt / price, 4) if price > 0 else 0
er = float(exp_rets.get(t, 0)); b = float(betas.get(t, 1)); sp = spread_map.get(t, 0.0008); vol_val = float(vol.get(t, 0))
dir_bg = "#f85149" if w_tgt < 0 else "#3fb950"
ret_col = "#3fb950" if er >= 0 else "#f85149"
sp_col = "#f85149" if sp > 0.001 else ("#e3b341" if sp > 0.0004 else "#3fb950")
pct_width = min(abs(w_tgt)*100, 100)
bg_color = "rgba(63, 185, 80, 0.2)" if w_tgt >= 0 else "rgba(248, 81, 73, 0.2)"
w_html = (f'<div style="position:relative; width:100%; min-width:80px; padding:2px 0;">'
f'<div style="position:absolute; left:0; top:0; bottom:0; width:{pct_width}%; background:{bg_color}; border-radius:3px; z-index:0;"></div>'
f'<div style="position:relative; z-index:1; padding-left:5px; font-weight:600;">{w_tgt*100:.1f}%</div></div>')
if has_curr and abs(w_tgt - w_cur) > 0.004:
chg = w_tgt - w_cur
chg_col = "#3fb950" if chg > 0 else "#f85149"
w_html = (f'<div style="position:relative; width:100%; min-width:140px; padding:2px 0;">'
f'<div style="position:absolute; left:0; top:0; bottom:0; width:{pct_width}%; background:{bg_color}; border-radius:3px; z-index:0;"></div>'
f'<div style="position:relative; z-index:1; padding-left:5px;">'
f'<span style="color:#8b949e;text-decoration:line-through;font-size:.75rem">{w_cur*100:.1f}%</span> '
f'<span style="color:{chg_col}; font-weight:600;">&#10132; {w_tgt*100:.1f}%</span>'
f'</div></div>')
table_rows += (f"<tr><td><strong>{t}</strong> <span style='background:{dir_bg};color:#0d1117;border-radius:3px;padding:1px 4px;font-size:.68rem;font-weight:700'>{'SHORT' if w_tgt<0 else 'LONG'}</span></td>"
f"<td>{w_html}</td><td>{curr}{amt:,.0f}</td><td>{curr}{price:.2f}</td><td>{sh:.4f}</td><td>{b:.2f}</td>"
f"<td style='color:{ret_col}'>{er*100:+.1f}%</td><td>{vol_val*100:.1f}%</td><td style='color:{sp_col}'>{sp*10000:.1f}bp</td></tr>\n")
return table_rows