Compare commits

...

3 commits

Author SHA1 Message Date
6636054742 feat(dashboard): /meet-kevin/strategy page wired
Some checks failed
ci/woodpecker/push/woodpecker Pipeline was canceled
Strategy.tsx composes 6-up metrics header, StrategyVsBenchmarkCurve
equity chart, TickerScorecardTable and BacktestRunHistory. Selecting a
backtest run replaces the chart with that run's equity curve. Run
Backtest button fires POST and polls for completion.
App.tsx: +route /meet-kevin/strategy.
Layout.tsx: +sidebar entry 'MK Strategy' under Meet Kevin group.
2026-05-24 00:48:27 +00:00
5f5529ef09 feat(dashboard): 3 components for the strategy page
TickerScorecardTable: bridge-status badges (WOULD-TRADE/HOLDING/etc),
conviction bar, unrealised P&L, manual-close button.
BacktestRunHistory: sortable run list with return/sharpe/alpha columns,
row click selects a run for detail view.
StrategyVsBenchmarkCurve: dual lightweight-charts line (strategy blue,
SPY dashed grey) with legend.
2026-05-24 00:48:22 +00:00
90cf21521f feat(dashboard): TS types + API client for strategy + backtest
BacktestRun, BacktestRunDetail, StrategyTicker, StrategyEquityCurve,
StrategyPerformance types added to meetKevin.ts. New meetKevinStrategy.ts
with 8 axios methods covering the backtest run/list/get/latest and
strategy tickers/equity-curve/performance/close endpoints.
2026-05-24 00:48:16 +00:00
8 changed files with 738 additions and 0 deletions

View file

@ -13,6 +13,7 @@ import MeetKevinVideos from './pages/meetKevin/Videos';
import MeetKevinVideoDetail from './pages/meetKevin/VideoDetail';
import MeetKevinStocks from './pages/meetKevin/Stocks';
import MeetKevinStockDetail from './pages/meetKevin/StockDetail';
import MeetKevinStrategy from './pages/meetKevin/Strategy';
export default function App() {
return (
@ -41,6 +42,7 @@ export default function App() {
<Route path="meet-kevin/videos/:id" element={<MeetKevinVideoDetail />} />
<Route path="meet-kevin/stocks" element={<MeetKevinStocks />} />
<Route path="meet-kevin/stocks/:symbol" element={<MeetKevinStockDetail />} />
<Route path="meet-kevin/strategy" element={<MeetKevinStrategy />} />
</Route>
{/* Catch-all redirect */}

View file

@ -0,0 +1,60 @@
import client from './client';
import type {
BacktestRun,
BacktestRunDetail,
StrategyEquityCurve,
StrategyPerformance,
StrategyTicker,
} from '../types/meetKevin';
export async function runBacktest(params: {
holding_days?: number;
slippage_pct?: number;
dedupe_policy?: 'roll' | 'ignore';
initial_capital?: number;
}): Promise<{ run_uuid: string; status: string }> {
const { data } = await client.post('/meet-kevin/backtest/run', params);
return data;
}
export async function listBacktestRuns(limit = 20): Promise<BacktestRun[]> {
const { data } = await client.get('/meet-kevin/backtest/runs', {
params: { limit },
});
return data;
}
export async function getBacktestRun(runUuid: string): Promise<BacktestRunDetail> {
const { data } = await client.get(`/meet-kevin/backtest/runs/${runUuid}`);
return data;
}
export async function getLatestBacktest(): Promise<BacktestRunDetail> {
const { data } = await client.get('/meet-kevin/backtest/latest');
return data;
}
export async function getStrategyTickers(): Promise<StrategyTicker[]> {
const { data } = await client.get('/meet-kevin/strategy/tickers');
return data;
}
export async function getStrategyEquityCurve(params: {
from?: string;
to?: string;
include_benchmark?: 'spy';
}): Promise<StrategyEquityCurve> {
const { data } = await client.get('/meet-kevin/strategy/equity-curve', {
params,
});
return data;
}
export async function getStrategyPerformance(): Promise<StrategyPerformance> {
const { data } = await client.get('/meet-kevin/strategy/performance');
return data;
}
export async function closeKevinPosition(symbol: string): Promise<void> {
await client.post(`/meet-kevin/positions/${symbol}/close`);
}

View file

@ -9,6 +9,7 @@ const navItems = [
{ to: '/news', label: 'News', icon: 'M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2V7m2 13a2 2 0 002-2V9a2 2 0 00-2-2h-2' },
{ to: '/backtest', label: 'Backtest', icon: 'M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z' },
{ to: '/meet-kevin', label: 'Meet Kevin', icon: 'M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z' },
{ to: '/meet-kevin/strategy', label: 'MK Strategy', icon: 'M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z' },
];
export function Layout() {

View file

@ -0,0 +1,122 @@
import type { BacktestRun, BacktestRunStatus } from '../../types/meetKevin';
const STATUS_BADGE: Record<BacktestRunStatus, { label: string; cls: string }> = {
running: { label: 'Running', cls: 'bg-blue-600/30 text-blue-300 border-blue-500/40' },
completed: { label: 'Completed', cls: 'bg-green-600/30 text-green-300 border-green-500/40' },
failed: { label: 'Failed', cls: 'bg-red-600/30 text-red-300 border-red-500/40' },
};
function fmt(v: number | null | undefined, suffix = '%', decimals = 2): string {
if (v == null) return '—';
return `${v >= 0 ? '+' : ''}${v.toFixed(decimals)}${suffix}`;
}
interface Props {
runs: BacktestRun[];
isLoading: boolean;
selectedRunUuid: string | null;
onSelect: (runUuid: string) => void;
}
export function BacktestRunHistory({ runs, isLoading, selectedRunUuid, onSelect }: Props) {
if (isLoading) {
return (
<div className="flex justify-center py-10">
<span className="inline-block w-6 h-6 border-2 border-blue-400/30 border-t-blue-400 rounded-full animate-spin" />
</div>
);
}
if (runs.length === 0) {
return (
<div className="bg-slate-800 border border-slate-700 rounded-xl p-10 text-center text-slate-400">
No backtest runs yet click &ldquo;Run Backtest&rdquo; to start one.
</div>
);
}
return (
<div className="bg-slate-800 border border-slate-700 rounded-xl overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-slate-900/50">
<tr>
<th className="px-5 py-3 text-left text-xs text-slate-400 uppercase tracking-wide font-semibold">
Started
</th>
<th className="px-5 py-3 text-left text-xs text-slate-400 uppercase tracking-wide font-semibold">
Status
</th>
<th className="px-5 py-3 text-left text-xs text-slate-400 uppercase tracking-wide font-semibold">
Return
</th>
<th className="px-5 py-3 text-left text-xs text-slate-400 uppercase tracking-wide font-semibold">
Sharpe
</th>
<th className="px-5 py-3 text-left text-xs text-slate-400 uppercase tracking-wide font-semibold">
Max DD
</th>
<th className="px-5 py-3 text-left text-xs text-slate-400 uppercase tracking-wide font-semibold">
Alpha
</th>
<th className="px-5 py-3 text-left text-xs text-slate-400 uppercase tracking-wide font-semibold">
Trades
</th>
<th className="px-5 py-3 text-left text-xs text-slate-400 uppercase tracking-wide font-semibold">
Source
</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-700">
{runs.map((run) => {
const badge = STATUS_BADGE[run.status];
const m = run.metrics_json;
const isSelected = run.run_uuid === selectedRunUuid;
return (
<tr
key={run.run_uuid}
onClick={() => onSelect(run.run_uuid)}
className={`cursor-pointer transition-colors ${
isSelected
? 'bg-blue-600/10'
: 'hover:bg-slate-700/30'
}`}
>
<td className="px-5 py-3.5 text-slate-300 font-mono text-xs">
{new Date(run.started_at).toLocaleString()}
</td>
<td className="px-5 py-3.5">
<span className={`px-2 py-0.5 text-xs font-semibold uppercase rounded-md border ${badge.cls}`}>
{badge.label}
</span>
{run.error_message && (
<span className="ml-2 text-xs text-red-400 truncate max-w-[180px] inline-block align-middle">
{run.error_message}
</span>
)}
</td>
<td className={`px-5 py-3.5 font-mono ${m && m.total_return_pct >= 0 ? 'text-green-400' : 'text-red-400'}`}>
{m ? fmt(m.total_return_pct) : '—'}
</td>
<td className="px-5 py-3.5 text-slate-300 font-mono">
{m?.sharpe_ratio != null ? m.sharpe_ratio.toFixed(2) : '—'}
</td>
<td className="px-5 py-3.5 font-mono text-red-400">
{m?.max_drawdown_pct != null ? `${m.max_drawdown_pct.toFixed(2)}%` : '—'}
</td>
<td className={`px-5 py-3.5 font-mono ${m?.alpha_vs_spy_pct != null && m.alpha_vs_spy_pct >= 0 ? 'text-green-400' : 'text-red-400'}`}>
{m ? fmt(m.alpha_vs_spy_pct) : '—'}
</td>
<td className="px-5 py-3.5 text-slate-300">
{m?.trade_count ?? '—'}
</td>
<td className="px-5 py-3.5 text-slate-400 text-xs capitalize">
{run.trigger_source}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}

View file

@ -0,0 +1,108 @@
import { useEffect, useRef } from 'react';
import { createChart, type IChartApi, LineSeries } from 'lightweight-charts';
import type { EquityCurvePoint } from '../../types/meetKevin';
interface Props {
strategy: EquityCurvePoint[];
benchmark: EquityCurvePoint[] | null;
height?: number;
}
function toChartData(points: EquityCurvePoint[]) {
const byDay = new Map<string, number>();
for (const p of points) {
const day = p.timestamp.split('T')[0];
byDay.set(day, p.value);
}
return Array.from(byDay.entries())
.sort(([a], [b]) => a.localeCompare(b))
.map(([time, value]) => ({ time, value }));
}
export function StrategyVsBenchmarkCurve({ strategy, benchmark, height = 350 }: Props) {
const containerRef = useRef<HTMLDivElement>(null);
const chartRef = useRef<IChartApi | null>(null);
useEffect(() => {
if (!containerRef.current) return;
const chart = createChart(containerRef.current, {
height,
layout: {
background: { color: '#1e293b' },
textColor: '#94a3b8',
},
grid: {
vertLines: { color: '#334155' },
horzLines: { color: '#334155' },
},
crosshair: { mode: 0 },
rightPriceScale: { borderColor: '#475569' },
timeScale: { borderColor: '#475569', timeVisible: true },
});
const strategySeries = chart.addSeries(LineSeries, {
color: '#3b82f6',
lineWidth: 2,
title: 'Strategy',
priceFormat: {
type: 'custom',
formatter: (price: number) =>
'$' + price.toLocaleString('en-US', { minimumFractionDigits: 2 }),
},
});
const benchmarkSeries = chart.addSeries(LineSeries, {
color: '#94a3b8',
lineWidth: 1,
title: 'SPY',
lineStyle: 1, // dashed
priceFormat: {
type: 'custom',
formatter: (price: number) =>
'$' + price.toLocaleString('en-US', { minimumFractionDigits: 2 }),
},
});
chartRef.current = chart;
if (strategy.length > 0) {
strategySeries.setData(toChartData(strategy) as { time: string; value: number }[]);
}
if (benchmark && benchmark.length > 0) {
benchmarkSeries.setData(toChartData(benchmark) as { time: string; value: number }[]);
}
chart.timeScale().fitContent();
const handleResize = () => {
if (containerRef.current) {
chart.applyOptions({ width: containerRef.current.clientWidth });
}
};
window.addEventListener('resize', handleResize);
handleResize();
return () => {
window.removeEventListener('resize', handleResize);
chart.remove();
chartRef.current = null;
};
}, [height, strategy, benchmark]);
return (
<div className="space-y-2">
<div className="flex items-center gap-4 text-xs text-slate-400">
<span className="flex items-center gap-1.5">
<span className="inline-block w-4 h-0.5 bg-blue-400" />
Strategy
</span>
<span className="flex items-center gap-1.5">
<span className="inline-block w-4 h-0.5 bg-slate-400 border-dashed" />
SPY benchmark
</span>
</div>
<div ref={containerRef} className="w-full rounded-lg overflow-hidden" />
</div>
);
}

View file

@ -0,0 +1,141 @@
import type { BridgeStatus, StrategyTicker } from '../../types/meetKevin';
import { ActionChip } from './ActionChip';
import { ConvictionBar } from './ConvictionBar';
const BRIDGE_BADGE: Record<BridgeStatus, { label: string; cls: string }> = {
emitted: { label: 'WOULD-TRADE', cls: 'bg-blue-600/30 text-blue-300 border-blue-500/40' },
dry_run: { label: 'WOULD-TRADE', cls: 'bg-blue-600/30 text-blue-300 border-blue-500/40' },
skipped_non_tradable: { label: 'NOT TRADABLE', cls: 'bg-slate-600/30 text-slate-400 border-slate-500/40' },
skipped_blocklist: { label: 'BLOCKLISTED', cls: 'bg-rose-600/30 text-rose-300 border-rose-500/40' },
skipped_caps: { label: 'CAP HIT', cls: 'bg-yellow-600/30 text-yellow-300 border-yellow-500/40' },
deferred: { label: 'DEFERRED', cls: 'bg-slate-600/30 text-slate-400 border-slate-500/40' },
broker_rejected: { label: 'REJECTED', cls: 'bg-red-600/30 text-red-300 border-red-500/40' },
};
interface Props {
tickers: StrategyTicker[];
isLoading: boolean;
onClose: (symbol: string) => void;
}
export function TickerScorecardTable({ tickers, isLoading, onClose }: Props) {
if (isLoading) {
return (
<div className="flex justify-center py-16">
<span className="inline-block w-8 h-8 border-2 border-blue-400/30 border-t-blue-400 rounded-full animate-spin" />
</div>
);
}
if (tickers.length === 0) {
return (
<div className="bg-slate-800 border border-slate-700 rounded-xl p-12 text-center text-slate-400">
No ticker signals yet
</div>
);
}
return (
<div className="bg-slate-800 border border-slate-700 rounded-xl overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-slate-900/50">
<tr>
<th className="px-5 py-3 text-left text-xs text-slate-400 uppercase tracking-wide font-semibold">
Symbol
</th>
<th className="px-5 py-3 text-left text-xs text-slate-400 uppercase tracking-wide font-semibold">
Signal
</th>
<th className="px-5 py-3 text-left text-xs text-slate-400 uppercase tracking-wide font-semibold">
Conviction
</th>
<th className="px-5 py-3 text-left text-xs text-slate-400 uppercase tracking-wide font-semibold">
Price
</th>
<th className="px-5 py-3 text-left text-xs text-slate-400 uppercase tracking-wide font-semibold">
P&amp;L
</th>
<th className="px-5 py-3 text-left text-xs text-slate-400 uppercase tracking-wide font-semibold">
Status
</th>
<th className="px-5 py-3 text-left text-xs text-slate-400 uppercase tracking-wide font-semibold">
Mentions
</th>
<th className="px-5 py-3 text-left text-xs text-slate-400 uppercase tracking-wide font-semibold">
Last seen
</th>
<th className="px-5 py-3" />
</tr>
</thead>
<tbody className="divide-y divide-slate-700">
{tickers.map((t) => {
const badge = t.bridge_status ? BRIDGE_BADGE[t.bridge_status] : null;
const pnl = t.unrealized_pnl_pct;
return (
<tr key={t.symbol} className="hover:bg-slate-700/30 transition-colors">
<td className="px-5 py-3.5">
<span className="font-mono font-bold text-white">${t.symbol}</span>
{t.is_held && (
<span className="ml-2 px-1.5 py-0.5 text-xs bg-green-600/20 text-green-400 border border-green-500/30 rounded">
HOLDING
</span>
)}
</td>
<td className="px-5 py-3.5">
<ActionChip action={t.latest_action} />
</td>
<td className="px-5 py-3.5">
<div className="flex items-center gap-2 min-w-[120px]">
<div className="flex-1">
<ConvictionBar value={t.latest_conviction} />
</div>
<span className="text-xs text-slate-400 shrink-0">
{(t.latest_conviction * 100).toFixed(0)}%
</span>
</div>
</td>
<td className="px-5 py-3.5 text-slate-300 font-mono">
{t.current_price != null
? `$${t.current_price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
: '—'}
</td>
<td className="px-5 py-3.5 font-mono">
{pnl != null ? (
<span className={pnl >= 0 ? 'text-green-400' : 'text-red-400'}>
{pnl >= 0 ? '+' : ''}{pnl.toFixed(2)}%
</span>
) : (
<span className="text-slate-500"></span>
)}
</td>
<td className="px-5 py-3.5">
{badge ? (
<span className={`px-2 py-0.5 text-xs font-semibold uppercase rounded-md border ${badge.cls}`}>
{badge.label}
</span>
) : (
<span className="text-slate-500"></span>
)}
</td>
<td className="px-5 py-3.5 text-slate-300">{t.mention_count}</td>
<td className="px-5 py-3.5 text-slate-400">
{new Date(t.last_mention_at).toLocaleDateString()}
</td>
<td className="px-5 py-3.5">
{t.is_held && (
<button
onClick={() => onClose(t.symbol)}
className="px-2.5 py-1 text-xs bg-red-600/20 hover:bg-red-600/40 text-red-300 border border-red-500/30 rounded transition-colors"
>
Close
</button>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}

View file

@ -0,0 +1,213 @@
import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { TickerScorecardTable } from '../../components/meetKevin/TickerScorecardTable';
import { BacktestRunHistory } from '../../components/meetKevin/BacktestRunHistory';
import { StrategyVsBenchmarkCurve } from '../../components/meetKevin/StrategyVsBenchmarkCurve';
import {
runBacktest,
listBacktestRuns,
getBacktestRun,
getStrategyTickers,
getStrategyEquityCurve,
getStrategyPerformance,
closeKevinPosition,
} from '../../api/meetKevinStrategy';
import type { BacktestRunStatus } from '../../types/meetKevin';
function MetricCard({ label, value, color = 'text-white' }: { label: string; value: string; color?: string }) {
return (
<div className="bg-slate-800 border border-slate-700 rounded-xl p-5">
<p className="text-xs text-slate-400 uppercase tracking-wide mb-1">{label}</p>
<p className={`text-2xl font-semibold font-mono ${color}`}>{value}</p>
</div>
);
}
function fmt(v: number | null | undefined, suffix = '%', decimals = 2): string {
if (v == null) return '—';
return `${v >= 0 ? '+' : ''}${v.toFixed(decimals)}${suffix}`;
}
const POLL_STATUSES: BacktestRunStatus[] = ['running'];
export default function MeetKevinStrategy() {
const queryClient = useQueryClient();
const [selectedRunUuid, setSelectedRunUuid] = useState<string | null>(null);
const { data: performance } = useQuery({
queryKey: ['meet-kevin', 'strategy', 'performance'],
queryFn: getStrategyPerformance,
refetchInterval: 60_000,
});
const { data: tickers, isLoading: tickersLoading } = useQuery({
queryKey: ['meet-kevin', 'strategy', 'tickers'],
queryFn: getStrategyTickers,
refetchInterval: 60_000,
});
const { data: equityCurve } = useQuery({
queryKey: ['meet-kevin', 'strategy', 'equity-curve'],
queryFn: () => getStrategyEquityCurve({ include_benchmark: 'spy' }),
refetchInterval: 120_000,
});
const { data: runs, isLoading: runsLoading } = useQuery({
queryKey: ['meet-kevin', 'backtest', 'runs'],
queryFn: () => listBacktestRuns(20),
refetchInterval: 30_000,
});
const { data: selectedRun } = useQuery({
queryKey: ['meet-kevin', 'backtest', 'run', selectedRunUuid],
queryFn: () => getBacktestRun(selectedRunUuid!),
enabled: selectedRunUuid != null,
refetchInterval: (query) => {
const data = query.state.data;
if (data && POLL_STATUSES.includes(data.status)) return 3_000;
return false;
},
});
const backtestMutation = useMutation({
mutationFn: runBacktest,
onSuccess: (data) => {
setSelectedRunUuid(data.run_uuid);
void queryClient.invalidateQueries({ queryKey: ['meet-kevin', 'backtest', 'runs'] });
},
});
const closeMutation = useMutation({
mutationFn: closeKevinPosition,
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ['meet-kevin', 'strategy', 'tickers'] });
},
});
const equityData = selectedRun?.equity_curve_json ?? equityCurve?.strategy ?? [];
const benchmarkData = selectedRun?.benchmark_curve_json ?? equityCurve?.benchmark ?? null;
return (
<div className="space-y-6">
{/* Page header */}
<div className="flex items-center justify-between">
<div>
<h2 className="text-2xl font-bold text-white">Meet Kevin Strategy</h2>
<p className="text-sm text-slate-400 mt-0.5">
Backtest history, ticker scorecard, and equity vs SPY
</p>
</div>
<button
onClick={() => backtestMutation.mutate({})}
disabled={backtestMutation.isPending}
className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-slate-600 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg transition-colors"
>
{backtestMutation.isPending ? (
<>
<span className="inline-block w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
Running
</>
) : (
<>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
Run Backtest
</>
)}
</button>
</div>
{/* Headline metrics */}
{performance && (
<div className="grid grid-cols-2 md:grid-cols-4 xl:grid-cols-6 gap-4">
<MetricCard
label="Total Return"
value={fmt(performance.total_return_pct)}
color={performance.total_return_pct >= 0 ? 'text-green-400' : 'text-red-400'}
/>
<MetricCard
label="Ann. Return"
value={fmt(performance.annualized_return_pct)}
color={(performance.annualized_return_pct ?? 0) >= 0 ? 'text-green-400' : 'text-red-400'}
/>
<MetricCard
label="Sharpe"
value={performance.sharpe_ratio != null ? performance.sharpe_ratio.toFixed(2) : '—'}
color={(performance.sharpe_ratio ?? 0) >= 1 ? 'text-green-400' : 'text-yellow-400'}
/>
<MetricCard
label="Max Drawdown"
value={performance.max_drawdown_pct != null ? `${performance.max_drawdown_pct.toFixed(2)}%` : '—'}
color="text-red-400"
/>
<MetricCard
label="Alpha vs SPY"
value={fmt(performance.alpha_vs_spy_pct)}
color={(performance.alpha_vs_spy_pct ?? 0) >= 0 ? 'text-green-400' : 'text-red-400'}
/>
<MetricCard
label="Open Positions"
value={performance.open_positions.toString()}
/>
</div>
)}
{/* Equity curve */}
{equityData.length > 0 && (
<div className="bg-slate-800 border border-slate-700 rounded-xl p-6">
<h3 className="text-lg font-semibold text-white mb-4">
{selectedRunUuid ? 'Backtest Equity Curve' : 'Strategy vs SPY'}
</h3>
<StrategyVsBenchmarkCurve
strategy={equityData}
benchmark={benchmarkData}
height={350}
/>
</div>
)}
{/* Ticker scorecard */}
<div className="space-y-3">
<h3 className="text-lg font-semibold text-white">Ticker Scorecard</h3>
<TickerScorecardTable
tickers={tickers ?? []}
isLoading={tickersLoading}
onClose={(symbol) => closeMutation.mutate(symbol)}
/>
</div>
{/* Backtest run history */}
<div className="space-y-3">
<h3 className="text-lg font-semibold text-white">Backtest History</h3>
<BacktestRunHistory
runs={runs ?? []}
isLoading={runsLoading}
selectedRunUuid={selectedRunUuid}
onSelect={setSelectedRunUuid}
/>
</div>
{/* Selected run detail */}
{selectedRun?.status === 'running' && (
<div className="bg-slate-800 border border-slate-700 rounded-xl p-6 text-center">
<span className="inline-block w-8 h-8 border-2 border-blue-400/30 border-t-blue-400 rounded-full animate-spin mb-3" />
<p className="text-white font-medium">Backtest running</p>
<p className="text-sm text-slate-400 mt-1">Results will appear automatically</p>
</div>
)}
{selectedRun?.status === 'failed' && (
<div className="bg-red-900/20 border border-red-700 rounded-xl p-6">
<p className="text-red-400 font-medium">Backtest Failed</p>
<p className="text-sm text-red-300 mt-1">
{selectedRun.error_message ?? 'An unknown error occurred'}
</p>
</div>
)}
</div>
);
}

View file

@ -112,3 +112,94 @@ export interface DashboardData {
count: number;
}[];
}
// --- Strategy + backtest types (v2) ---
export type BacktestRunStatus = 'running' | 'completed' | 'failed';
export interface BacktestTrade {
symbol: string;
entry_at: string;
entry_price: number;
exit_at: string | null;
exit_price: number | null;
qty: number;
pnl_usd: number | null;
pnl_pct: number | null;
holding_days_actual: number | null;
}
export interface BacktestMetrics {
total_return_pct: number;
annualized_return_pct: number | null;
sharpe_ratio: number | null;
max_drawdown_pct: number | null;
win_rate: number | null;
trade_count: number;
alpha_vs_spy_pct: number | null;
beta_vs_spy: number | null;
winners: number | null;
losers: number | null;
best_trade_pct: number | null;
worst_trade_pct: number | null;
}
export interface BacktestRun {
run_uuid: string;
status: BacktestRunStatus;
started_at: string;
finished_at: string | null;
trigger_source: 'manual' | 'scheduled';
params_json: Record<string, unknown>;
metrics_json: BacktestMetrics | null;
error_message: string | null;
}
export interface BacktestRunDetail extends BacktestRun {
trades: BacktestTrade[];
equity_curve_json: Array<{ timestamp: string; value: number }> | null;
benchmark_curve_json: Array<{ timestamp: string; value: number }> | null;
}
export type BridgeStatus =
| 'emitted'
| 'skipped_non_tradable'
| 'skipped_blocklist'
| 'skipped_caps'
| 'deferred'
| 'broker_rejected'
| 'dry_run';
export interface StrategyTicker {
symbol: string;
latest_action: TickerAction;
latest_conviction: number;
mention_count: number;
last_mention_at: string;
bridge_status: BridgeStatus | null;
is_held: boolean;
current_price: number | null;
unrealized_pnl_pct: number | null;
}
export interface EquityCurvePoint {
timestamp: string;
value: number;
}
export interface StrategyEquityCurve {
strategy: EquityCurvePoint[];
benchmark: EquityCurvePoint[] | null;
}
export interface StrategyPerformance {
total_return_pct: number;
annualized_return_pct: number | null;
sharpe_ratio: number | null;
max_drawdown_pct: number | null;
win_rate: number | null;
trade_count: number;
alpha_vs_spy_pct: number | null;
open_positions: number;
last_backtest_at: string | null;
}