stock-bot/apps/stock/web-api/src/services/backtest-result.ts

173 lines
6.8 KiB
TypeScript

import { BACKTEST_DEFAULTS } from '@stock-bot/stock-config/backtest';
import type { BacktestRunProvenance, BacktestRunResult, BacktestRunTrade } from '@stock-bot/types';
type StoredTrade = Omit<BacktestRunTrade, 'kind' | 'timestamp' | 'price'> &
Partial<Pick<BacktestRunTrade, 'kind' | 'timestamp' | 'price'>>;
/** Projection returned by the saved-result query, including pre-contract history. */
export interface StoredBacktestResult {
run_id: string;
backtest_id: string;
run_status?: BacktestRunResult['status'];
completed_at: Date;
engine?: BacktestRunResult['engine'] | null;
configuration?: BacktestRunResult['config'] | null;
metrics: BacktestRunResult['metrics'];
analytics?: Partial<BacktestRunResult['analytics']> | null;
trades: StoredTrade[];
equity_curve: BacktestRunResult['equity'];
ohlc_data: BacktestRunResult['ohlcData'];
positions: BacktestRunResult['positions'];
execution_time: number;
strategy: string;
symbols: string[];
start_date: Date;
end_date: Date;
initial_capital: string | number;
backtest_config?: Record<string, unknown> & {
name?: string;
commission?: number;
slippage?: number;
dataFrequency?: string;
};
}
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 ?? null };
const trades = row.trades.map(trade => {
const timestamp = trade.timestamp ?? trade.entryDate;
const price = trade.price ?? trade.entryPrice;
if (!timestamp || price === undefined) {
throw new Error('Malformed stored backtest trade');
}
return {
...trade,
kind: trade.kind ?? (trade.entryDate ? 'closed' : 'fill'),
timestamp,
price,
};
});
if (legacy) {
// Pre-contract backends reported return/win rate in percentage points.
metrics.totalReturn /= 100;
metrics.winRate /= 100;
for (const key of ['annualReturn', 'annualizedReturn']) {
if (typeof metrics[key] === 'number') {
metrics[key] /= 100;
}
}
if (trades.some(trade => trade.kind === 'closed')) {
metrics.totalTrades = trades.length;
metrics.profitableTrades = trades.filter(trade => (trade.pnl ?? 0) > 0).length;
}
if (analytics.exposureTime !== null) {
analytics.exposureTime /= 100;
}
analytics.drawdownSeries = analytics.drawdownSeries?.map(point => ({
...point,
value: point.value / 100,
}));
// Legacy native finalValue marks daily returns already expressed as fractions.
if (typeof row.metrics.finalValue !== 'number') {
analytics.dailyReturns = analytics.dailyReturns?.map(value => value / 100);
}
if (analytics.monthlyReturns) {
analytics.monthlyReturns = Object.fromEntries(
Object.entries(analytics.monthlyReturns).map(([month, value]) => [month, value / 100])
);
}
}
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 ?? {},
name: row.backtest_config?.name || 'Backtest',
strategy: row.strategy,
symbols: row.symbols,
startDate: row.start_date.toISOString(),
endDate: row.end_date.toISOString(),
initialCapital: parseFloat(String(row.initial_capital)),
commission: row.backtest_config?.commission ?? BACKTEST_DEFAULTS.commission,
slippage: row.backtest_config?.slippage ?? BACKTEST_DEFAULTS.slippage,
dataFrequency: row.backtest_config?.dataFrequency || BACKTEST_DEFAULTS.dataFrequency,
},
metrics,
equity: row.equity_curve,
ohlcData: row.ohlc_data,
trades,
positions: row.positions,
analytics,
executionTime: row.execution_time,
};
}