573 lines
22 KiB
TypeScript
573 lines
22 KiB
TypeScript
import { useState } from 'react';
|
|
import { Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
|
|
import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
|
|
import type { CanonicalMetrics } from '@stock-bot/types';
|
|
import { actionClass } from '@/components/ui/formStyles';
|
|
import { downloadJsonText } from '@/utils/downloadJsonText';
|
|
import { DatasetDownload } from './DatasetDownload';
|
|
|
|
const tableClass = 'w-full text-sm text-left border-collapse';
|
|
const cell = 'p-2 border-b border-border align-top';
|
|
export function canonicalTime(timestamp: number): string {
|
|
const date = new Date(timestamp);
|
|
return Number.isFinite(date.getTime()) ? date.toISOString() : `${timestamp} ms since Unix epoch`;
|
|
}
|
|
function calendarDuration(milliseconds: string): string {
|
|
let remaining = BigInt(milliseconds);
|
|
const parts: string[] = [];
|
|
for (const [size, unit] of [
|
|
[86_400_000n, 'day'],
|
|
[3_600_000n, 'hour'],
|
|
[60_000n, 'minute'],
|
|
[1000n, 'second'],
|
|
[1n, 'millisecond'],
|
|
] as const) {
|
|
const count = remaining / size;
|
|
remaining %= size;
|
|
if (count > 0n) {
|
|
parts.push(`${count} ${unit}${count === 1n ? '' : 's'}`);
|
|
}
|
|
}
|
|
return parts.join(', ') || '0 seconds';
|
|
}
|
|
const reasonText = (reason: string | undefined) => reason?.replace(/-/g, ' ') ?? 'not reported';
|
|
|
|
function RunResultDownload({ result }: { result: CanonicalRunResult }) {
|
|
const [error, setError] = useState('');
|
|
const download = () => {
|
|
setError('');
|
|
try {
|
|
downloadJsonText(JSON.stringify(result), `run-${result.runId}.json`);
|
|
} catch (cause) {
|
|
setError(cause instanceof Error ? cause.message : 'Could not download run result');
|
|
}
|
|
};
|
|
return (
|
|
<div className="space-y-2">
|
|
<button type="button" className={actionClass} onClick={download}>
|
|
{error ? 'Retry run result download' : 'Download run result'}
|
|
</button>
|
|
{error && (
|
|
<p role="alert" className="text-error text-sm">
|
|
{error}
|
|
</p>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
const metricFields: { key: keyof CanonicalMetrics; label: string; percentage?: boolean }[] = [
|
|
{ key: 'totalReturn', label: 'Total return', percentage: true },
|
|
{ key: 'cagr', label: 'CAGR', percentage: true },
|
|
{ key: 'maxDrawdown', label: 'Sampled maximum drawdown', percentage: true },
|
|
{ key: 'exposureTime', label: 'Exposure time', percentage: true },
|
|
{ key: 'volatility', label: 'Annualized volatility', percentage: true },
|
|
{ key: 'downsideDeviation', label: 'Downside deviation', percentage: true },
|
|
{ key: 'sharpeRatio', label: 'Sharpe ratio' },
|
|
{ key: 'sortinoRatio', label: 'Sortino ratio' },
|
|
{ key: 'var95', label: 'Value at risk (95%)', percentage: true },
|
|
{ key: 'cvar95', label: 'Conditional value at risk (95%)', percentage: true },
|
|
{ key: 'var99', label: 'Value at risk (99%)', percentage: true },
|
|
{ key: 'roundTripCount', label: 'Completed round trips' },
|
|
{ key: 'winRate', label: 'Win rate', percentage: true },
|
|
{ key: 'profitFactor', label: 'Profit factor' },
|
|
{ key: 'avgWin', label: 'Average win' },
|
|
{ key: 'avgLoss', label: 'Average loss' },
|
|
{ key: 'alpha', label: 'Alpha' },
|
|
{ key: 'beta', label: 'Beta' },
|
|
{ key: 'informationRatio', label: 'Information ratio' },
|
|
];
|
|
export function CanonicalResults({
|
|
result,
|
|
fillsOnly = false,
|
|
}: {
|
|
result: CanonicalRunResult;
|
|
fillsOnly?: boolean;
|
|
}) {
|
|
const [showCurve, setShowCurve] = useState(false);
|
|
const { financial, analytics, request } = result;
|
|
const valuation = financial.projection.valuation;
|
|
const currency = financial.view.portfolio.baseCurrency;
|
|
const risk = financial.view.risk;
|
|
const riskPolicy = financial.policy.matching.risk;
|
|
const samples = [
|
|
{
|
|
timestamp: financial.reporting.tradeStart,
|
|
equity: financial.reporting.initialEquity,
|
|
label: 'Initial equity',
|
|
partial: false,
|
|
},
|
|
...financial.reporting.sessions.map(sample => ({
|
|
timestamp: sample.periodEnd,
|
|
equity: sample.equity,
|
|
label: sample.session.sessionId,
|
|
partial: sample.partialStart || sample.partialEnd,
|
|
})),
|
|
];
|
|
if (fillsOnly) {
|
|
return <CanonicalFills result={result} />;
|
|
}
|
|
return (
|
|
<div className="space-y-5 text-text-primary pb-4">
|
|
<section
|
|
aria-label="Canonical result provenance"
|
|
className="p-4 border border-border rounded-lg space-y-3"
|
|
>
|
|
<h3 className="font-semibold">Canonical research result</h3>
|
|
<p className="text-sm text-text-secondary">
|
|
Rust financial simulation ·{' '}
|
|
{request.strategy.origin === 'candidate'
|
|
? 'isolated TypeScript candidate'
|
|
: 'retained TypeScript built-in'}
|
|
. Completion does not establish strategy profitability or authorize trading.
|
|
</p>
|
|
{request.strategy.origin === 'candidate' && (
|
|
<p className="text-sm break-all">
|
|
Sandbox {request.strategy.execution.imageId} · Author-declared warmup{' '}
|
|
{request.strategy.package.execution?.warmupBars} bars. Candidate code is unverified;
|
|
retained seeds and inputs support an actual reproduction comparison.
|
|
</p>
|
|
)}
|
|
<dl className="grid gap-3 text-sm sm:grid-cols-2 break-all">
|
|
<div>
|
|
<dt>Run</dt>
|
|
<dd>{result.runId}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Strategy version</dt>
|
|
<dd>{request.strategy.versionId}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Dataset hash</dt>
|
|
<dd>{request.datasetHash}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Executed strategy artifact SHA256</dt>
|
|
<dd>{request.strategy.package.artifact.sha256}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Native engine SHA256</dt>
|
|
<dd>{request.build.engineBinarySha256}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Worker SHA256</dt>
|
|
<dd>{request.build.workerSha256}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Engine wrapper SHA256</dt>
|
|
<dd>{request.build.engineWrapperSha256}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Dependency lock SHA256</dt>
|
|
<dd>{request.build.dependencyLockSha256}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Financial / reporting versions</dt>
|
|
<dd>
|
|
{financial.financialVersion} / {financial.reportingVersion}
|
|
</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Runtime</dt>
|
|
<dd>
|
|
{request.build.runtime} {request.build.runtimeVersion} · {request.build.platform}/
|
|
{request.build.arch}
|
|
</dd>
|
|
</div>
|
|
</dl>
|
|
<RunResultDownload key={result.runId} result={result} />
|
|
<DatasetDownload hash={request.datasetHash} />
|
|
<details>
|
|
<summary className="cursor-pointer">Immutable configuration and reporting policy</summary>
|
|
<pre className="mt-2 text-xs overflow-auto max-h-96">
|
|
{JSON.stringify(
|
|
{
|
|
name: request.name,
|
|
strategy: {
|
|
familyId: request.strategy.familyId,
|
|
versionId: request.strategy.versionId,
|
|
origin: request.strategy.origin,
|
|
reviewId: request.strategy.reviewId,
|
|
program: request.strategy.package.program,
|
|
selection: request.strategy.selection,
|
|
source: request.strategy.package.source,
|
|
dependencyLockSha256: request.strategy.package.dependencyLock.sha256,
|
|
},
|
|
datasetHash: request.datasetHash,
|
|
policy: request.policy,
|
|
analyticsPolicy: analytics.policy,
|
|
build: request.build,
|
|
modelArtifacts: request.modelArtifacts,
|
|
},
|
|
null,
|
|
2
|
|
)}
|
|
</pre>
|
|
</details>
|
|
<ul className="list-disc pl-5 text-sm text-text-secondary space-y-1">
|
|
{[...financial.limitations, ...financial.modelLimitations].map((limitation, index) => (
|
|
<li key={index}>{limitation}</li>
|
|
))}
|
|
</ul>
|
|
</section>
|
|
<section className="space-y-3">
|
|
<h3 className="font-semibold">Authoritative terminal account ({currency})</h3>
|
|
<dl className="grid gap-3 sm:grid-cols-3 text-sm">
|
|
{(
|
|
[
|
|
'cash',
|
|
'markedHoldings',
|
|
'equity',
|
|
'remainingCost',
|
|
'realizedGrossPnl',
|
|
'unrealizedPnl',
|
|
'fees',
|
|
] as const
|
|
).map(key => (
|
|
<div key={key}>
|
|
<dt>
|
|
{
|
|
{
|
|
cash: 'Cash',
|
|
markedHoldings: 'Marked holdings',
|
|
equity: 'Equity',
|
|
remainingCost: 'Remaining cost',
|
|
realizedGrossPnl: 'Gross realized P&L',
|
|
unrealizedPnl: 'Unrealized P&L',
|
|
fees: 'Fees',
|
|
}[key]
|
|
}
|
|
</dt>
|
|
<dd className="font-mono">{valuation[key]}</dd>
|
|
</div>
|
|
))}
|
|
</dl>
|
|
<p className="text-xs text-text-secondary">
|
|
Decimal amounts come directly from Rust. Gross realized P&L excludes separately reported
|
|
fees. Holdings are valued using the last available marks.
|
|
</p>
|
|
</section>
|
|
<section aria-label="Final risk state" className="space-y-3">
|
|
<h3 className="font-semibold">Final risk state</h3>
|
|
<dl className="grid gap-3 sm:grid-cols-3 text-sm">
|
|
{[
|
|
{ label: 'Daily-loss halt', active: risk.dailyHalted },
|
|
{ label: 'Drawdown halt', active: risk.drawdownHalted },
|
|
].map(({ label, active }) => (
|
|
<div key={label}>
|
|
<dt>{label}</dt>
|
|
<dd className={active ? 'font-medium text-warning' : 'text-text-secondary'}>
|
|
{active ? 'Active at end' : 'Inactive at end'}
|
|
</dd>
|
|
</div>
|
|
))}
|
|
{[
|
|
['Daily-loss limit', riskPolicy.maxDailyLoss],
|
|
['Drawdown limit', riskPolicy.maxDrawdownAmount],
|
|
['Daily equity baseline', risk.dailyBaseline],
|
|
['Peak equity', risk.peakEquity],
|
|
].map(([label, value]) => (
|
|
<div key={label}>
|
|
<dt>{label}</dt>
|
|
<dd className="font-mono">{value}</dd>
|
|
</div>
|
|
))}
|
|
<div>
|
|
<dt>Risk session</dt>
|
|
<dd>{risk.riskSession.sessionId}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Risk calendar</dt>
|
|
<dd className="break-all">
|
|
{risk.riskSession.calendarId} · revision {risk.riskSession.calendarRevision}
|
|
</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Risk session start (UTC)</dt>
|
|
<dd>{canonicalTime(risk.riskSession.startsAt)}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Last processed risk event (UTC)</dt>
|
|
<dd>{canonicalTime(risk.lastEventTime)}</dd>
|
|
</div>
|
|
</dl>
|
|
<p className="text-xs text-text-secondary">
|
|
Amounts are in {currency} and come from the retained Rust state and policy. An active halt
|
|
blocks risk-increasing orders; exposure-reducing orders remain permitted subject to other
|
|
checks. Inactive at end describes only this snapshot, not whether earlier halts or other
|
|
rejections occurred.
|
|
</p>
|
|
<p className="text-xs text-text-secondary">
|
|
Daily-loss state can reset at an account risk-session boundary. Price recovery alone does
|
|
not clear a latched drawdown halt. The last processed risk event is not the first halt
|
|
time; this report does not contain halt history or rejection counts.
|
|
</p>
|
|
</section>
|
|
<section className="space-y-3">
|
|
<h3 className="font-semibold">Canonical metrics</h3>
|
|
<dl aria-label="Evaluation horizon" className="grid gap-3 sm:grid-cols-3 text-sm">
|
|
<div>
|
|
<dt>Evaluation start (UTC)</dt>
|
|
<dd>{canonicalTime(financial.reporting.tradeStart)}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Evaluation end (UTC, exclusive)</dt>
|
|
<dd>{canonicalTime(financial.reporting.tradeEnd)}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Elapsed calendar duration</dt>
|
|
<dd>{calendarDuration(financial.reporting.elapsedMs)}</dd>
|
|
</div>
|
|
</dl>
|
|
<p className="text-sm text-text-secondary">
|
|
{analytics.fillCount} fills · {analytics.completePeriodCount} complete periods ·{' '}
|
|
{analytics.periodicSampleCount} statistical samples. Returns use fractions, displayed as
|
|
percentages. Drawdown is sampled at period ends and the terminal boundary, not every
|
|
intraday price. Exposure uses elapsed calendar time.
|
|
</p>
|
|
<dl className="grid gap-3 sm:grid-cols-3 text-sm">
|
|
{metricFields.map(field => {
|
|
const value = analytics.metrics[field.key];
|
|
return (
|
|
<div key={field.key}>
|
|
<dt>{field.label}</dt>
|
|
<dd title={value === null ? undefined : String(value)}>
|
|
{value === null
|
|
? `Unavailable — ${reasonText(analytics.unavailable[field.key])}`
|
|
: field.percentage
|
|
? `${(value * 100).toFixed(2)}%`
|
|
: value.toFixed(2)}
|
|
</dd>
|
|
{field.key === 'cagr' && (
|
|
<dd className="text-xs text-text-secondary">
|
|
CAGR extrapolates this evaluation interval to a 365-calendar-day year, including
|
|
nontrading time. It is not an observed annual return or a forecast.
|
|
</dd>
|
|
)}
|
|
</div>
|
|
);
|
|
})}
|
|
</dl>
|
|
<p className="text-xs text-text-secondary">
|
|
Period calendar: {analytics.policy.calendarId}, revision{' '}
|
|
{analytics.policy.calendarRevision}. Annualization for periodic statistics:{' '}
|
|
{analytics.policy.periodsPerYear} periods/year. Risk-free rate:{' '}
|
|
{analytics.policy.annualRiskFreeRate === null
|
|
? 'unknown'
|
|
: `${(analytics.policy.annualRiskFreeRate * 100).toFixed(2)}%`}
|
|
. Partial periods are visible but excluded from periodic statistics. Per-period mark
|
|
freshness is not certified.
|
|
</p>
|
|
</section>
|
|
<section className="space-y-3">
|
|
<h3 className="font-semibold">Equity samples</h3>
|
|
<button type="button" className={actionClass} onClick={() => setShowCurve(value => !value)}>
|
|
{showCurve ? 'Hide equity curve' : 'Show equity curve'}
|
|
</button>
|
|
{showCurve && (
|
|
<div aria-label="Canonical equity curve" className="h-64">
|
|
<ResponsiveContainer width="100%" height="100%">
|
|
<LineChart
|
|
data={samples.map(sample => ({
|
|
timestamp: sample.timestamp,
|
|
equity: Number(sample.equity),
|
|
}))}
|
|
>
|
|
<XAxis
|
|
type="number"
|
|
dataKey="timestamp"
|
|
domain={['dataMin', 'dataMax']}
|
|
tickFormatter={canonicalTime}
|
|
/>
|
|
<YAxis domain={['auto', 'auto']} />
|
|
<Tooltip labelFormatter={value => canonicalTime(Number(value))} />
|
|
<Line
|
|
type="linear"
|
|
dataKey="equity"
|
|
stroke="#3b82f6"
|
|
dot={false}
|
|
isAnimationActive={false}
|
|
/>
|
|
</LineChart>
|
|
</ResponsiveContainer>
|
|
<p className="text-xs text-text-muted">
|
|
The plot uses approximate numbers; exact sampled equity remains in the table.
|
|
</p>
|
|
</div>
|
|
)}
|
|
<div className="overflow-auto">
|
|
<table className={tableClass}>
|
|
<thead>
|
|
<tr>
|
|
<th className={cell}>Timestamp (UTC)</th>
|
|
<th className={cell}>Sample</th>
|
|
<th className={cell}>Equity ({currency})</th>
|
|
<th className={cell}>Period</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{samples.map((sample, index) => (
|
|
<tr key={index}>
|
|
<td className={cell}>{canonicalTime(sample.timestamp)}</td>
|
|
<td className={cell}>{sample.label}</td>
|
|
<td className={`${cell} font-mono`}>{sample.equity}</td>
|
|
<td className={cell}>
|
|
{index === 0 ? 'Initial' : sample.partial ? 'Partial' : 'Complete'}
|
|
</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</section>
|
|
<section className="space-y-3">
|
|
<h3 className="font-semibold">Owner positions</h3>
|
|
<p className="text-sm text-text-secondary">
|
|
These are owner books, not reconstructed round trips. Per-position marks, average prices
|
|
and unrealized P&L are unavailable in this report.
|
|
</p>
|
|
{!financial.view.portfolio.positions.length ? (
|
|
<p>No owner positions recorded.</p>
|
|
) : (
|
|
<div className="overflow-auto">
|
|
<table className={tableClass}>
|
|
<thead>
|
|
<tr>
|
|
{[
|
|
'Owner',
|
|
'Asset',
|
|
'Quantity',
|
|
`Remaining cost (${currency})`,
|
|
`Gross realized P&L (${currency})`,
|
|
].map(label => (
|
|
<th className={cell} key={label}>
|
|
{label}
|
|
</th>
|
|
))}
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{financial.view.portfolio.positions.map(position => (
|
|
<tr key={`${position.ownerId}:${position.instrumentId}`}>
|
|
<td className={cell}>{position.ownerId}</td>
|
|
<td className={cell}>{position.instrumentId}</td>
|
|
<td className={`${cell} font-mono`}>{position.quantity}</td>
|
|
<td className={`${cell} font-mono`}>{position.remainingCost}</td>
|
|
<td className={`${cell} font-mono`}>{position.realizedGrossPnl}</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
)}
|
|
<h4 className="font-medium">Owner valuations ({currency})</h4>
|
|
<div className="overflow-auto">
|
|
<table className={tableClass}>
|
|
<thead>
|
|
<tr>
|
|
{[
|
|
'Owner',
|
|
'Initial allocation',
|
|
'Marked holdings',
|
|
'Remaining cost',
|
|
'Gross realized P&L',
|
|
'Unrealized P&L',
|
|
'Fees',
|
|
'Equity contribution',
|
|
].map(label => (
|
|
<th className={cell} key={label}>
|
|
{label}
|
|
</th>
|
|
))}
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{valuation.owners.map(owner => (
|
|
<tr key={owner.ownerId}>
|
|
<td className={cell}>{owner.ownerId}</td>
|
|
{(
|
|
[
|
|
'initialCapital',
|
|
'markedHoldings',
|
|
'remainingCost',
|
|
'realizedGrossPnl',
|
|
'unrealizedPnl',
|
|
'fees',
|
|
'equityContribution',
|
|
] as const
|
|
).map(key => (
|
|
<td className={`${cell} font-mono`} key={key}>
|
|
{owner[key]}
|
|
</td>
|
|
))}
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</section>
|
|
</div>
|
|
);
|
|
}
|
|
function CanonicalFills({ result }: { result: CanonicalRunResult }) {
|
|
const fills = result.financial.projection.fills;
|
|
return (
|
|
<section className="space-y-4 text-text-primary">
|
|
<h3 className="font-semibold">Canonical fills ({result.analytics.fillCount})</h3>
|
|
<p className="text-sm text-text-secondary">
|
|
Actual Rust fill postings. A fill is not a completed round trip; gross realized P&L and fees
|
|
are separate. Win rate and round-trip statistics are unavailable.
|
|
</p>
|
|
{!fills.length ? (
|
|
<p role="status">No fills were executed in this completed run.</p>
|
|
) : (
|
|
<div className="overflow-auto">
|
|
<table className={tableClass}>
|
|
<thead>
|
|
<tr>
|
|
{[
|
|
'Time (UTC)',
|
|
'Owner',
|
|
'Asset',
|
|
'Side',
|
|
'Quantity',
|
|
'Price',
|
|
'Fee',
|
|
'Released basis',
|
|
'Gross realized P&L',
|
|
'Order / fill / decision',
|
|
].map(label => (
|
|
<th className={cell} key={label}>
|
|
{label}
|
|
</th>
|
|
))}
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{fills.map(fill => (
|
|
<tr key={`${fill.ownerId}:${fill.fillId}`}>
|
|
<td className={cell}>{canonicalTime(fill.eventTime)}</td>
|
|
<td className={cell}>{fill.ownerId}</td>
|
|
<td className={cell}>{fill.instrumentId}</td>
|
|
<td className={cell}>{fill.side}</td>
|
|
<td className={`${cell} font-mono`}>{fill.quantity}</td>
|
|
<td className={`${cell} font-mono`}>{fill.price}</td>
|
|
<td className={`${cell} font-mono`}>{fill.fee.amount}</td>
|
|
<td className={`${cell} font-mono`}>{fill.releasedBasis}</td>
|
|
<td className={`${cell} font-mono`}>{fill.realizedGrossPnl}</td>
|
|
<td className={`${cell} text-xs break-all`}>
|
|
{fill.orderId}
|
|
<br />
|
|
{fill.fillId}
|
|
<br />
|
|
{fill.decision.decisionId}
|
|
</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
)}
|
|
</section>
|
|
);
|
|
}
|