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
|
|
@ -72,7 +72,7 @@ test('compact metrics preserve null ratios and render a genuine zero profit', ()
|
|||
dataFrequency: '1d',
|
||||
parameters: {},
|
||||
},
|
||||
metrics,
|
||||
metrics: { ...metrics, totalProfit: 0 },
|
||||
equity: [],
|
||||
ohlcData: {},
|
||||
positions: [],
|
||||
|
|
@ -88,3 +88,34 @@ test('compact metrics preserve null ratios and render a genuine zero profit', ()
|
|||
expect(rendered).toContain('$0.00');
|
||||
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);
|
||||
});
|
||||
|
||||
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();
|
||||
row.backtest_config = {
|
||||
name: 'Legacy',
|
||||
|
|
@ -176,10 +176,108 @@ describe('pure stored backtest result conversion', () => {
|
|||
dataFrequency: '1h',
|
||||
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', () => {
|
||||
const row = fixture();
|
||||
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'
|
||||
);
|
||||
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);
|
||||
});
|
||||
}
|
||||
test('completed missing results differ from successful zero trades and retry uses saved results', async () => {
|
||||
await mountPage('completed');
|
||||
expect(host.textContent).toContain('Loading run data');
|
||||
expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull();
|
||||
await flush(() => click('Trades'));
|
||||
await flush(() => reply(request('/api/v2/runs/A/results'), { error: 'Not found' }, 404));
|
||||
expect(host.textContent).toContain('saved results are unavailable');
|
||||
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(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
|
||||
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
|
||||
expect(host.textContent).toContain('No trades executed in this backtest.');
|
||||
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