phase-10.5: market screener ui enhancements

This commit is contained in:
Kazuma
2026-06-09 01:21:02 -04:00
parent 7bc242911e
commit fbadd7fb6e
45 changed files with 3054 additions and 539 deletions
+47
View File
@@ -0,0 +1,47 @@
import type { AuthResponse } from '$lib/types.js';
import { authStore } from '$lib/stores/auth.store.svelte.js';
const BASE = import.meta.env.VITE_API_URL ?? 'http://localhost:3000';
/**
* fetch() wrapper that automatically attaches the JWT Bearer token.
* Use this for all API calls that require authentication.
*/
export function authFetch(url: string, init: RequestInit = {}): Promise<Response> {
const token = authStore.token;
const headers = new Headers(init.headers);
if (!headers.has('Content-Type')) headers.set('Content-Type', 'application/json');
if (token) headers.set('Authorization', `Bearer ${token}`);
return fetch(url, { ...init, headers });
}
export async function login(email: string, password: string): Promise<AuthResponse> {
const res = await fetch(`${BASE}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
if (!res.ok) {
const { error } = await res.json().catch(() => ({ error: 'Login failed' }));
throw new Error(error ?? 'Login failed');
}
return res.json() as Promise<AuthResponse>;
}
export async function register(
email: string,
password: string,
role: 'trader' | 'viewer' = 'viewer',
inviteCode = '',
): Promise<AuthResponse> {
const res = await fetch(`${BASE}/auth/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password, role, inviteCode }),
});
if (!res.ok) {
const { error } = await res.json().catch(() => ({ error: 'Registration failed' }));
throw new Error(error ?? 'Registration failed');
}
return res.json() as Promise<AuthResponse>;
}
+3 -3
View File
@@ -1,4 +1,5 @@
import type { MarketCall, CalendarEvent, ScreenerResult } from '$lib/types.js';
import { authFetch } from './auth.js';
const BASE = '/api';
@@ -21,9 +22,8 @@ export async function createCall(payload: {
tickers: string[];
date?: string;
}): Promise<MarketCall> {
const res = await fetch(`${BASE}/calls`, {
const res = await authFetch(`${BASE}/calls`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
if (!res.ok) throw new Error(await res.text());
@@ -31,7 +31,7 @@ export async function createCall(payload: {
}
export async function deleteCall(id: string): Promise<{ ok: boolean }> {
const res = await fetch(`${BASE}/calls/${id}`, { method: 'DELETE' });
const res = await authFetch(`${BASE}/calls/${id}`, { method: 'DELETE' });
if (!res.ok) throw new Error(await res.text());
return res.json();
}
+5 -7
View File
@@ -1,4 +1,5 @@
import type { MarketContext, PortfolioHolding, PortfolioAdvice } from '$lib/types.js';
import { authFetch } from './auth.js';
const BASE = '/api';
@@ -9,7 +10,7 @@ export async function fetchPortfolio(): Promise<{
netWorth: number | null;
error?: string;
}> {
const res = await fetch(`${BASE}/finance/portfolio`);
const res = await authFetch(`${BASE}/finance/portfolio`);
if (!res.ok) throw new Error(await res.text());
return res.json();
}
@@ -17,9 +18,8 @@ export async function fetchPortfolio(): Promise<{
export async function addHolding(
holding: PortfolioHolding,
): Promise<{ holdings: PortfolioHolding[] }> {
const res = await fetch(`${BASE}/finance/holdings`, {
const res = await authFetch(`${BASE}/finance/holdings`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(holding),
});
if (!res.ok) throw new Error(await res.text());
@@ -27,15 +27,13 @@ export async function addHolding(
}
export async function removeHolding(ticker: string): Promise<{ holdings: PortfolioHolding[] }> {
const res = await fetch(`${BASE}/finance/holdings/${ticker}`, {
method: 'DELETE',
});
const res = await authFetch(`${BASE}/finance/holdings/${ticker}`, { method: 'DELETE' });
if (!res.ok) throw new Error(await res.text());
return res.json();
}
export async function fetchMarketContext(): Promise<MarketContext> {
const res = await fetch(`${BASE}/finance/market-context`);
const res = await authFetch(`${BASE}/finance/market-context`);
if (!res.ok) throw new Error(await res.text());
return res.json();
}
+1
View File
@@ -5,3 +5,4 @@
export { screenTickers, fetchCatalysts, analyzeTickers } from './screener.js';
export { fetchPortfolio, addHolding, removeHolding, fetchMarketContext } from './finance.js';
export { fetchCalls, fetchCall, createCall, deleteCall, fetchCallsCalendar } from './calls.js';
export { login, register, authFetch } from './auth.js';
@@ -29,7 +29,7 @@
<div class="accounts-two-col">
<section class="accounts-section">
<h2>Accounts</h2>
<table>
<table class="accounts-table">
<thead><tr><th>Account</th><th>Type</th><th>Institution</th><th class="right">Balance</th></tr></thead>
<tbody>
{#each pf.accounts as a}
@@ -46,7 +46,7 @@
<section class="accounts-section">
<h2>Spending — Last 30 Days</h2>
<table>
<table class="accounts-table">
<thead><tr><th>Category</th><th class="right">Amount</th><th class="right">%</th><th>Share</th></tr></thead>
<tbody>
{#each pf.categoryBreakdown.slice(0, 10) as c}
@@ -118,7 +118,7 @@
<!-- Holdings table -->
<section class="advice-section">
<h2>Holdings — Hold / Sell / Add Advice</h2>
<table>
<table class="advice-table">
<thead>
<tr>
<th class="sortable" onclick={() => toggleSort('ticker')}>Ticker {sortIcon('ticker')}</th>
@@ -168,7 +168,7 @@
<td class="num {glClass(a.gainLossPct)}">{a.gainLossPct != null ? a.gainLossPct + '%' : '—'}</td>
<td>{#if a.signal}<SignalBadge signal={a.signal} />{:else}<span class="gray"></span>{/if}</td>
<td class={advClass(a.advice)}>{a.advice}</td>
<td class="reason">{a.reason}</td>
<td class="reason col-reason">{a.reason}</td>
<td class="advice-row-actions">
{#if isEditing}
<button class="btn-save-inline" onclick={saveEdit} disabled={saving}>{saving ? '…' : '✓'}</button>
+437 -100
View File
@@ -1,7 +1,5 @@
<script lang="ts">
import { sigOrd, sorted } from '$lib/utils.js';
import VerdictPill from '$lib/components/shared/VerdictPill.svelte';
import SignalBadge from '$lib/components/shared/SignalBadge.svelte';
import Spinner from '$lib/components/shared/Spinner.svelte';
import type { AssetType, AssetResult } from '$lib/types.js';
@@ -17,22 +15,172 @@
onAnalyze: () => void;
} = $props();
// Mode state is self-contained — each table independently tracks inflated vs fundamental
let mode = $state('inflated');
let mode = $state('inflated');
let expanded = $state<string | null>(null);
let sortCol = $state<string | null>(null);
let sortAsc = $state(true);
let filterTicker = $state('');
let filterSignal = $state('');
let filterStyle = $state('');
let filterCap = $state('');
let filterPriceMin = $state('');
let filterPriceMax = $state('');
let filterScoreMin = $state('');
let filterFlags = $state(false);
const STYLE_OPTIONS = ['High Growth', 'Growth', 'Value', 'Stable', 'Turnaround', 'Declining'];
const CAP_OPTIONS = ['Mega Cap', 'Large Cap', 'Mid Cap', 'Small Cap', 'Micro Cap'];
function hasFilter() {
return !!(filterTicker || filterSignal || filterStyle || filterCap || filterPriceMin || filterPriceMax || filterScoreMin || filterFlags);
}
function clearFilters() {
filterTicker = ''; filterSignal = ''; filterStyle = ''; filterCap = '';
filterPriceMin = ''; filterPriceMax = ''; filterScoreMin = ''; filterFlags = false;
}
function filteredRows(rows: AssetResult[]): AssetResult[] {
let out = rows;
if (filterTicker.trim()) {
const q = filterTicker.trim().toUpperCase();
out = out.filter(r => r.asset.ticker.includes(q));
}
if (filterSignal) {
out = out.filter(r => r.signal === filterSignal);
}
if (filterStyle) {
out = out.filter(r => (r.asset.displayMetrics?.['Style'] ?? '') === filterStyle);
}
if (filterCap) {
out = out.filter(r => (r.asset.displayMetrics?.['Cap Tier'] ?? '') === filterCap);
}
if (filterPriceMin !== '') {
const min = parseFloat(filterPriceMin);
out = out.filter(r => numVal(r.asset.displayMetrics?.['Price']) >= min);
}
if (filterPriceMax !== '') {
const max = parseFloat(filterPriceMax);
out = out.filter(r => numVal(r.asset.displayMetrics?.['Price']) <= max);
}
if (filterScoreMin !== '' && filterScoreMin !== null) {
const min = Number(filterScoreMin);
if (!isNaN(min)) {
out = out.filter(r => {
const v = r[mode as 'inflated' | 'fundamental'];
const raw = v.scoreSummary ?? '';
// Gate-failed rows have no numeric score — treat as 0
const match = raw.match(/Score:\s*(\d+)/);
const s = match ? parseInt(match[1], 10) : 0;
return s >= min;
});
}
}
if (filterFlags) {
// Hide gate-failed (rejected) rows — use scoreSummary as it's always serialized
out = out.filter(r => {
const v = r[mode as 'inflated' | 'fundamental'];
return !(v.scoreSummary ?? '').startsWith('Gate failed');
});
}
return out;
}
function toggleExpand(ticker: string) {
expanded = expanded === ticker ? null : ticker;
}
function setSort(col: string) {
if (sortCol === col) {
sortAsc = !sortAsc;
} else {
sortCol = col;
sortAsc = col === 'ticker'; // text cols default asc; number cols default desc
}
expanded = null; // close any open row when re-sorting
}
function sortIcon(col: string): string {
if (sortCol !== col) return '⇅';
return sortAsc ? '↑' : '↓';
}
function numVal(s: string | number | undefined | null): number {
if (s == null || s === '—') return -Infinity;
return parseFloat(String(s).replace(/[%$,x]/g, '')) || 0;
}
function sortedRows(rows: AssetResult[]): AssetResult[] {
const base = filteredRows(rows);
if (!sortCol) return sorted(base);
const col = sortCol;
const asc = sortAsc;
return [...base].sort((a, b) => {
const ma = a.asset.displayMetrics ?? {};
const mb = b.asset.displayMetrics ?? {};
const va = a[mode as 'inflated' | 'fundamental'];
const vb = b[mode as 'inflated' | 'fundamental'];
let av: number | string = 0;
let bv: number | string = 0;
if (col === 'ticker') {
av = a.asset.ticker; bv = b.asset.ticker;
} else if (col === 'price') {
av = numVal(ma['Price']); bv = numVal(mb['Price']);
} else if (col === 'signal') {
av = sigOrd(a.signal); bv = sigOrd(b.signal);
} else if (col === 'score') {
av = numVal(va.scoreSummary); bv = numVal(vb.scoreSummary);
} else if (col === 'cap') {
const capOrder: Record<string, number> = { 'Mega Cap': 5, 'Large Cap': 4, 'Mid Cap': 3, 'Small Cap': 2, 'Micro Cap': 1 };
av = capOrder[ma['Cap Tier'] as string] ?? 0;
bv = capOrder[mb['Cap Tier'] as string] ?? 0;
} else {
// Generic display metric by display key
const keyMap: Record<string, string> = {
pe: 'P/E', peg: 'PEG', roe: 'ROE%', fcf: 'FCF Yld%',
expense: 'Exp Ratio%', ret5y: '5Y Return%',
rating: 'Rating', ytm: 'YTM%',
};
const metricKey = keyMap[col] ?? col;
av = numVal(ma[metricKey]); bv = numVal(mb[metricKey]);
}
if (typeof av === 'string' && typeof bv === 'string') {
return asc ? av.localeCompare(bv) : bv.localeCompare(av);
}
const diff = (av as number) - (bv as number);
return asc ? diff : -diff;
});
}
// Colour class for signed % values (52W Chg, From High, Upside, DCF Safety)
function signClass(val: string | number | null | undefined): string {
if (val == null) return '';
const n = typeof val === 'number' ? val : parseFloat(String(val));
if (isNaN(n)) return '';
return n > 0 ? 'pos' : n < 0 ? 'neg' : '';
}
function breakdownEntries(bd: Record<string, number> | undefined) {
if (!bd) return [];
return Object.entries(bd).sort((a, b) => Math.abs(b[1]) - Math.abs(a[1]));
}
function maxAbs(bd: Record<string, number> | undefined): number {
if (!bd) return 1;
const max = Math.max(...Object.values(bd).map(Math.abs));
return max === 0 ? 1 : max;
}
</script>
<section class="section">
<div class="section-header">
<h2>{type}S</h2>
<span class="count">{rows.length}</span>
<span class="count">{filteredRows(rows).length === rows.length ? rows.length : `${filteredRows(rows).length} / ${rows.length}`}</span>
{#if hasFilter()}
<button class="filter-clear-btn" onclick={clearFilters}> Clear filters</button>
{/if}
<div class="mode-tabs">
<button class:active={mode === 'inflated'} onclick={() => mode = 'inflated'}>Mkt-Adjusted</button>
@@ -54,123 +202,312 @@
</div>
<div class="table-wrap">
<table>
<table class="asset-table">
<thead>
<!-- ── Column headers ── -->
<tr>
<th class="col-ticker">Ticker</th>
<th>Price</th>
<th>Verdict</th>
<th>Score</th>
<th class="col-expand"></th>
<th class="col-ticker sort-th" onclick={() => setSort('ticker')}>
Ticker <span class="sort-icon">{sortIcon('ticker')}</span>
</th>
<th class="sort-th" onclick={() => setSort('price')}>
Price <span class="sort-icon">{sortIcon('price')}</span>
</th>
<th class="sort-th" onclick={() => setSort('signal')}>
Signal <span class="sort-icon">{sortIcon('signal')}</span>
</th>
<th class="sort-th" onclick={() => setSort('score')}>
Score <span class="sort-icon">{sortIcon('score')}</span>
</th>
{#if type === 'STOCK'}
<!-- Classification -->
<th title="Market cap tier">Cap</th>
<th title="Growth / style classification">Style</th>
<!-- Valuation -->
<th>P/E</th>
<th>PEG</th>
<!-- Quality -->
<th title="Gross Margin %">GrossM%</th>
<th>ROE%</th>
<th>OpMgn%</th>
<th>FCF%</th>
<!-- Risk -->
<th>D/E</th>
<!-- 52-week movement -->
<th title="Total price return over last 52 weeks">52W Chg</th>
<th title="% below 52-week high">From High</th>
<!-- Expert signals -->
<th title="Wall Street analyst consensus">Analyst</th>
<th title="% upside to analyst target price">Upside</th>
<th title="DCF margin of safety — positive means undervalued">DCF Safety</th>
<!-- Risk flags -->
<th class="sort-th" title="Market cap tier" onclick={() => setSort('cap')}>
Cap <span class="sort-icon">{sortIcon('cap')}</span>
</th>
<th title="Growth / style">Style</th>
<th>Flags</th>
{:else if type === 'ETF'}
<th>Expense</th><th>Yield</th><th>AUM</th><th>5Y Ret</th>
<th class="sort-th" onclick={() => setSort('expense')}>
Expense <span class="sort-icon">{sortIcon('expense')}</span>
</th>
<th class="sort-th" onclick={() => setSort('ret5y')}>
5Y Ret <span class="sort-icon">{sortIcon('ret5y')}</span>
</th>
{:else}
<th>YTM</th><th>Duration</th><th>Rating</th>
<th class="sort-th" onclick={() => setSort('rating')}>
Rating <span class="sort-icon">{sortIcon('rating')}</span>
</th>
<th class="sort-th" onclick={() => setSort('ytm')}>
YTM <span class="sort-icon">{sortIcon('ytm')}</span>
</th>
{/if}
</tr>
<!-- ── Inline filter row ── -->
<tr class="filter-row">
<td></td>
<td class="col-ticker">
<input class="th-filter" type="text" placeholder="Ticker…" bind:value={filterTicker} />
</td>
<td>
<div class="th-filter-pair">
<input class="th-filter th-filter-num" type="number" placeholder="$ min" bind:value={filterPriceMin} />
<input class="th-filter th-filter-num" type="number" placeholder="$ max" bind:value={filterPriceMax} />
</div>
</td>
<td>
<select class="th-filter" bind:value={filterSignal}>
<option value="">All signals</option>
<option value="✅ Strong Buy">Strong Buy</option>
<option value="⚡ Momentum">Momentum</option>
<option value="⚠️ Speculation">Speculation</option>
<option value="🔄 Neutral">Neutral</option>
<option value="❌ Avoid">Avoid</option>
</select>
</td>
<td>
<input class="th-filter th-filter-num" type="number" placeholder="Score ≥" min="0" max="20" bind:value={filterScoreMin} />
</td>
{#if type === 'STOCK'}
<td>
<select class="th-filter" bind:value={filterCap}>
<option value="">All caps</option>
{#each CAP_OPTIONS as c}<option value={c}>{c}</option>{/each}
</select>
</td>
<td>
<select class="th-filter" bind:value={filterStyle}>
<option value="">All styles</option>
{#each STYLE_OPTIONS as s}<option value={s}>{s}</option>{/each}
</select>
</td>
<td>
<label class="th-filter-check" title="Show only rows that passed all gates">
<input type="checkbox" bind:checked={filterFlags} />
<span>Passed only</span>
</label>
</td>
{:else}
<td></td>
<td></td>
{/if}
</tr>
</thead>
<tbody>
{#each sorted(rows) as r}
{#each sortedRows(rows) as r}
{@const m = r.asset.displayMetrics ?? {}}
{@const v = r[mode as 'inflated' | 'fundamental']}
<tr class="data-row" data-signal={sigOrd(r.signal)}>
{@const isOpen = expanded === r.asset.ticker}
{@const colCount = type === 'STOCK' ? 8 : 7}
{@const flags = v.audit?.riskFlags ?? []}
{@const rawScore = parseInt(v.scoreSummary?.replace(/\D/g, '') ?? '0', 10)}
<!-- ── Summary row ── -->
<tr
class="data-row summary-row"
class:row-open={isOpen}
data-signal={sigOrd(r.signal)}
onclick={() => toggleExpand(r.asset.ticker)}
>
<td class="col-expand">{isOpen ? '▾' : '▸'}</td>
<td class="ticker">{r.asset.ticker}</td>
<td class="num">{m.Price ?? '—'}</td>
<td><VerdictPill label={v.label} /></td>
<td class="score-cell" title={v.scoreSummary}>{v.scoreSummary}</td>
<!-- Signal pill -->
<td class="signal-verdict-cell">
<span class="sv-pill sv-{(r.signal ?? '').includes('Strong') ? 'strong' : (r.signal ?? '').includes('Momentum') ? 'momentum' : (r.signal ?? '').includes('Speculation') ? 'spec' : (r.signal ?? '').includes('Neutral') ? 'neutral' : 'avoid'}">{(r.signal ?? '').replace(/^[^\w\s]+\s*/, '').trim() || '—'}</span>
</td>
<!-- Score as dot scale -->
<td class="score-cell" title={v.scoreSummary}>
{#if v.scoreSummary?.startsWith('Gate failed')}
<span class="score-fail"></span>
{:else}
<span class="score-dots">
{#each Array(5) as _, i}
<span class="score-dot" class:on={i < Math.round(rawScore / 4)}></span>
{/each}
</span>
<span class="score-num">{rawScore}</span>
{/if}
</td>
{#if type === 'STOCK'}
<!-- Classification -->
<td><span class="tag sm cap-tag">{m['Cap Tier'] ?? '—'}</span></td>
<td><span class="tag sm style-tag">{m['Style'] ?? '—'}</span></td>
<!-- Valuation -->
<td class="num">{m['P/E'] ?? '—'}</td>
<td class="num">{m['PEG'] ?? '—'}</td>
<!-- Quality -->
<td class="num">{m['GrossM%'] ?? '—'}</td>
<td class="num">{m['ROE%'] ?? '—'}</td>
<td class="num">{m['OpMgn%'] ?? '—'}</td>
<td class="num">{m['FCF Yld%'] ?? '—'}</td>
<!-- Risk -->
<td class="num">{m['D/E'] ?? '—'}</td>
<!-- 52-week movement — green if up, red if down -->
<td class="num {signClass(m['52W Chg'])}">{m['52W Chg'] ?? '—'}</td>
<td class="num {signClass(m['From High'])}">{m['From High'] ?? '—'}</td>
<!-- Expert signals -->
<td class="analyst-cell">{m['Analyst'] ?? '—'}</td>
<td class="num {signClass(m['Upside'])}">{m['Upside'] ?? '—'}</td>
<td class="num {signClass(m['DCF Safety'])}">{m['DCF Safety'] ?? '—'}</td>
<!-- Risk flags -->
<td class="flags">
{#each v.audit?.riskFlags ?? [] as flag}
<span class="flag">{flag}</span>
{/each}
<td><span class="tag sm style-tag">{m['Style'] ?? '—'}</span></td>
<!-- Flags: count badge with hover expand -->
<td class="flags-cell">
{#if flags.length > 0}
<span class="flags-badge">
<span class="flags-count">{flags.length}</span>
</span>
{/if}
</td>
{:else if type === 'ETF'}
<td class="num">{m['Exp Ratio%'] ?? '—'}</td>
<td class="num">{m['Yield%'] ?? '—'}</td>
<td class="num">{m['AUM'] ?? '—'}</td>
<td class="num">{m['5Y Return%'] ?? '—'}</td>
<td class="num">{m['Exp Ratio%'] ?? '—'}</td>
<td class="num">{m['5Y Return%'] ?? '—'}</td>
{:else}
<td class="num">{m['YTM%'] ?? '—'}</td>
<td class="num">{m['Duration'] ?? '—'}</td>
<td class="num">{m['Rating'] ?? '—'}</td>
<td class="num">{m['Rating'] ?? '—'}</td>
<td class="num">{m['YTM%'] ?? '—'}</td>
{/if}
</tr>
<!-- ── Inline detail row ── -->
{#if isOpen}
{@const mktPass = r.inflated.audit?.passedGates}
{@const grahamPass = r.fundamental.audit?.passedGates}
<tr class="detail-row">
<td colspan={colCount} class="detail-cell">
<div class="detail-panel">
<!-- ══ LEFT — metric grid ══════════════════════════════════ -->
<div class="dp-left">
<div class="dp-title">Metrics</div>
<div class="dp-metric-grid">
{#if type === 'STOCK'}
<div class="dp-metric-card">
<span class="dp-mc-label">P/E</span>
<span class="dp-mc-value">{m['P/E'] ?? '—'}</span>
</div>
<div class="dp-metric-card">
<span class="dp-mc-label">PEG</span>
<span class="dp-mc-value">{m['PEG'] ?? '—'}</span>
</div>
<div class="dp-metric-card">
<span class="dp-mc-label">ROE%</span>
<span class="dp-mc-value {signClass(m['ROE%'])}">{m['ROE%'] ?? '—'}</span>
</div>
<div class="dp-metric-card">
<span class="dp-mc-label">Op Mgn%</span>
<span class="dp-mc-value {signClass(m['OpMgn%'])}">{m['OpMgn%'] ?? '—'}</span>
</div>
<div class="dp-metric-card">
<span class="dp-mc-label">Gross M%</span>
<span class="dp-mc-value {signClass(m['GrossM%'])}">{m['GrossM%'] ?? '—'}</span>
</div>
<div class="dp-metric-card">
<span class="dp-mc-label">FCF Yld%</span>
<span class="dp-mc-value {signClass(m['FCF Yld%'])}">{m['FCF Yld%'] ?? '—'}</span>
</div>
<div class="dp-metric-card">
<span class="dp-mc-label">D/E</span>
<span class="dp-mc-value">{m['D/E'] ?? '—'}</span>
</div>
<div class="dp-metric-card">
<span class="dp-mc-label">52W Chg</span>
<span class="dp-mc-value {signClass(m['52W Chg'])}">{m['52W Chg'] ?? '—'}</span>
</div>
<div class="dp-metric-card">
<span class="dp-mc-label">From High</span>
<span class="dp-mc-value {signClass(m['From High'])}">{m['From High'] ?? '—'}</span>
</div>
<div class="dp-metric-card">
<span class="dp-mc-label">Analyst</span>
<span class="dp-mc-value">{m['Analyst'] ?? '—'}</span>
</div>
<div class="dp-metric-card">
<span class="dp-mc-label">Upside</span>
<span class="dp-mc-value {signClass(m['Upside'])}">{m['Upside'] ?? '—'}</span>
</div>
<div class="dp-metric-card">
<span class="dp-mc-label">DCF Safety</span>
<span class="dp-mc-value {signClass(m['DCF Safety'])}">{m['DCF Safety'] ?? '—'}</span>
</div>
{:else if type === 'ETF'}
<div class="dp-metric-card">
<span class="dp-mc-label">Yield%</span>
<span class="dp-mc-value">{m['Yield%'] ?? '—'}</span>
</div>
<div class="dp-metric-card">
<span class="dp-mc-label">AUM</span>
<span class="dp-mc-value">{m['AUM'] ?? '—'}</span>
</div>
<div class="dp-metric-card">
<span class="dp-mc-label">5Y Ret%</span>
<span class="dp-mc-value {signClass(m['5Y Return%'])}">{m['5Y Return%'] ?? '—'}</span>
</div>
<div class="dp-metric-card">
<span class="dp-mc-label">Exp Ratio%</span>
<span class="dp-mc-value">{m['Exp Ratio%'] ?? '—'}</span>
</div>
{:else}
<div class="dp-metric-card">
<span class="dp-mc-label">YTM%</span>
<span class="dp-mc-value">{m['YTM%'] ?? '—'}</span>
</div>
<div class="dp-metric-card">
<span class="dp-mc-label">Duration</span>
<span class="dp-mc-value">{m['Duration'] ?? '—'}</span>
</div>
<div class="dp-metric-card">
<span class="dp-mc-label">Rating</span>
<span class="dp-mc-value">{m['Rating'] ?? '—'}</span>
</div>
{/if}
</div>
<!-- ── Gate badge chips ── -->
<div class="dp-gates-row">
<span class="dp-gate-chip" class:dp-gate-chip-pass={mktPass} class:dp-gate-chip-fail={!mktPass}>
MKT {mktPass ? '✓' : '✗'}
</span>
<span class="dp-gate-chip" class:dp-gate-chip-pass={grahamPass} class:dp-gate-chip-fail={!grahamPass}>
GRAHAM {grahamPass ? '✓' : '✗'}
</span>
</div>
<!-- ── Risk flag pills ── -->
{#if v.audit?.riskFlags?.length}
<div class="dp-risk-row">
{#each v.audit.riskFlags as flag}
<span class="dp-risk-pill">{flag}</span>
{/each}
</div>
{/if}
</div>
<!-- ══ RIGHT — verdict card (factor bar chart) ═════════════ -->
<div class="dp-right">
<div class="dp-title">
Factor Scores
<span class="dp-mode-note">({mode === 'inflated' ? 'Mkt-Adj' : 'Graham'})</span>
</div>
{#if !v.audit?.passedGates && v.audit?.failures?.length}
<!-- Gate failures shown when gates didn't pass -->
<div class="dp-failures">
{#each v.audit.failures as f}
<div class="dp-failure-item">{f}</div>
{/each}
</div>
{:else if breakdownEntries(v.audit?.breakdown).length}
{@const entries = breakdownEntries(v.audit?.breakdown)}
{@const scale = maxAbs(v.audit?.breakdown)}
<div class="dp-bar-chart">
{#each entries as [factor, score]}
{@const pct = Math.round((Math.abs(score) / scale) * 100)}
<div class="dp-bar-row">
<span class="dp-bar-label">{factor}</span>
<div class="dp-bar-track">
<div
class="dp-bar-fill {score > 0 ? 'dp-bar-pos' : 'dp-bar-neg'}"
style="width: {pct}%"
></div>
</div>
<span class="dp-bar-val {score > 0 ? 'pos' : score < 0 ? 'neg' : ''}">
{score > 0 ? '+' : ''}{score}
</span>
</div>
{/each}
</div>
{:else}
<div class="dp-no-factors">No factor data — gates failed before scoring</div>
{/if}
</div>
</div>
</td>
</tr>
{/if}
{/each}
</tbody>
</table>
</div>
</section>
<style>
/* Score cell — truncates long gate summaries, tooltip shows full text */
.score-cell {
color: var(--text-dim);
font-size: var(--fs-sm);
max-width: 140px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Classification tags */
.cap-tag { color: var(--blue-light, #93c5fd); border-color: var(--blue-dim, #1e3a5f); }
.style-tag { color: var(--text-muted); }
/* Signed % colouring */
.pos { color: var(--green); }
.neg { color: var(--red); }
/* Analyst label — not a number */
.analyst-cell {
font-size: var(--fs-sm);
color: var(--text-muted);
white-space: nowrap;
}
/* Risk flags column */
.flags { display: flex; flex-direction: column; gap: 2px; min-width: 160px; }
.flag { color: var(--orange); font-size: var(--fs-sm); white-space: nowrap; }
</style>
@@ -68,110 +68,19 @@
{/if}
{#if expanded}
<div class="grid">
<div class="ctx-grid">
{#each cards as c}
<div class="card">
<div class="label-row">
<span class="label">{c.label}</span>
<div class="ctx-card">
<div class="ctx-label-row">
<span class="ctx-card-label">{c.label}</span>
<span class="tip-wrap">
<span class="tip-anchor">?</span>
<span class="tip-box">{c.tip}</span>
</span>
</div>
<div class="value">{c.value}</div>
<div class="ctx-value">{c.value}</div>
</div>
{/each}
</div>
{/if}
</div>
<style>
.ctx-wrap { margin-bottom: 20px; }
/* ── Collapsible toggle ─────────────────────────────────────────── */
.ctx-toggle {
display: flex;
align-items: center;
gap: 8px;
background: none;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 6px 12px;
cursor: pointer;
margin-bottom: 10px;
}
.ctx-toggle-label {
font-size: var(--fs-sm);
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.07em;
color: var(--text-dimmer);
}
.ctx-toggle-chevron { font-size: var(--fs-2xs); color: var(--text-faint); }
/* ── Cards grid ─────────────────────────────────────────────────── */
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
gap: 10px;
margin-bottom: 8px;
}
.card { background: var(--bg-card); border-radius: var(--radius-md); padding: 12px var(--space-lg); }
.label-row { display: flex; align-items: center; justify-content: space-between; gap: 4px; }
.label { font-size: var(--fs-xs); color: var(--text-dim); text-transform: uppercase; letter-spacing: 0.05em; }
/* ── Tooltip ─────────────────────────────────────────────────────── */
.tip-wrap { position: relative; display: inline-flex; flex-shrink: 0; }
.tip-anchor {
display: inline-flex;
align-items: center;
justify-content: center;
width: 13px;
height: 13px;
border-radius: 50%;
background: var(--bg-card);
border: 1px solid var(--text-faint);
color: var(--text-dimmer);
font-size: var(--fs-2xs);
font-weight: 700;
cursor: help;
}
.tip-box {
display: none;
position: absolute;
bottom: calc(100% + 6px);
left: 50%;
transform: translateX(-50%);
width: 220px;
background: var(--bg-card);
border: 1px solid var(--text-faint);
border-radius: var(--radius-sm);
padding: 8px 10px;
font-size: var(--fs-sm);
color: var(--text-muted);
line-height: 1.5;
z-index: 50;
pointer-events: none;
white-space: normal;
}
.tip-box::after {
content: '';
position: absolute;
top: 100%;
left: 50%;
transform: translateX(-50%);
border: 5px solid transparent;
border-top-color: var(--text-faint);
}
.tip-wrap:hover .tip-box { display: block; }
.value { font-size: 17px; font-weight: 700; color: var(--text-primary); margin-top: 4px; }
</style>
@@ -3,67 +3,25 @@
import type { MarketContext } from '$lib/types.js';
let { ctx }: { ctx: MarketContext } = $props();
// Flat list of chips so the template stays declarative
// color: bg, border, text (all as hex/rgba strings)
const chips = $derived([
{ label: '10Y', value: ctx.riskFreeRate?.toFixed(2) + '%' },
{ label: 'VIX', value: ctx.vixLevel?.toFixed(1) },
{ label: 'S&P', value: ctx.sp500Price?.toLocaleString() },
{ label: 'S&P P/E', value: fmtPE(ctx.benchmarks?.marketPE) },
{ label: 'Tech P/E', value: fmtPE(ctx.benchmarks?.techPE) },
{ label: 'REIT Yld', value: ctx.benchmarks?.reitYield?.toFixed(2) + '%' },
{ label: 'IG Sprd', value: ctx.benchmarks?.igSpread?.toFixed(2) + '%' },
{ label: 'Rates', value: ctx.rateRegime, regime: ctx.rateRegime },
{ label: 'Vol', value: ctx.volatilityRegime, regime: ctx.volatilityRegime },
{ label: '10Y', value: ctx.riskFreeRate != null ? ctx.riskFreeRate.toFixed(1) + '%' : '—', color: 'indigo' },
{ label: 'VIX', value: ctx.vixLevel != null ? ctx.vixLevel.toFixed(1) : '—', color: 'rose' },
{ label: 'S&P', value: ctx.sp500Price?.toLocaleString() ?? '—', color: 'emerald' },
{ label: 'S&P P/E', value: fmtPE(ctx.benchmarks?.marketPE), color: 'sky' },
{ label: 'Tech P/E', value: fmtPE(ctx.benchmarks?.techPE), color: 'violet' },
{ label: 'REIT Yld', value: ctx.benchmarks?.reitYield != null ? ctx.benchmarks.reitYield.toFixed(1) + '%' : '—', color: 'amber' },
{ label: 'IG Sprd', value: ctx.benchmarks?.igSpread != null ? ctx.benchmarks.igSpread.toFixed(2) + '%' : '—', color: 'teal' },
{ label: 'Rates', value: ctx.rateRegime, regime: ctx.rateRegime, color: ctx.rateRegime === 'HIGH' ? 'red' : ctx.rateRegime === 'LOW' ? 'blue' : 'slate' },
{ label: 'Vol', value: ctx.volatilityRegime, regime: ctx.volatilityRegime, color: ctx.volatilityRegime === 'ELEVATED' ? 'orange' : 'slate' },
]);
</script>
<div class="ctx-strip">
<div class="bubble-strip">
{#each chips as chip}
<div class="ctx-chip">
<span class="ctx-label">{chip.label}</span>
<span class="ctx-val" class:ctx-regime={!!chip.regime} data-regime={chip.regime ?? ''}>
{chip.value ?? '—'}
</span>
<div class="bubble bubble-{chip.color}">
<span class="bubble-val">{chip.value ?? '—'}</span>
<span class="bubble-label">{chip.label}</span>
</div>
{/each}
</div>
<style>
.ctx-strip {
display: flex;
gap: 1px;
background: var(--border);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
overflow: hidden;
}
.ctx-chip {
flex: 1;
min-width: 70px;
background: var(--bg-base);
padding: 10px var(--space-lg);
display: flex;
flex-direction: column;
gap: 3px;
}
.ctx-label {
font-size: var(--fs-2xs);
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--text-dimmer);
}
.ctx-val {
font-size: var(--fs-lg);
font-weight: 700;
color: var(--text-primary);
font-variant-numeric: tabular-nums;
}
.ctx-regime[data-regime='HIGH'] { color: var(--red); }
.ctx-regime[data-regime='NORMAL'] { color: var(--text-muted); }
.ctx-regime[data-regime='LOW'] { color: var(--green); }
</style>
+71
View File
@@ -0,0 +1,71 @@
/**
* Auth store — holds current user + JWT token.
* Persists token to sessionStorage so it survives page refresh within the tab.
*/
import type { AuthUser, Role } from '$lib/types.js';
const TOKEN_KEY = 'ms_token';
function createAuthStore() {
// Hydrate from sessionStorage on first load
const stored = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem(TOKEN_KEY) : null;
let token = $state<string | null>(stored);
let user = $state<AuthUser | null>(stored ? parseTokenUser(stored) : null);
function setAuth(newToken: string, newUser: AuthUser) {
token = newToken;
user = newUser;
sessionStorage.setItem(TOKEN_KEY, newToken);
}
function clearAuth() {
token = null;
user = null;
sessionStorage.removeItem(TOKEN_KEY);
}
return {
get token() {
return token;
},
get user() {
return user;
},
get isLoggedIn() {
return token !== null && user !== null;
},
get role(): Role | null {
return user?.role ?? null;
},
get isTrader() {
return user?.role === 'trader' || user?.role === 'admin';
},
setAuth,
clearAuth,
};
}
/** Decode the JWT payload (base64url middle segment) to extract user info. */
function parseTokenUser(token: string): AuthUser | null {
try {
const parts = token.split('.');
if (parts.length !== 3) return null;
const payload = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')));
if (!payload.sub || !payload.email || !payload.role) return null;
// Check expiry
if (payload.exp && payload.exp * 1000 < Date.now()) return null;
return {
id: payload.sub as string,
email: payload.email as string,
role: payload.role as Role,
createdAt: '',
lastLogin: null,
};
} catch {
return null;
}
}
export const authStore = createAuthStore();
+2 -3
View File
@@ -1,4 +1,4 @@
import { addHolding, removeHolding } from '$lib/api.js';
import { addHolding, removeHolding, authFetch } from '$lib/api.js';
import type { MarketContext, AdviceRow, PersonalFinance, HoldingFormData } from '$lib/types.js';
interface PortfolioData {
@@ -23,8 +23,7 @@ class PortfolioStore {
else this.refreshing = true;
this.loadError = null;
window
.fetch('/api/finance/portfolio')
authFetch('/api/finance/portfolio')
.then((res) =>
res.ok
? res.json()
+17
View File
@@ -1,6 +1,23 @@
import type { AssetType } from '$types/asset.model.js';
import type { LLMAnalysis } from '$types/finance.model.js';
// ── Auth types ────────────────────────────────────────────────────────────────
export type Role = 'trader' | 'viewer' | 'admin';
export interface AuthUser {
id: string;
email: string;
role: Role;
createdAt: string;
lastLogin: string | null;
}
export interface AuthResponse {
token: string;
user: AuthUser;
}
/** Detailed display metrics rendered per asset row in the screener table. */
export interface AssetDisplayMetrics {
// ── Common ──────────────────────────────────────────────────────────
+2 -2
View File
@@ -2,9 +2,9 @@
* Number and currency formatting utilities.
*/
/** Formats a P/E ratio — e.g. 22.5 → "22.5x", null → "—" */
/** Formats a P/E ratio — e.g. 26.72091 → "26.7x", null → "—" */
export function fmtPE(v: number | null | undefined): string {
return v != null ? v + 'x' : '—';
return v != null ? v.toFixed(1) + 'x' : '—';
}
/** Full currency format — e.g. 1234.5 → "$1,234.50" */
+32 -8
View File
@@ -9,25 +9,49 @@
*/
export function verdictShort(label: string | null | undefined): string {
if (!label) return '—';
if (label.includes('High Conviction')) return 'Strong';
if (label.includes('High Conviction')) return 'Strong Buy';
if (label.includes('Speculative')) return 'Speculative';
if (label.includes('Momentum')) return 'Momentum';
if (label.includes('BUY')) return 'Buy';
if (label.includes('Efficient')) return 'Efficient';
if (label.includes('Attractive')) return 'Attractive';
if (label.includes('Neutral')) return 'Hold';
if (label.includes('REJECT')) return 'Reject';
if (label.includes('Avoid')) return 'Avoid';
return label.replace(/[🟢🟡🔴]/u, '').trim();
return label.replace(/[\u{1F7E2}\u{1F7E1}\u{1F534}]/u, '').trim();
}
/**
* Returns a CSS colour class ('green' | 'yellow' | 'red') based on
* the emoji prefix of a verdict label.
* Returns a CSS colour class based on the verdict label content.
*
* Signal mapping:
* 🟢 / High Conviction / Efficient / Attractive → green
* 🟡 / Speculative / Momentum → yellow
* Neutral / Hold / no signal → blue (calm, not alarming)
* 🔴 / Avoid / Reject / REJECT → red
*/
export function vClass(label: string | null | undefined): 'green' | 'yellow' | 'red' {
if (label?.startsWith('🟢')) return 'green';
if (label?.startsWith('🟡')) return 'yellow';
return 'red';
export function vClass(
label: string | null | undefined,
): 'green' | 'yellow' | 'red' | 'blue' | 'gray' {
if (!label) return 'gray';
if (
label.startsWith('🟢') ||
label.includes('High Conviction') ||
label.includes('Efficient') ||
label.includes('Attractive')
)
return 'green';
if (label.startsWith('🟡') || label.includes('Speculative') || label.includes('Momentum'))
return 'yellow';
if (
label.startsWith('🔴') ||
label.includes('Avoid') ||
label.includes('Reject') ||
label.includes('REJECT')
)
return 'red';
if (label.includes('Neutral') || label.includes('Hold') || label.includes('BUY')) return 'blue';
return 'gray';
}
/**