feat(research): disclose saved result provenance and limitations

This commit is contained in:
Boki 2026-10-22 14:50:24 -04:00
parent 43ffb547be
commit fe00ecd0e2
12 changed files with 456 additions and 12 deletions

View file

@ -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 ?? {},