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 { 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'> &
|
type StoredTrade = Omit<BacktestRunTrade, 'kind' | 'timestamp' | 'price'> &
|
||||||
Partial<Pick<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 {
|
export function mapStoredBacktestResult(row: StoredBacktestResult): BacktestRunResult {
|
||||||
const legacy = !row.configuration;
|
const legacy = !row.configuration;
|
||||||
const metrics = { ...row.metrics };
|
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 trades = row.trades.map(trade => {
|
||||||
const timestamp = trade.timestamp ?? trade.entryDate;
|
const timestamp = trade.timestamp ?? trade.entryDate;
|
||||||
const price = trade.price ?? trade.entryPrice;
|
const price = trade.price ?? trade.entryPrice;
|
||||||
|
|
@ -63,7 +117,9 @@ export function mapStoredBacktestResult(row: StoredBacktestResult): BacktestRunR
|
||||||
metrics.totalTrades = trades.length;
|
metrics.totalTrades = trades.length;
|
||||||
metrics.profitableTrades = trades.filter(trade => (trade.pnl ?? 0) > 0).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 => ({
|
analytics.drawdownSeries = analytics.drawdownSeries?.map(point => ({
|
||||||
...point,
|
...point,
|
||||||
value: point.value / 100,
|
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 {
|
return {
|
||||||
runId: row.run_id,
|
runId: row.run_id,
|
||||||
backtestId: row.backtest_id,
|
backtestId: row.backtest_id,
|
||||||
status: row.run_status ?? 'completed',
|
status: row.run_status ?? 'completed',
|
||||||
completedAt: row.completed_at.toISOString(),
|
completedAt: row.completed_at.toISOString(),
|
||||||
engine: row.engine ?? 'legacy',
|
engine: row.engine ?? 'legacy',
|
||||||
|
provenance: resultProvenance(row),
|
||||||
...(legacy ? { legacy: true } : {}),
|
...(legacy ? { legacy: true } : {}),
|
||||||
config: row.configuration ?? {
|
config: row.configuration ?? {
|
||||||
parameters: row.backtest_config ?? {},
|
parameters: row.backtest_config ?? {},
|
||||||
|
|
|
||||||
|
|
@ -331,7 +331,8 @@ export function BacktestDetailPageV2() {
|
||||||
)}
|
)}
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-xs text-text-secondary">
|
<p className="text-xs text-text-secondary">
|
||||||
{backtest?.strategy || ''} • {backtest?.symbols.join(', ') || ''}
|
Current definition: {backtest?.strategy || ''} •{' '}
|
||||||
|
{backtest?.symbols.join(', ') || ''}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ import type { Position } from '../types/backtest.types';
|
||||||
import { BacktestChart } from './BacktestChart';
|
import { BacktestChart } from './BacktestChart';
|
||||||
import { CompactPerformanceMetrics } from './CompactPerformanceMetrics';
|
import { CompactPerformanceMetrics } from './CompactPerformanceMetrics';
|
||||||
import { PositionsSummary } from './PositionsSummary';
|
import { PositionsSummary } from './PositionsSummary';
|
||||||
|
import { ResultProvenance } from './ResultProvenance';
|
||||||
|
|
||||||
interface BacktestPlaybackProps {
|
interface BacktestPlaybackProps {
|
||||||
result: RunResult | null;
|
result: RunResult | null;
|
||||||
|
|
@ -68,6 +69,10 @@ export const BacktestPlayback = memo(function BacktestPlayback({
|
||||||
</ErrorBoundary>
|
</ErrorBoundary>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-shrink-0 max-h-64 overflow-y-auto">
|
||||||
|
<ResultProvenance result={result} />
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Performance Metrics and Positions - Fixed height section */}
|
{/* Performance Metrics and Positions - Fixed height section */}
|
||||||
<div className="flex-shrink-0 grid grid-cols-1 lg:grid-cols-2 gap-4">
|
<div className="flex-shrink-0 grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||||
<CompactPerformanceMetrics result={result} isLoading={isLoading} />
|
<CompactPerformanceMetrics result={result} isLoading={isLoading} />
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ interface ExtendedMetrics {
|
||||||
maxDrawdown?: number | null;
|
maxDrawdown?: number | null;
|
||||||
winRate?: number | null;
|
winRate?: number | null;
|
||||||
totalProfit?: number | null;
|
totalProfit?: number | null;
|
||||||
|
totalPnl?: number | null;
|
||||||
profitFactor?: number | null;
|
profitFactor?: number | null;
|
||||||
totalTrades?: number | null;
|
totalTrades?: number | null;
|
||||||
avgWin?: number | null;
|
avgWin?: number | null;
|
||||||
|
|
@ -55,10 +56,13 @@ export function CompactPerformanceMetrics({ result, isLoading }: CompactPerforma
|
||||||
...metrics,
|
...metrics,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Calculate totalProfit if not provided
|
// Never infer a historical cash amount from a mutable legacy definition's capital.
|
||||||
const totalProfit =
|
const totalProfit =
|
||||||
allMetrics.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
|
? allMetrics.totalReturn * result.config.initialCapital
|
||||||
: undefined);
|
: 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[];
|
positions: Position[];
|
||||||
trades: Trade[];
|
trades: Trade[];
|
||||||
performanceData: PerformanceDataPoint[];
|
performanceData: PerformanceDataPoint[];
|
||||||
analytics?: { exposureTime?: number };
|
analytics?: { exposureTime?: number | null };
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface OrderBookLevel {
|
export interface OrderBookLevel {
|
||||||
|
|
|
||||||
|
|
@ -57,6 +57,17 @@ export interface BacktestRunTrade {
|
||||||
duration?: number;
|
duration?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Read-only evidence from saved results, not a certification of economic correctness. */
|
||||||
|
export interface BacktestRunProvenance {
|
||||||
|
/** Legacy config remains a compatibility display fallback, never historical evidence. */
|
||||||
|
configurationSource: 'stored-snapshot' | 'legacy-definition-fallback';
|
||||||
|
datasetHash: string | null;
|
||||||
|
engineVersion: string | null;
|
||||||
|
economicsVersion: string | null;
|
||||||
|
strategyArtifactHash: string | null;
|
||||||
|
limitations: { code: string; message: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface BacktestRunResult {
|
export interface BacktestRunResult {
|
||||||
runId: string;
|
runId: string;
|
||||||
backtestId: string;
|
backtestId: string;
|
||||||
|
|
@ -65,6 +76,8 @@ export interface BacktestRunResult {
|
||||||
legacy?: boolean;
|
legacy?: boolean;
|
||||||
status: 'completed' | 'cancelled';
|
status: 'completed' | 'cancelled';
|
||||||
completedAt: string;
|
completedAt: string;
|
||||||
|
/** Optional for older API clients/results. Missing provenance must display as unknown. */
|
||||||
|
provenance?: BacktestRunProvenance;
|
||||||
config: BacktestRunConfiguration;
|
config: BacktestRunConfiguration;
|
||||||
metrics: BacktestRunMetrics;
|
metrics: BacktestRunMetrics;
|
||||||
equity: { date: string; value: number }[];
|
equity: { date: string; value: number }[];
|
||||||
|
|
@ -83,7 +96,8 @@ export interface BacktestRunResult {
|
||||||
}[];
|
}[];
|
||||||
/** Returns, drawdowns, and exposure use fractions here as well. */
|
/** Returns, drawdowns, and exposure use fractions here as well. */
|
||||||
analytics: {
|
analytics: {
|
||||||
exposureTime: number;
|
/** Null when unavailable or a known placeholder; genuine measured zero remains zero. */
|
||||||
|
exposureTime: number | null;
|
||||||
drawdownSeries?: { timestamp: number; value: number }[];
|
drawdownSeries?: { timestamp: number; value: number }[];
|
||||||
dailyReturns?: number[];
|
dailyReturns?: number[];
|
||||||
monthlyReturns?: Record<string, number>;
|
monthlyReturns?: Record<string, number>;
|
||||||
|
|
|
||||||
|
|
@ -47,6 +47,7 @@ export type { BacktestResults } from './backtesting';
|
||||||
export type {
|
export type {
|
||||||
BacktestRunConfiguration,
|
BacktestRunConfiguration,
|
||||||
BacktestRunMetrics,
|
BacktestRunMetrics,
|
||||||
|
BacktestRunProvenance,
|
||||||
BacktestRunTrade,
|
BacktestRunTrade,
|
||||||
BacktestRunResult,
|
BacktestRunResult,
|
||||||
} from './backtest-run';
|
} from './backtest-run';
|
||||||
|
|
|
||||||
|
|
@ -72,7 +72,7 @@ test('compact metrics preserve null ratios and render a genuine zero profit', ()
|
||||||
dataFrequency: '1d',
|
dataFrequency: '1d',
|
||||||
parameters: {},
|
parameters: {},
|
||||||
},
|
},
|
||||||
metrics,
|
metrics: { ...metrics, totalProfit: 0 },
|
||||||
equity: [],
|
equity: [],
|
||||||
ohlcData: {},
|
ohlcData: {},
|
||||||
positions: [],
|
positions: [],
|
||||||
|
|
@ -88,3 +88,34 @@ test('compact metrics preserve null ratios and render a genuine zero profit', ()
|
||||||
expect(rendered).toContain('$0.00');
|
expect(rendered).toContain('$0.00');
|
||||||
expect(rendered).not.toMatch(/Infinity|NaN/);
|
expect(rendered).not.toMatch(/Infinity|NaN/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('null_metrics: detailed exposure is unavailable rather than a measured zero', () => {
|
||||||
|
const rendered = text(
|
||||||
|
renderToStaticMarkup(
|
||||||
|
createElement(BacktestMetrics, {
|
||||||
|
isLoading: false,
|
||||||
|
result: {
|
||||||
|
id: 'fixture',
|
||||||
|
config: {
|
||||||
|
name: 'fixture',
|
||||||
|
startDate: new Date('2024-01-01'),
|
||||||
|
endDate: new Date('2024-02-01'),
|
||||||
|
initialCapital: 1000,
|
||||||
|
symbols: ['A.US'],
|
||||||
|
strategy: 'sma',
|
||||||
|
speedMultiplier: 0,
|
||||||
|
commission: 0,
|
||||||
|
slippage: 0,
|
||||||
|
},
|
||||||
|
metrics,
|
||||||
|
positions: [],
|
||||||
|
trades: [],
|
||||||
|
performanceData: [],
|
||||||
|
analytics: { exposureTime: null },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
expect(rendered).toContain('Exposure TimeN/A');
|
||||||
|
expect(rendered).not.toContain('Exposure Time0.0%');
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -157,7 +157,7 @@ describe('pure stored backtest result conversion', () => {
|
||||||
expect(row).toEqual(before);
|
expect(row).toEqual(before);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('legacy explicit zero fees and absent optional analytics keep their existing defaults', () => {
|
test('legacy explicit zero fees remain compatibility defaults, missing analytics are unknown', () => {
|
||||||
const row = fixture();
|
const row = fixture();
|
||||||
row.backtest_config = {
|
row.backtest_config = {
|
||||||
name: 'Legacy',
|
name: 'Legacy',
|
||||||
|
|
@ -176,10 +176,108 @@ describe('pure stored backtest result conversion', () => {
|
||||||
dataFrequency: '1h',
|
dataFrequency: '1h',
|
||||||
parameters: row.backtest_config,
|
parameters: row.backtest_config,
|
||||||
},
|
},
|
||||||
analytics: { exposureTime: 0 },
|
analytics: { exposureTime: null },
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('legacy_missing_provenance: mutable definition fallback is explicitly not saved evidence', () => {
|
||||||
|
const row = fixture();
|
||||||
|
row.backtest_config = { name: 'Changed later', commission: 0.25 };
|
||||||
|
const result = mapStoredBacktestResult(row);
|
||||||
|
expect(result.config.name).toBe('Changed later'); // Old consumers keep their display fallback.
|
||||||
|
expect(result.provenance).toMatchObject({
|
||||||
|
configurationSource: 'legacy-definition-fallback',
|
||||||
|
datasetHash: null,
|
||||||
|
engineVersion: null,
|
||||||
|
economicsVersion: null,
|
||||||
|
strategyArtifactHash: null,
|
||||||
|
});
|
||||||
|
expect(result.provenance?.limitations.map(item => item.code)).toContain(
|
||||||
|
'missing-configuration'
|
||||||
|
);
|
||||||
|
expect(result.provenance?.limitations.map(item => item.code)).toContain(
|
||||||
|
'unversioned-execution'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('frozen_config_not_mutable_definition: all stored inputs and dataset identity survive definition edits', () => {
|
||||||
|
const row = fixture();
|
||||||
|
row.engine = 'typescript';
|
||||||
|
row.configuration = {
|
||||||
|
name: 'Frozen strategy',
|
||||||
|
strategy: 'saved-strategy',
|
||||||
|
symbols: ['B.US'],
|
||||||
|
startDate: '2023-01-01',
|
||||||
|
endDate: '2023-02-01',
|
||||||
|
initialCapital: 1000,
|
||||||
|
commission: 0.0007,
|
||||||
|
slippage: 0.0002,
|
||||||
|
dataFrequency: '1m',
|
||||||
|
parameters: { lookback: 14 },
|
||||||
|
dataset: {
|
||||||
|
version: 1,
|
||||||
|
hash: 'a'.repeat(64),
|
||||||
|
instruments: [{ id: 'B.US', symbol: 'B', exchange: 'US' }],
|
||||||
|
startDate: '2023-01-01',
|
||||||
|
endDate: '2023-02-01',
|
||||||
|
interval: '1m',
|
||||||
|
policy: { adjustment: 'raw', timestamp: 'utc-instant' },
|
||||||
|
volumePolicy: 'reported',
|
||||||
|
qualityPolicy: 'reject-invalid-no-interpolation',
|
||||||
|
sources: [],
|
||||||
|
barCount: 10,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const first = mapStoredBacktestResult(row);
|
||||||
|
row.strategy = 'changed-strategy';
|
||||||
|
row.symbols = ['C.US'];
|
||||||
|
row.initial_capital = 999999;
|
||||||
|
row.backtest_config = { commission: 0.9, slippage: 0.9, dataFrequency: '1d' };
|
||||||
|
const reopened = mapStoredBacktestResult(row);
|
||||||
|
expect(reopened.config).toEqual(first.config);
|
||||||
|
expect(reopened.provenance).toEqual(first.provenance);
|
||||||
|
expect(reopened.provenance).toMatchObject({
|
||||||
|
configurationSource: 'stored-snapshot',
|
||||||
|
datasetHash: 'a'.repeat(64),
|
||||||
|
engineVersion: null,
|
||||||
|
economicsVersion: null,
|
||||||
|
strategyArtifactHash: null,
|
||||||
|
});
|
||||||
|
expect(reopened.provenance?.limitations.map(item => item.code)).not.toContain(
|
||||||
|
'missing-configuration'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('null_metrics: known placeholders are unavailable without discarding computed statistics or mutating storage', () => {
|
||||||
|
const row = fixture();
|
||||||
|
row.engine = 'native';
|
||||||
|
row.metrics.sharpeRatio = 1.2;
|
||||||
|
row.metrics.sortinoRatio = 1.4;
|
||||||
|
row.analytics = {
|
||||||
|
exposureTime: 0,
|
||||||
|
riskMetrics: { value_at_risk_95: 0, volatility: 0.12, downside_deviation: 0.08 },
|
||||||
|
};
|
||||||
|
const before = structuredClone(row);
|
||||||
|
const result = mapStoredBacktestResult(row);
|
||||||
|
expect(result.analytics.exposureTime).toBeNull();
|
||||||
|
expect(result.analytics.riskMetrics).toEqual({
|
||||||
|
value_at_risk_95: null,
|
||||||
|
volatility: 0.12,
|
||||||
|
downside_deviation: 0.08,
|
||||||
|
});
|
||||||
|
expect(result.metrics.sharpeRatio).toBe(1.2);
|
||||||
|
expect(result.metrics.sortinoRatio).toBe(1.4);
|
||||||
|
expect(row).toEqual(before);
|
||||||
|
row.engine = 'typescript';
|
||||||
|
row.analytics = { exposureTime: 0, riskMetrics: { var95: 0 } };
|
||||||
|
expect(mapStoredBacktestResult(row).analytics).toEqual({
|
||||||
|
exposureTime: 0,
|
||||||
|
riskMetrics: { var95: 0 },
|
||||||
|
});
|
||||||
|
row.engine = 'legacy';
|
||||||
|
expect(mapStoredBacktestResult(row).analytics.exposureTime).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
test('malformed trade identities fail instead of fabricating an execution time or price', () => {
|
test('malformed trade identities fail instead of fabricating an execution time or price', () => {
|
||||||
const row = fixture();
|
const row = fixture();
|
||||||
delete row.trades[0]!.entryDate;
|
delete row.trades[0]!.entryDate;
|
||||||
|
|
|
||||||
119
test/integration/backtest-result-provenance.test.tsx
Normal file
119
test/integration/backtest-result-provenance.test.tsx
Normal file
|
|
@ -0,0 +1,119 @@
|
||||||
|
import { expect, test } from 'bun:test';
|
||||||
|
import { createElement } from 'react';
|
||||||
|
import { renderToStaticMarkup } from 'react-dom/server';
|
||||||
|
import type { BacktestRunResult } from '@stock-bot/types';
|
||||||
|
import { mapStoredBacktestResult } from '../../apps/stock/web-api/src/services/backtest-result';
|
||||||
|
import { CompactPerformanceMetrics } from '../../apps/stock/web-app/src/features/backtest/components/CompactPerformanceMetrics';
|
||||||
|
import { ResultProvenance } from '../../apps/stock/web-app/src/features/backtest/components/ResultProvenance';
|
||||||
|
|
||||||
|
function result(): BacktestRunResult {
|
||||||
|
return mapStoredBacktestResult({
|
||||||
|
run_id: 'saved-run',
|
||||||
|
backtest_id: 'definition',
|
||||||
|
completed_at: new Date('2024-02-01'),
|
||||||
|
strategy: 'MUTABLE_STRATEGY',
|
||||||
|
symbols: ['CHANGED.US'],
|
||||||
|
initial_capital: 999999,
|
||||||
|
start_date: new Date('2020-01-01'),
|
||||||
|
end_date: new Date('2020-02-01'),
|
||||||
|
backtest_config: { name: 'MUTABLE_NAME', commission: 0.9 },
|
||||||
|
metrics: {
|
||||||
|
totalReturn: 10,
|
||||||
|
sharpeRatio: 1,
|
||||||
|
maxDrawdown: 0.1,
|
||||||
|
winRate: 50,
|
||||||
|
totalTrades: 2,
|
||||||
|
profitFactor: 1.5,
|
||||||
|
avgWin: 1,
|
||||||
|
avgLoss: -1,
|
||||||
|
},
|
||||||
|
trades: [],
|
||||||
|
equity_curve: [],
|
||||||
|
ohlc_data: {},
|
||||||
|
positions: [],
|
||||||
|
execution_time: 2,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const text = (html: string) => html.replace(/<[^>]*>/g, '');
|
||||||
|
const panel = (saved: BacktestRunResult) =>
|
||||||
|
text(renderToStaticMarkup(createElement(ResultProvenance, { result: saved })));
|
||||||
|
const metrics = (saved: BacktestRunResult) =>
|
||||||
|
text(
|
||||||
|
renderToStaticMarkup(
|
||||||
|
createElement(CompactPerformanceMetrics, { result: saved, isLoading: false })
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
test('legacy_missing_provenance: panel never substitutes current settings for historical evidence', () => {
|
||||||
|
const saved = result();
|
||||||
|
const rendered = panel(saved);
|
||||||
|
expect(rendered).toContain('Stored run configuration: Unknown');
|
||||||
|
expect(rendered).toContain('Dataset hashUnknown');
|
||||||
|
expect(rendered).toContain('Engine buildUnknown');
|
||||||
|
expect(rendered).toContain('Strategy artifactUnknown');
|
||||||
|
expect(rendered).not.toContain('MUTABLE_STRATEGY');
|
||||||
|
expect(rendered).not.toContain('MUTABLE_NAME');
|
||||||
|
expect(rendered).not.toContain('999999');
|
||||||
|
expect(metrics(saved)).toContain('Total Profit-');
|
||||||
|
saved.metrics.totalPnl = 123;
|
||||||
|
expect(metrics(saved)).toContain('Total Profit$123.00');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('frozen_config_not_mutable_definition: exact snapshot renders and permits capital-derived profit', () => {
|
||||||
|
const saved = result();
|
||||||
|
saved.config = {
|
||||||
|
name: 'Stored strategy',
|
||||||
|
strategy: 'saved-strategy',
|
||||||
|
symbols: ['A.US'],
|
||||||
|
startDate: '2024-01-01',
|
||||||
|
endDate: '2024-02-01',
|
||||||
|
initialCapital: 1000,
|
||||||
|
commission: 0.0007,
|
||||||
|
slippage: 0,
|
||||||
|
dataFrequency: '1m',
|
||||||
|
parameters: { lookback: 42 },
|
||||||
|
};
|
||||||
|
saved.provenance!.configurationSource = 'stored-snapshot';
|
||||||
|
saved.provenance!.datasetHash = 'a'.repeat(64);
|
||||||
|
const rendered = panel(saved);
|
||||||
|
expect(rendered).toContain('Stored run configuration');
|
||||||
|
expect(rendered).toContain('saved-strategy');
|
||||||
|
expect(rendered).toContain('lookback');
|
||||||
|
expect(rendered).toContain('42');
|
||||||
|
expect(rendered).toContain('0.0007');
|
||||||
|
expect(rendered).toContain('a'.repeat(64));
|
||||||
|
expect(rendered).not.toContain('MUTABLE_STRATEGY');
|
||||||
|
expect(metrics(saved)).toContain('Total Profit$100.00');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('limitation_badge: engine name never establishes version or financial validation', () => {
|
||||||
|
const saved = result();
|
||||||
|
saved.engine = 'native';
|
||||||
|
const rendered = panel(saved);
|
||||||
|
expect(rendered).toContain('Research only · Unverified economics');
|
||||||
|
expect(rendered).toContain('Recorded enginenative');
|
||||||
|
expect(rendered).toContain('Engine buildUnknown');
|
||||||
|
expect(rendered).toContain('same-bar execution');
|
||||||
|
expect(rendered).toContain('funding constraints');
|
||||||
|
expect(rendered).toContain('strategy attribution');
|
||||||
|
expect(rendered).toContain(
|
||||||
|
'Current terminal-equity and fee-funding fixes do not certify this saved run'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('old API without provenance remains readable but cannot invent historical inputs', () => {
|
||||||
|
const saved = result();
|
||||||
|
delete saved.provenance;
|
||||||
|
expect(panel(saved)).toContain('Provenance metadata is unavailable from this API');
|
||||||
|
expect(panel(saved)).toContain('Stored run configuration: Unknown');
|
||||||
|
expect(metrics(saved)).toContain('Total Profit-');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('null_metrics: missing exposure is unavailable, genuine recorded zeros remain visible', () => {
|
||||||
|
const saved = result();
|
||||||
|
expect(metrics(saved)).toContain('Exposure-');
|
||||||
|
saved.analytics.exposureTime = 0;
|
||||||
|
saved.metrics.totalProfit = 0;
|
||||||
|
expect(metrics(saved)).toContain('Total Profit$0.00');
|
||||||
|
expect(metrics(saved)).toContain('Exposure0.0%');
|
||||||
|
});
|
||||||
|
|
@ -537,20 +537,37 @@ describe('actual detail page result states', () => {
|
||||||
status === 'failed' ? 'Run failed: Fixture failure' : 'Run cancelled'
|
status === 'failed' ? 'Run failed: Fixture failure' : 'Run cancelled'
|
||||||
);
|
);
|
||||||
expect(host.textContent).not.toContain('No trades executed');
|
expect(host.textContent).not.toContain('No trades executed');
|
||||||
|
expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull();
|
||||||
expect(requests.some(item => item.path.endsWith('/results'))).toBe(false);
|
expect(requests.some(item => item.path.endsWith('/results'))).toBe(false);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
test('completed missing results differ from successful zero trades and retry uses saved results', async () => {
|
test('completed missing results differ from successful zero trades and retry uses saved results', async () => {
|
||||||
await mountPage('completed');
|
await mountPage('completed');
|
||||||
expect(host.textContent).toContain('Loading run data');
|
expect(host.textContent).toContain('Loading run data');
|
||||||
|
expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull();
|
||||||
await flush(() => click('Trades'));
|
await flush(() => click('Trades'));
|
||||||
await flush(() => reply(request('/api/v2/runs/A/results'), { error: 'Not found' }, 404));
|
await flush(() => reply(request('/api/v2/runs/A/results'), { error: 'Not found' }, 404));
|
||||||
expect(host.textContent).toContain('saved results are unavailable');
|
expect(host.textContent).toContain('saved results are unavailable');
|
||||||
expect(host.textContent).not.toContain('No trades executed');
|
expect(host.textContent).not.toContain('No trades executed');
|
||||||
|
expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull();
|
||||||
await flush(() => click('Retry results'));
|
await flush(() => click('Retry results'));
|
||||||
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
|
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
|
||||||
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
|
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
|
||||||
expect(host.textContent).toContain('No trades executed in this backtest.');
|
expect(host.textContent).toContain('No trades executed in this backtest.');
|
||||||
expect(host.textContent).not.toContain('saved results are unavailable');
|
expect(host.textContent).not.toContain('saved results are unavailable');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('limitation_badge: completed detail shows unknown legacy provenance beside performance', async () => {
|
||||||
|
await mountPage('completed');
|
||||||
|
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
|
||||||
|
const evidence = host.querySelector('[aria-label="Result provenance and limitations"]');
|
||||||
|
expect(evidence).not.toBeNull();
|
||||||
|
expect(evidence!.textContent).toContain('Research only · Unverified economics');
|
||||||
|
const details = evidence!.querySelector('details')!;
|
||||||
|
await flush(() => details.querySelector('summary')!.click());
|
||||||
|
expect(details.open).toBe(true);
|
||||||
|
expect(evidence!.textContent).toContain('Stored run configuration: Unknown');
|
||||||
|
expect(evidence!.textContent).toContain('Provenance metadata is unavailable from this API');
|
||||||
|
expect(host.textContent).toContain('Performance');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue