feat(research): disclose saved result provenance and limitations
This commit is contained in:
parent
43ffb547be
commit
fe00ecd0e2
12 changed files with 456 additions and 12 deletions
|
|
@ -1,5 +1,5 @@
|
|||
import { BACKTEST_DEFAULTS } from '@stock-bot/stock-config/backtest';
|
||||
import type { BacktestRunResult, BacktestRunTrade } from '@stock-bot/types';
|
||||
import type { BacktestRunProvenance, BacktestRunResult, BacktestRunTrade } from '@stock-bot/types';
|
||||
|
||||
type StoredTrade = Omit<BacktestRunTrade, 'kind' | 'timestamp' | 'price'> &
|
||||
Partial<Pick<BacktestRunTrade, 'kind' | 'timestamp' | 'price'>>;
|
||||
|
|
@ -32,11 +32,65 @@ export interface StoredBacktestResult {
|
|||
};
|
||||
}
|
||||
|
||||
/** Read-only compatibility conversion. Stored rows and metric units are never rewritten. */
|
||||
function resultProvenance(row: StoredBacktestResult): BacktestRunProvenance {
|
||||
const limitations = [
|
||||
{
|
||||
code: 'unversioned-execution',
|
||||
message:
|
||||
'Engine build, financial semantics version and strategy artifact were not recorded. Current terminal-equity and fee-funding fixes do not certify this saved run.',
|
||||
},
|
||||
{
|
||||
code: 'same-bar-execution',
|
||||
message:
|
||||
'Existing simulators can observe a completed bar and fill at its close. These results do not establish next-event execution or freedom from look-ahead bias.',
|
||||
},
|
||||
{
|
||||
code: 'funding-policy',
|
||||
message:
|
||||
'Native and TypeScript engines have different funding checks; short and reducing-order financing is not a canonical cash or margin model.',
|
||||
},
|
||||
{
|
||||
code: 'strategy-attribution',
|
||||
message:
|
||||
'Positions and cost basis are aggregated by symbol. Shared-asset strategy ownership and P&L attribution are not independently reconciled.',
|
||||
},
|
||||
];
|
||||
if (!row.configuration) {
|
||||
limitations.push({
|
||||
code: 'missing-configuration',
|
||||
message:
|
||||
'No frozen run configuration was saved. The compatibility config may use the current mutable definition and defaults; it is not evidence of historical inputs.',
|
||||
});
|
||||
}
|
||||
if (row.engine === 'typescript') {
|
||||
limitations.push({
|
||||
code: 'exposure-convention',
|
||||
message:
|
||||
'TypeScript exposure sums closed-trade durations, so overlapping positions can be counted twice and open positions omitted. It is not portfolio exposure time.',
|
||||
});
|
||||
} else {
|
||||
limitations.push({
|
||||
code: 'unavailable-risk-metrics',
|
||||
message:
|
||||
'Native exposure and VaR include placeholders, which are shown as unavailable. For unknown engines, zero exposure cannot be distinguished from a placeholder. Native daily-return grouping and Sharpe/Sortino conventions need correction; stored computed statistics are retained but are not comparable across engines. Unknown-engine historical metric conventions cannot be verified.',
|
||||
});
|
||||
}
|
||||
return {
|
||||
configurationSource: row.configuration ? 'stored-snapshot' : 'legacy-definition-fallback',
|
||||
datasetHash: row.configuration?.dataset?.hash ?? null,
|
||||
// Neither the stored engine name nor a mutable strategy name identifies a build/artifact.
|
||||
engineVersion: null,
|
||||
economicsVersion: null,
|
||||
strategyArtifactHash: null,
|
||||
limitations,
|
||||
};
|
||||
}
|
||||
|
||||
/** Read-only compatibility conversion. Stored rows are never rewritten. */
|
||||
export function mapStoredBacktestResult(row: StoredBacktestResult): BacktestRunResult {
|
||||
const legacy = !row.configuration;
|
||||
const metrics = { ...row.metrics };
|
||||
const analytics = { ...row.analytics, exposureTime: row.analytics?.exposureTime ?? 0 };
|
||||
const analytics = { ...row.analytics, exposureTime: row.analytics?.exposureTime ?? null };
|
||||
const trades = row.trades.map(trade => {
|
||||
const timestamp = trade.timestamp ?? trade.entryDate;
|
||||
const price = trade.price ?? trade.entryPrice;
|
||||
|
|
@ -63,7 +117,9 @@ export function mapStoredBacktestResult(row: StoredBacktestResult): BacktestRunR
|
|||
metrics.totalTrades = trades.length;
|
||||
metrics.profitableTrades = trades.filter(trade => (trade.pnl ?? 0) > 0).length;
|
||||
}
|
||||
analytics.exposureTime /= 100;
|
||||
if (analytics.exposureTime !== null) {
|
||||
analytics.exposureTime /= 100;
|
||||
}
|
||||
analytics.drawdownSeries = analytics.drawdownSeries?.map(point => ({
|
||||
...point,
|
||||
value: point.value / 100,
|
||||
|
|
@ -78,12 +134,21 @@ export function mapStoredBacktestResult(row: StoredBacktestResult): BacktestRunR
|
|||
);
|
||||
}
|
||||
}
|
||||
if (row.engine !== 'typescript' && analytics.exposureTime === 0) {
|
||||
// Native writes placeholder exposure. Unknown-engine historical zero cannot be
|
||||
// distinguished from that placeholder; retain nonzero stored legacy evidence.
|
||||
analytics.exposureTime = null;
|
||||
}
|
||||
if (row.engine !== 'typescript' && analytics.riskMetrics?.value_at_risk_95 === 0) {
|
||||
analytics.riskMetrics = { ...analytics.riskMetrics, value_at_risk_95: null };
|
||||
}
|
||||
return {
|
||||
runId: row.run_id,
|
||||
backtestId: row.backtest_id,
|
||||
status: row.run_status ?? 'completed',
|
||||
completedAt: row.completed_at.toISOString(),
|
||||
engine: row.engine ?? 'legacy',
|
||||
provenance: resultProvenance(row),
|
||||
...(legacy ? { legacy: true } : {}),
|
||||
config: row.configuration ?? {
|
||||
parameters: row.backtest_config ?? {},
|
||||
|
|
|
|||
|
|
@ -331,7 +331,8 @@ export function BacktestDetailPageV2() {
|
|||
)}
|
||||
</h1>
|
||||
<p className="text-xs text-text-secondary">
|
||||
{backtest?.strategy || ''} • {backtest?.symbols.join(', ') || ''}
|
||||
Current definition: {backtest?.strategy || ''} •{' '}
|
||||
{backtest?.symbols.join(', ') || ''}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import type { Position } from '../types/backtest.types';
|
|||
import { BacktestChart } from './BacktestChart';
|
||||
import { CompactPerformanceMetrics } from './CompactPerformanceMetrics';
|
||||
import { PositionsSummary } from './PositionsSummary';
|
||||
import { ResultProvenance } from './ResultProvenance';
|
||||
|
||||
interface BacktestPlaybackProps {
|
||||
result: RunResult | null;
|
||||
|
|
@ -68,6 +69,10 @@ export const BacktestPlayback = memo(function BacktestPlayback({
|
|||
</ErrorBoundary>
|
||||
</div>
|
||||
|
||||
<div className="flex-shrink-0 max-h-64 overflow-y-auto">
|
||||
<ResultProvenance result={result} />
|
||||
</div>
|
||||
|
||||
{/* Performance Metrics and Positions - Fixed height section */}
|
||||
<div className="flex-shrink-0 grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
<CompactPerformanceMetrics result={result} isLoading={isLoading} />
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ interface ExtendedMetrics {
|
|||
maxDrawdown?: number | null;
|
||||
winRate?: number | null;
|
||||
totalProfit?: number | null;
|
||||
totalPnl?: number | null;
|
||||
profitFactor?: number | null;
|
||||
totalTrades?: number | null;
|
||||
avgWin?: number | null;
|
||||
|
|
@ -55,10 +56,13 @@ export function CompactPerformanceMetrics({ result, isLoading }: CompactPerforma
|
|||
...metrics,
|
||||
};
|
||||
|
||||
// Calculate totalProfit if not provided
|
||||
// Never infer a historical cash amount from a mutable legacy definition's capital.
|
||||
const totalProfit =
|
||||
allMetrics.totalProfit ??
|
||||
(typeof allMetrics.totalReturn === 'number' && typeof result.config?.initialCapital === 'number'
|
||||
allMetrics.totalPnl ??
|
||||
(result.provenance?.configurationSource === 'stored-snapshot' &&
|
||||
typeof allMetrics.totalReturn === 'number' &&
|
||||
typeof result.config?.initialCapital === 'number'
|
||||
? allMetrics.totalReturn * result.config.initialCapital
|
||||
: undefined);
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,89 @@
|
|||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
|
||||
/** Display saved evidence only; the mutable definition remains a separate settings view. */
|
||||
export function ResultProvenance({ result }: { result: BacktestRunResult }) {
|
||||
const provenance = result.provenance;
|
||||
const config = provenance?.configurationSource === 'stored-snapshot' ? result.config : null;
|
||||
|
||||
return (
|
||||
<section
|
||||
aria-label="Result provenance and limitations"
|
||||
className="bg-surface-secondary border border-warning/40 rounded-lg p-3 text-sm space-y-2"
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h3 className="font-medium text-text-primary">Saved run evidence</h3>
|
||||
<span className="text-xs text-warning">Research only · Unverified economics</span>
|
||||
</div>
|
||||
<p className="text-text-secondary">
|
||||
Completion is not financial validation. Do not use this result alone as evidence for
|
||||
promotion to paper or live trading.
|
||||
</p>
|
||||
<p className="text-text-secondary">
|
||||
Known limitations: same-bar execution, funding constraints, strategy attribution and metric
|
||||
conventions.
|
||||
</p>
|
||||
<details>
|
||||
<summary className="cursor-pointer text-text-primary">
|
||||
Configuration, provenance and simulation limitations
|
||||
</summary>
|
||||
<div className="mt-3 space-y-3">
|
||||
<dl className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-text-secondary break-words">
|
||||
<div>
|
||||
<dt>Run</dt>
|
||||
<dd>{result.runId}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Recorded engine</dt>
|
||||
<dd>{result.engine === 'legacy' ? 'Unknown' : result.engine}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Engine build</dt>
|
||||
<dd>{provenance?.engineVersion ?? 'Unknown — not recorded'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Financial semantics version</dt>
|
||||
<dd>{provenance?.economicsVersion ?? 'Unknown — not recorded'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Strategy artifact</dt>
|
||||
<dd>{provenance?.strategyArtifactHash ?? 'Unknown — not recorded'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Dataset hash</dt>
|
||||
<dd>{provenance?.datasetHash ?? 'Unknown — not recorded'}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
{config ? (
|
||||
<div>
|
||||
<h4 className="font-medium text-text-primary">Stored run configuration</h4>
|
||||
<p className="text-text-secondary">
|
||||
Exact saved snapshot, including parameters and data policy when recorded. This is
|
||||
not the current editable definition.
|
||||
</p>
|
||||
<pre className="mt-2 overflow-auto max-h-64 text-xs text-text-secondary">
|
||||
{JSON.stringify(config, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-text-secondary">
|
||||
Stored run configuration: Unknown. Current strategy settings and defaults are not
|
||||
historical evidence.
|
||||
</p>
|
||||
)}
|
||||
{provenance ? (
|
||||
<ul className="list-disc pl-5 space-y-1 text-text-secondary">
|
||||
{provenance.limitations.map(limitation => (
|
||||
<li key={limitation.code}>{limitation.message}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="text-text-secondary">
|
||||
Provenance metadata is unavailable from this API. Execution timing, funding, strategy
|
||||
attribution and metric conventions are unverified.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -78,7 +78,7 @@ export interface BacktestResult {
|
|||
positions: Position[];
|
||||
trades: Trade[];
|
||||
performanceData: PerformanceDataPoint[];
|
||||
analytics?: { exposureTime?: number };
|
||||
analytics?: { exposureTime?: number | null };
|
||||
}
|
||||
|
||||
export interface OrderBookLevel {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue