feat(research): run retained strategies through durable canonical engine
This commit is contained in:
parent
d929db707a
commit
618fb9e33c
58 changed files with 6596 additions and 779 deletions
|
|
@ -0,0 +1,438 @@
|
|||
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 '@/features/strategies/components/StrategyParameterForm';
|
||||
|
||||
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`;
|
||||
}
|
||||
const reasonText = (reason: string | undefined) => reason?.replace(/-/g, ' ') ?? 'not reported';
|
||||
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 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 · retained TypeScript built-in. Completion does not establish
|
||||
strategy profitability or authorize trading.
|
||||
</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>
|
||||
<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 className="space-y-3">
|
||||
<h3 className="font-semibold">Canonical metrics</h3>
|
||||
<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>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</dl>
|
||||
<p className="text-xs text-text-secondary">
|
||||
Period calendar: {analytics.policy.calendarId}, revision{' '}
|
||||
{analytics.policy.calendarRevision}. Annualization: {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>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,610 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
canonicalResearchSettingsSchema,
|
||||
type CanonicalDatasetCatalogEntry,
|
||||
type CanonicalResearchSettings,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { actionClass, fieldClass } from '@/features/strategies/components/StrategyParameterForm';
|
||||
import {
|
||||
StrategySelection,
|
||||
type CatalogSelection,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
import {
|
||||
confirmDiscard,
|
||||
useUnsavedWarning,
|
||||
} from '@/features/strategies/components/useUnsavedWarning';
|
||||
import {
|
||||
backtestApiV2,
|
||||
type Backtest,
|
||||
type CreateBacktestRequest,
|
||||
} from '../services/backtestApiV2';
|
||||
|
||||
type PolicyKey = Exclude<keyof CanonicalResearchSettings, 'version'>;
|
||||
const policyFields: {
|
||||
key: PolicyKey;
|
||||
label: string;
|
||||
group: string;
|
||||
kind: 'decimal' | 'number' | 'nullable';
|
||||
description: string;
|
||||
}[] = [
|
||||
{
|
||||
key: 'ownerBudget',
|
||||
label: 'Owner budget',
|
||||
group: 'Capital allocation',
|
||||
kind: 'decimal',
|
||||
description: 'USD allocated to this strategy; it cannot exceed initial capital.',
|
||||
},
|
||||
{
|
||||
key: 'feeRate',
|
||||
label: 'Fee rate',
|
||||
group: 'Execution',
|
||||
kind: 'decimal',
|
||||
description: 'Fraction of fill notional charged once per fill. 0.001 means 0.1%.',
|
||||
},
|
||||
{
|
||||
key: 'halfSpreadRate',
|
||||
label: 'Half-spread rate',
|
||||
group: 'Execution',
|
||||
kind: 'decimal',
|
||||
description: 'Fractional price adjustment for one side of the simulated spread.',
|
||||
},
|
||||
{
|
||||
key: 'slippageRate',
|
||||
label: 'Slippage rate',
|
||||
group: 'Execution',
|
||||
kind: 'decimal',
|
||||
description: 'Additional adverse price fraction per fill.',
|
||||
},
|
||||
{
|
||||
key: 'participationRate',
|
||||
label: 'Volume participation rate',
|
||||
group: 'Execution',
|
||||
kind: 'decimal',
|
||||
description:
|
||||
'Maximum fraction of previously available completed-bar volume used for liquidity; this is not contemporaneous liquidity.',
|
||||
},
|
||||
{
|
||||
key: 'latencyMs',
|
||||
label: 'Order latency (ms)',
|
||||
group: 'Execution',
|
||||
kind: 'number',
|
||||
description: 'Nonnegative delay before an order becomes eligible.',
|
||||
},
|
||||
{
|
||||
key: 'maxOrderQuantity',
|
||||
label: 'Maximum order quantity',
|
||||
group: 'Financial constraints',
|
||||
kind: 'decimal',
|
||||
description: 'Absolute asset quantity per order.',
|
||||
},
|
||||
{
|
||||
key: 'maxPositionQuantity',
|
||||
label: 'Maximum position quantity',
|
||||
group: 'Financial constraints',
|
||||
kind: 'decimal',
|
||||
description: 'Absolute asset quantity held by the strategy.',
|
||||
},
|
||||
{
|
||||
key: 'maxSymbolExposure',
|
||||
label: 'Maximum asset exposure',
|
||||
group: 'Financial constraints',
|
||||
kind: 'decimal',
|
||||
description: 'USD notional exposure to the selected asset.',
|
||||
},
|
||||
{
|
||||
key: 'maxGrossExposure',
|
||||
label: 'Maximum gross exposure',
|
||||
group: 'Financial constraints',
|
||||
kind: 'decimal',
|
||||
description: 'USD gross exposure across the account.',
|
||||
},
|
||||
{
|
||||
key: 'maxDailyLoss',
|
||||
label: 'Maximum risk-period loss',
|
||||
group: 'Financial constraints',
|
||||
kind: 'decimal',
|
||||
description:
|
||||
'USD loss from the declared risk-period baseline; zero is an active zero threshold.',
|
||||
},
|
||||
{
|
||||
key: 'maxDrawdownAmount',
|
||||
label: 'Maximum drawdown amount',
|
||||
group: 'Financial constraints',
|
||||
kind: 'decimal',
|
||||
description: 'USD decline from peak equity; zero is an active zero threshold.',
|
||||
},
|
||||
{
|
||||
key: 'maxMarkAgeMs',
|
||||
label: 'Maximum mark age (ms)',
|
||||
group: 'Financial constraints',
|
||||
kind: 'number',
|
||||
description: 'Maximum age of an available mark for financial admission.',
|
||||
},
|
||||
{
|
||||
key: 'seed',
|
||||
label: 'Random seed',
|
||||
group: 'Research and reporting',
|
||||
kind: 'number',
|
||||
description: 'Integer seed retained with the run.',
|
||||
},
|
||||
{
|
||||
key: 'periodsPerYear',
|
||||
label: 'Reporting periods per year',
|
||||
group: 'Research and reporting',
|
||||
kind: 'number',
|
||||
description: 'Explicit annualization convention for complete declared risk periods.',
|
||||
},
|
||||
{
|
||||
key: 'annualRiskFreeRate',
|
||||
label: 'Annual risk-free rate',
|
||||
group: 'Research and reporting',
|
||||
kind: 'nullable',
|
||||
description: 'Fraction per year. Leave blank for unknown; zero is an explicit assumption.',
|
||||
},
|
||||
];
|
||||
type RawPolicy = Record<PolicyKey, string>;
|
||||
function defaults(capital: number): CanonicalResearchSettings {
|
||||
return {
|
||||
version: 1,
|
||||
ownerBudget: String(capital),
|
||||
feeRate: '0.001',
|
||||
halfSpreadRate: '0.0005',
|
||||
slippageRate: '0.0005',
|
||||
participationRate: '0.1',
|
||||
latencyMs: 0,
|
||||
maxOrderQuantity: '1000000',
|
||||
maxPositionQuantity: '1000000',
|
||||
maxSymbolExposure: String(capital),
|
||||
maxGrossExposure: String(capital),
|
||||
maxDailyLoss: '1000',
|
||||
maxDrawdownAmount: '2000',
|
||||
maxMarkAgeMs: 604800000,
|
||||
seed: 1,
|
||||
periodsPerYear: 252,
|
||||
annualRiskFreeRate: null,
|
||||
};
|
||||
}
|
||||
function initialPolicy(backtest: Backtest): RawPolicy {
|
||||
const input = backtest.config.canonical;
|
||||
const source = input && typeof input === 'object' ? input : defaults(backtest.initialCapital);
|
||||
return Object.fromEntries(
|
||||
policyFields.map(({ key }) => {
|
||||
const value = Reflect.get(source, key);
|
||||
return [key, value === undefined || value === null ? '' : String(value)];
|
||||
})
|
||||
) as RawPolicy;
|
||||
}
|
||||
export function canonicalDatasetFields(entry: CanonicalDatasetCatalogEntry) {
|
||||
const manifest = entry.manifest;
|
||||
if (
|
||||
!entry.available ||
|
||||
!manifest ||
|
||||
manifest.version !== 2 ||
|
||||
manifest.hash !== entry.hash ||
|
||||
manifest.eligibility !== 'eligible' ||
|
||||
manifest.executionSeries.length !== 1
|
||||
) {
|
||||
throw new Error(entry.reason ?? 'Choose an eligible single-asset canonical dataset.');
|
||||
}
|
||||
const execution = manifest.executionSeries[0];
|
||||
if (!execution) {
|
||||
throw new Error('Dataset execution series is missing.');
|
||||
}
|
||||
const series = manifest.series.find(
|
||||
item => item.id === execution.seriesId && item.instrumentId === execution.instrumentId
|
||||
);
|
||||
if (!series) {
|
||||
throw new Error('Dataset execution series is unavailable.');
|
||||
}
|
||||
const startDate = new Date(manifest.bounds.tradeStart).toISOString();
|
||||
const endDate = new Date(manifest.bounds.tradeEnd).toISOString();
|
||||
return {
|
||||
symbols: [execution.instrumentId],
|
||||
startDate,
|
||||
endDate,
|
||||
warmupStart: new Date(manifest.bounds.warmupStart).toISOString(),
|
||||
dataFrequency: series.interval,
|
||||
};
|
||||
}
|
||||
function parsePolicy(raw: RawPolicy): {
|
||||
settings?: CanonicalResearchSettings;
|
||||
errors: Partial<Record<PolicyKey, string>>;
|
||||
} {
|
||||
const values: Record<string, unknown> = { version: 1 };
|
||||
const errors: Partial<Record<PolicyKey, string>> = {};
|
||||
for (const field of policyFields) {
|
||||
const text = raw[field.key];
|
||||
try {
|
||||
if (field.kind === 'nullable' && text.trim() === '') {
|
||||
values[field.key] = null;
|
||||
} else if (field.kind === 'decimal') {
|
||||
values[field.key] = parseFinancialDecimal(text);
|
||||
} else {
|
||||
if (text.trim() === '' || !Number.isFinite(Number(text))) {
|
||||
throw new Error('Enter a finite number.');
|
||||
}
|
||||
values[field.key] = Number(text);
|
||||
}
|
||||
} catch (cause) {
|
||||
errors[field.key] = cause instanceof Error ? cause.message : 'Invalid value';
|
||||
}
|
||||
}
|
||||
if (Object.keys(errors).length) {
|
||||
return { errors };
|
||||
}
|
||||
const parsed = canonicalResearchSettingsSchema.safeParse(values);
|
||||
if (!parsed.success) {
|
||||
for (const issue of parsed.error.issues) {
|
||||
const key = issue.path[0] as PolicyKey;
|
||||
errors[key] = issue.message;
|
||||
}
|
||||
return { errors };
|
||||
}
|
||||
return { settings: parsed.data, errors };
|
||||
}
|
||||
|
||||
export function CanonicalSetup({
|
||||
backtest,
|
||||
disabled = false,
|
||||
onSave,
|
||||
onClose,
|
||||
}: {
|
||||
backtest: Backtest;
|
||||
disabled?: boolean;
|
||||
onSave: (request: CreateBacktestRequest) => Promise<void>;
|
||||
onClose?: () => void;
|
||||
}) {
|
||||
const [name, setName] = useState(backtest.name);
|
||||
const [capital, setCapital] = useState(String(backtest.initialCapital));
|
||||
const [raw, setRaw] = useState(() => initialPolicy(backtest));
|
||||
const [hash, setHash] = useState(
|
||||
typeof backtest.config.canonical === 'object' && typeof backtest.config.datasetHash === 'string'
|
||||
? backtest.config.datasetHash
|
||||
: ''
|
||||
);
|
||||
const [selection, setSelection] = useState<CatalogSelection>({
|
||||
strategyVersionId: backtest.strategyVersionId,
|
||||
strategyParameters: backtest.strategyParameters,
|
||||
});
|
||||
const [strategyValid, setStrategyValid] = useState(false);
|
||||
const [epoch, setEpoch] = useState(0);
|
||||
const [catalog, setCatalog] = useState<CanonicalDatasetCatalogEntry[]>([]);
|
||||
const [dataset, setDataset] = useState<CanonicalDatasetCatalogEntry | null>(null);
|
||||
const [catalogLoading, setCatalogLoading] = useState(true);
|
||||
const [datasetLoading, setDatasetLoading] = useState(false);
|
||||
const [catalogError, setCatalogError] = useState<string | null>(null);
|
||||
const [datasetError, setDatasetError] = useState<string | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const authoritative = useRef(backtest);
|
||||
const pending = useRef(false);
|
||||
const active = useRef(true);
|
||||
useUnsavedWarning(dirty);
|
||||
useEffect(() => {
|
||||
active.current = true;
|
||||
return () => {
|
||||
active.current = false;
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (backtest === authoritative.current) {
|
||||
return;
|
||||
}
|
||||
authoritative.current = backtest;
|
||||
setName(backtest.name);
|
||||
setCapital(String(backtest.initialCapital));
|
||||
setRaw(initialPolicy(backtest));
|
||||
setHash(
|
||||
typeof backtest.config.canonical === 'object' &&
|
||||
typeof backtest.config.datasetHash === 'string'
|
||||
? backtest.config.datasetHash
|
||||
: ''
|
||||
);
|
||||
setSelection({
|
||||
strategyVersionId: backtest.strategyVersionId,
|
||||
strategyParameters: backtest.strategyParameters,
|
||||
});
|
||||
setStrategyValid(false);
|
||||
setEpoch(value => value + 1);
|
||||
setDirty(false);
|
||||
setError(null);
|
||||
}, [backtest]);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setCatalogLoading(true);
|
||||
setCatalogError(null);
|
||||
void backtestApiV2
|
||||
.listCanonicalDatasets(controller.signal)
|
||||
.then(entries => {
|
||||
if (!controller.signal.aborted) {
|
||||
setCatalog(entries);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
setCatalogError(cause.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setCatalogLoading(false);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [retry]);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setDataset(null);
|
||||
setDatasetError(null);
|
||||
setDatasetLoading(Boolean(hash));
|
||||
if (hash) {
|
||||
void backtestApiV2
|
||||
.canonicalDataset(hash, controller.signal)
|
||||
.then(entry => {
|
||||
if (!controller.signal.aborted) {
|
||||
if (entry.hash !== hash) {
|
||||
throw new Error('Dataset lookup returned a different hash.');
|
||||
}
|
||||
setDataset(entry);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
setDatasetError(cause.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setDatasetLoading(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
return () => controller.abort();
|
||||
}, [hash, retry]);
|
||||
const parsed = parsePolicy(raw);
|
||||
let selectedFields: ReturnType<typeof canonicalDatasetFields> | undefined;
|
||||
let compatibilityError: string | null = null;
|
||||
if (dataset && dataset.hash === hash) {
|
||||
try {
|
||||
selectedFields = canonicalDatasetFields(dataset);
|
||||
} catch (cause) {
|
||||
compatibilityError = cause instanceof Error ? cause.message : 'Dataset is unsupported';
|
||||
}
|
||||
}
|
||||
const validCapital =
|
||||
capital.trim() !== '' && Number.isFinite(Number(capital)) && Number(capital) > 0;
|
||||
const locked = disabled || saving;
|
||||
const valid = Boolean(
|
||||
name.trim() &&
|
||||
validCapital &&
|
||||
selectedFields &&
|
||||
parsed.settings &&
|
||||
selection.strategyVersionId &&
|
||||
strategyValid
|
||||
);
|
||||
const save = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (locked || pending.current || !valid || !selectedFields || !parsed.settings) {
|
||||
return;
|
||||
}
|
||||
pending.current = true;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await onSave({
|
||||
name,
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: selection.strategyVersionId,
|
||||
strategyParameters: selection.strategyParameters,
|
||||
symbols: selectedFields.symbols,
|
||||
startDate: selectedFields.startDate,
|
||||
endDate: selectedFields.endDate,
|
||||
initialCapital: Number(capital),
|
||||
config: {
|
||||
datasetHash: hash,
|
||||
dataFrequency: selectedFields.dataFrequency,
|
||||
canonical: parsed.settings,
|
||||
},
|
||||
});
|
||||
if (active.current) {
|
||||
setDirty(false);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (active.current) {
|
||||
setError(cause instanceof Error ? cause.message : 'Could not save canonical setup');
|
||||
}
|
||||
} finally {
|
||||
pending.current = false;
|
||||
if (active.current) {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const options =
|
||||
dataset && !catalog.some(entry => entry.hash === dataset.hash)
|
||||
? [dataset, ...catalog]
|
||||
: catalog;
|
||||
return (
|
||||
<form
|
||||
className="space-y-5"
|
||||
onSubmit={event => void save(event)}
|
||||
onChange={() => setDirty(true)}
|
||||
>
|
||||
<h3 className="font-semibold text-text-primary">Canonical research setup</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Review every policy below. Rust enforces accounting, fills and financial limits. This
|
||||
workflow supports one asset and reviewed built-in versions; saving does not start a run.
|
||||
</p>
|
||||
{dirty && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
Unsaved canonical setup. Save or discard before leaving.
|
||||
</p>
|
||||
)}
|
||||
<fieldset disabled={locked} className="space-y-4">
|
||||
<label className="block text-sm">
|
||||
Backtest name
|
||||
<input
|
||||
aria-label="Backtest name"
|
||||
className={fieldClass}
|
||||
value={name}
|
||||
onChange={event => setName(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
Initial capital (USD)
|
||||
<input
|
||||
aria-label="Initial capital (USD)"
|
||||
className={fieldClass}
|
||||
value={capital}
|
||||
onChange={event => setCapital(event.target.value)}
|
||||
inputMode="decimal"
|
||||
/>
|
||||
</label>
|
||||
{!validCapital && (
|
||||
<p role="alert" className="text-error text-sm">
|
||||
Initial capital must be a positive finite number.
|
||||
</p>
|
||||
)}
|
||||
<label className="block text-sm">
|
||||
Canonical dataset
|
||||
<select
|
||||
aria-label="Canonical dataset"
|
||||
className={fieldClass}
|
||||
value={hash}
|
||||
onChange={event => setHash(event.target.value)}
|
||||
>
|
||||
<option value="">Select a retained single-asset dataset</option>
|
||||
{hash && !options.some(entry => entry.hash === hash) && (
|
||||
<option value={hash}>{hash} — retained selection</option>
|
||||
)}
|
||||
{options.map(entry => (
|
||||
<option key={entry.hash} value={entry.hash} disabled={!entry.available}>
|
||||
{entry.hash} —{' '}
|
||||
{entry.manifest?.executionSeries.map(item => item.instrumentId).join(', ') ||
|
||||
'Unknown asset'}
|
||||
{entry.available ? '' : ` (${entry.reason ?? 'Unavailable'})`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{catalogLoading && <p role="status">Loading canonical datasets...</p>}
|
||||
{!catalogLoading && !catalogError && !catalog.length && (
|
||||
<p role="status">
|
||||
No canonical datasets are available. Retain an eligible dataset with explicit sessions
|
||||
and availability before configuring a run.
|
||||
</p>
|
||||
)}
|
||||
{datasetLoading && <p role="status">Loading selected canonical dataset...</p>}
|
||||
{[catalogError, datasetError, compatibilityError].filter(Boolean).map((message, index) => (
|
||||
<p key={index} role="alert" className="text-error text-sm">
|
||||
{message}
|
||||
</p>
|
||||
))}
|
||||
{(catalogError || datasetError || compatibilityError) && (
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
onClick={() => setRetry(value => value + 1)}
|
||||
>
|
||||
Retry canonical datasets
|
||||
</button>
|
||||
)}
|
||||
{hash && !selectedFields && !datasetLoading && (
|
||||
<p className="text-sm text-text-secondary">
|
||||
The selected hash is retained. Saving stays disabled until compatible metadata is
|
||||
available.
|
||||
</p>
|
||||
)}
|
||||
{selectedFields && (
|
||||
<dl aria-label="Canonical dataset bounds" className="grid gap-2 text-sm sm:grid-cols-2">
|
||||
<div>
|
||||
<dt>Execution asset</dt>
|
||||
<dd>{selectedFields.symbols.join(', ')}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Execution interval</dt>
|
||||
<dd>{selectedFields.dataFrequency}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Trading start (UTC)</dt>
|
||||
<dd>{selectedFields.startDate}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Trading end (UTC, exclusive)</dt>
|
||||
<dd>{selectedFields.endDate}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Warmup start (UTC)</dt>
|
||||
<dd>{selectedFields.warmupStart}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
)}
|
||||
<StrategySelection
|
||||
key={epoch}
|
||||
allowArchivedSelection
|
||||
value={selection}
|
||||
onChange={setSelection}
|
||||
onValidityChange={setStrategyValid}
|
||||
disabled={locked}
|
||||
/>
|
||||
{[...new Set(policyFields.map(field => field.group))].map(group => (
|
||||
<section key={group} className="space-y-3 border border-border rounded-md p-3">
|
||||
<h4 className="font-medium text-text-primary">{group}</h4>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
{policyFields
|
||||
.filter(field => field.group === group)
|
||||
.map(field => (
|
||||
<label key={field.key} className="block text-sm text-text-secondary">
|
||||
{field.label}
|
||||
<input
|
||||
aria-label={field.label}
|
||||
className={fieldClass}
|
||||
type="text"
|
||||
inputMode="decimal"
|
||||
value={raw[field.key]}
|
||||
onChange={event =>
|
||||
setRaw(previous => ({ ...previous, [field.key]: event.target.value }))
|
||||
}
|
||||
aria-invalid={Boolean(parsed.errors[field.key])}
|
||||
/>
|
||||
<span className="block text-xs text-text-muted">{field.description}</span>
|
||||
{parsed.errors[field.key] && (
|
||||
<span role="alert" className="block text-error">
|
||||
{parsed.errors[field.key]}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</fieldset>
|
||||
{error && (
|
||||
<p role="alert" className="text-error text-sm">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button type="submit" className={actionClass} disabled={locked || !valid}>
|
||||
{saving ? 'Saving canonical setup...' : 'Save canonical setup'}
|
||||
</button>{' '}
|
||||
{onClose && (
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={saving}
|
||||
onClick={() => {
|
||||
if (confirmDiscard(dirty)) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
>
|
||||
Back to draft settings
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
|
@ -8,9 +8,10 @@ import {
|
|||
import type { ColumnDef } from '@tanstack/react-table';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { isCanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
|
||||
import { DataTable } from '@/components/ui/DataTable';
|
||||
import { browserLog } from '@/utils/browserLog';
|
||||
import type { Run, RunResult } from '../services/backtestApiV2';
|
||||
import type { Run } from '../services/backtestApiV2';
|
||||
import { backtestApiV2 } from '../services/backtestApiV2';
|
||||
|
||||
interface RunsListProps {
|
||||
|
|
@ -20,7 +21,15 @@ interface RunsListProps {
|
|||
}
|
||||
|
||||
interface RunWithMetrics extends Run {
|
||||
metrics?: RunResult['metrics'];
|
||||
metrics?: {
|
||||
totalReturn: number | null;
|
||||
sharpeRatio: number | null;
|
||||
maxDrawdown: number | null;
|
||||
winRate: number | null;
|
||||
profitFactor: number | null;
|
||||
totalProfit?: number | null;
|
||||
};
|
||||
resultKind?: 'canonical' | 'legacy';
|
||||
initialCapital?: number;
|
||||
}
|
||||
|
||||
|
|
@ -32,17 +41,28 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
|
|||
|
||||
// Fetch metrics for completed runs
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
const fetchMetrics = async () => {
|
||||
setLoadingMetrics(true);
|
||||
const updatedRuns: RunWithMetrics[] = await Promise.all(
|
||||
runs.map(async run => {
|
||||
if (run.status === 'completed') {
|
||||
try {
|
||||
const results = await backtestApiV2.getRunResults(run.id);
|
||||
const results = await backtestApiV2.getRunResults(run.id, controller.signal);
|
||||
if (results.runId !== run.id || results.backtestId !== run.backtestId) {
|
||||
throw new Error('Received results for a different backtest or run');
|
||||
}
|
||||
return {
|
||||
...run,
|
||||
metrics: results.metrics,
|
||||
initialCapital: results.config?.initialCapital,
|
||||
metrics: isCanonicalRunResult(results)
|
||||
? results.analytics.metrics
|
||||
: results.metrics,
|
||||
resultKind: isCanonicalRunResult(results)
|
||||
? ('canonical' as const)
|
||||
: ('legacy' as const),
|
||||
initialCapital: isCanonicalRunResult(results)
|
||||
? undefined
|
||||
: results.config?.initialCapital,
|
||||
};
|
||||
} catch (error) {
|
||||
browserLog.error(`Failed to fetch metrics for run ${run.id}:`, error);
|
||||
|
|
@ -52,13 +72,19 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
|
|||
return run;
|
||||
})
|
||||
);
|
||||
setRunsWithMetrics(updatedRuns);
|
||||
setLoadingMetrics(false);
|
||||
if (!controller.signal.aborted) {
|
||||
setRunsWithMetrics(updatedRuns);
|
||||
setLoadingMetrics(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (runs.length > 0) {
|
||||
fetchMetrics();
|
||||
void fetchMetrics();
|
||||
} else {
|
||||
setRunsWithMetrics([]);
|
||||
setLoadingMetrics(false);
|
||||
}
|
||||
return () => controller.abort();
|
||||
}, [runs]);
|
||||
|
||||
const getStatusIcon = (status: Run['status']) => {
|
||||
|
|
@ -114,6 +140,9 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
|
|||
className={`text-sm font-medium ${row.original.id === currentRunId ? 'text-primary-500' : 'text-text-primary'}`}
|
||||
>
|
||||
#{getValue() as number}
|
||||
{row.original.resultKind === 'canonical' && (
|
||||
<span className="ml-1 text-xs text-text-secondary">Canonical</span>
|
||||
)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
|
|
@ -212,14 +241,20 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
|
|||
cell: ({ row }) => {
|
||||
const metrics = row.original.metrics;
|
||||
const value = metrics?.maxDrawdown;
|
||||
// Canonical analytics report a positive loss magnitude; legacy results
|
||||
// retain their signed drawdown convention.
|
||||
const signedLoss =
|
||||
row.original.resultKind === 'canonical' && value !== null && value !== undefined
|
||||
? -value
|
||||
: value;
|
||||
return (
|
||||
<span
|
||||
className={`text-sm font-medium ${
|
||||
value === undefined || value === null
|
||||
signedLoss === undefined || signedLoss === null
|
||||
? 'text-text-secondary'
|
||||
: value > -0.1
|
||||
: signedLoss > -0.1
|
||||
? 'text-success'
|
||||
: value > -0.2
|
||||
: signedLoss > -0.2
|
||||
? 'text-warning'
|
||||
: 'text-error'
|
||||
}`}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue