feat(research): add canonical session reporting and analytics
This commit is contained in:
parent
1e164450c3
commit
3838295eec
28 changed files with 2402 additions and 47 deletions
|
|
@ -2,6 +2,7 @@ import { fork, type ChildProcess } from 'node:child_process';
|
|||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
parseReplayProjectionResult,
|
||||
parseReplayReportResult,
|
||||
parseReplayResult,
|
||||
replayConfigSchema,
|
||||
replayIdentitySchema,
|
||||
|
|
@ -85,9 +86,11 @@ export class NativeBacktestWorker {
|
|||
if (expectedReplay) {
|
||||
try {
|
||||
const parse =
|
||||
expectedReplay.format === 'projection'
|
||||
? parseReplayProjectionResult
|
||||
: parseReplayResult;
|
||||
expectedReplay.format === 'report'
|
||||
? parseReplayReportResult
|
||||
: expectedReplay.format === 'projection'
|
||||
? parseReplayProjectionResult
|
||||
: parseReplayResult;
|
||||
parse(message.result, expectedReplay.identity, expectedReplay.policy);
|
||||
} catch (error) {
|
||||
terminate(error instanceof Error ? error : new Error(String(error)));
|
||||
|
|
|
|||
195
apps/stock/orchestrator/src/backtest/canonical-result.ts
Normal file
195
apps/stock/orchestrator/src/backtest/canonical-result.ts
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
dayMs,
|
||||
drawdownAnalysis,
|
||||
nullable,
|
||||
ratio,
|
||||
returnStatistics,
|
||||
} from '@stock-bot/calculations/analytics';
|
||||
import { cagr, simpleReturn } from '@stock-bot/calculations/returns';
|
||||
import type {
|
||||
CanonicalBacktestAnalytics,
|
||||
CanonicalMetrics,
|
||||
CanonicalMetricsInput,
|
||||
CanonicalMetricUnavailableReason,
|
||||
CanonicalSessionReturn,
|
||||
} from '@stock-bot/types';
|
||||
import type { ReplayReportResult } from '../contracts/native-replay';
|
||||
|
||||
const metricsInput = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
periodsPerYear: z.number().finite().positive(),
|
||||
annualRiskFreeRate: z.number().finite().nullable(),
|
||||
benchmark: z.null(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export interface CanonicalBacktestReport {
|
||||
/** Exact validated Rust facts; never converted through the legacy DTO. */
|
||||
financial: ReplayReportResult;
|
||||
analytics: CanonicalBacktestAnalytics;
|
||||
}
|
||||
|
||||
/** Consume a validated report from the native protocol parser. Financial facts
|
||||
* stay untouched; only statistical reporting converts decimal equity to numbers.
|
||||
* Persistence/public-result migration belongs to the separately gated R05 path. */
|
||||
export function buildCanonicalBacktestReport(
|
||||
financial: ReplayReportResult,
|
||||
input: CanonicalMetricsInput
|
||||
): CanonicalBacktestReport {
|
||||
const policy = metricsInput.parse(input);
|
||||
const reporting = financial.reporting;
|
||||
const initial = Number(reporting.initialEquity);
|
||||
const terminal = Number(financial.projection.valuation.equity);
|
||||
const elapsedMs = Number(reporting.elapsedMs);
|
||||
let previous = initial;
|
||||
const sessionReturns: CanonicalSessionReturn[] = reporting.sessions.map(session => {
|
||||
const current = Number(session.equity);
|
||||
const value = previous > 0 ? nullable(simpleReturn(previous, current)) : null;
|
||||
const reason =
|
||||
value === null
|
||||
? previous <= 0
|
||||
? ('nonpositive-baseline' as const)
|
||||
: ('nonfinite-result' as const)
|
||||
: undefined;
|
||||
previous = current;
|
||||
return {
|
||||
sessionId: session.session.sessionId,
|
||||
periodStart: session.periodStart,
|
||||
periodEnd: session.periodEnd,
|
||||
partialStart: session.partialStart,
|
||||
partialEnd: session.partialEnd,
|
||||
value,
|
||||
eligible: !session.partialStart && !session.partialEnd && value !== null,
|
||||
...(reason ? { reason } : {}),
|
||||
};
|
||||
});
|
||||
const complete = sessionReturns.filter(session => !session.partialStart && !session.partialEnd);
|
||||
// One undefined complete return invalidates this statistical sequence. A later
|
||||
// positive baseline must not silently turn it into a shorter, different sample.
|
||||
const periodicReturns = complete.every(
|
||||
(session): session is CanonicalSessionReturn & { value: number } => session.value !== null
|
||||
)
|
||||
? complete.map(session => session.value)
|
||||
: null;
|
||||
const statistics =
|
||||
periodicReturns === null
|
||||
? null
|
||||
: returnStatistics(periodicReturns, policy.annualRiskFreeRate, policy.periodsPerYear);
|
||||
const points = [
|
||||
{ timestamp: reporting.tradeStart, value: initial },
|
||||
...reporting.sessions.map(session => ({
|
||||
timestamp: session.periodEnd,
|
||||
value: Number(session.equity),
|
||||
})),
|
||||
];
|
||||
const metrics: CanonicalMetrics = {
|
||||
totalReturn: initial > 0 ? nullable(simpleReturn(initial, terminal)) : null,
|
||||
cagr: initial > 0 ? cagr(initial, terminal, elapsedMs / dayMs / 365) : null,
|
||||
maxDrawdown: initial > 0 ? drawdownAnalysis(points, initial).maxDrawdown : null,
|
||||
exposureTime: ratio(Number(reporting.occupiedMs), elapsedMs),
|
||||
volatility: statistics?.volatility ?? null,
|
||||
downsideDeviation: statistics?.downsideDeviation ?? null,
|
||||
sharpeRatio: statistics?.sharpeRatio ?? null,
|
||||
sortinoRatio: statistics?.sortinoRatio ?? null,
|
||||
var95: statistics?.var95 ?? null,
|
||||
cvar95: statistics?.cvar95 ?? null,
|
||||
var99: statistics?.var99 ?? null,
|
||||
alpha: null,
|
||||
beta: null,
|
||||
informationRatio: null,
|
||||
roundTripCount: null,
|
||||
winRate: null,
|
||||
profitFactor: null,
|
||||
avgWin: null,
|
||||
avgLoss: null,
|
||||
};
|
||||
const unavailable: CanonicalBacktestAnalytics['unavailable'] = {
|
||||
alpha: 'missing-benchmark',
|
||||
beta: 'missing-benchmark',
|
||||
informationRatio: 'missing-benchmark',
|
||||
roundTripCount: 'unsupported-round-trips',
|
||||
winRate: 'unsupported-round-trips',
|
||||
profitFactor: 'unsupported-round-trips',
|
||||
avgWin: 'unsupported-round-trips',
|
||||
avgLoss: 'unsupported-round-trips',
|
||||
};
|
||||
if (metrics.totalReturn === null) {
|
||||
unavailable.totalReturn = initial <= 0 ? 'nonpositive-baseline' : 'nonfinite-result';
|
||||
}
|
||||
if (metrics.maxDrawdown === null) {
|
||||
unavailable.maxDrawdown = 'nonpositive-baseline';
|
||||
}
|
||||
if (metrics.exposureTime === null) {
|
||||
unavailable.exposureTime = elapsedMs === 0 ? 'zero-duration' : 'nonfinite-result';
|
||||
}
|
||||
if (metrics.cagr === null) {
|
||||
unavailable.cagr =
|
||||
initial <= 0
|
||||
? 'nonpositive-baseline'
|
||||
: elapsedMs === 0
|
||||
? 'zero-duration'
|
||||
: terminal < 0
|
||||
? 'negative-terminal-equity'
|
||||
: 'nonfinite-result';
|
||||
}
|
||||
const minimumPeriods = {
|
||||
volatility: 2,
|
||||
downsideDeviation: 2,
|
||||
sharpeRatio: 2,
|
||||
sortinoRatio: 2,
|
||||
var95: 20,
|
||||
cvar95: 20,
|
||||
var99: 100,
|
||||
};
|
||||
for (const key of Object.keys(minimumPeriods) as (keyof typeof minimumPeriods)[]) {
|
||||
if (metrics[key] !== null) {
|
||||
continue;
|
||||
}
|
||||
let reason: CanonicalMetricUnavailableReason = 'nonfinite-result';
|
||||
if (periodicReturns === null) {
|
||||
reason = 'undefined-period-return';
|
||||
} else if (
|
||||
['downsideDeviation', 'sharpeRatio', 'sortinoRatio'].includes(key) &&
|
||||
policy.annualRiskFreeRate === null
|
||||
) {
|
||||
reason = 'missing-risk-free';
|
||||
} else if (periodicReturns.length < minimumPeriods[key]) {
|
||||
reason = 'insufficient-periods';
|
||||
} else if (key === 'sharpeRatio' && statistics?.volatility === 0) {
|
||||
reason = 'zero-variance';
|
||||
} else if (key === 'sortinoRatio' && statistics?.downsideDeviation === 0) {
|
||||
reason = 'zero-downside-deviation';
|
||||
}
|
||||
unavailable[key] = reason;
|
||||
}
|
||||
return {
|
||||
financial,
|
||||
analytics: {
|
||||
version: 1,
|
||||
policy: {
|
||||
...policy,
|
||||
calendarId: reporting.calendarId,
|
||||
calendarRevision: reporting.calendarRevision,
|
||||
sampling: reporting.sampling,
|
||||
marks: 'last-available-no-per-session-freshness-certification',
|
||||
returnUnit: 'fraction',
|
||||
variance: 'sample-n-minus-one',
|
||||
riskFreeConversion: 'annual-rate-divided-by-periods-per-year',
|
||||
downside: 'full-series-rms-relative-to-risk-free',
|
||||
partialPeriods: 'visible-excluded-from-periodic-statistics',
|
||||
drawdown: 'session-end-and-terminal-sampled',
|
||||
exposureBasis: reporting.exposureBasis,
|
||||
cagrBasis: 'elapsed-calendar-days-365',
|
||||
zeroTerminalCagr: 'negative-one-for-positive-elapsed-time',
|
||||
},
|
||||
sessionReturns,
|
||||
completePeriodCount: complete.length,
|
||||
periodicSampleCount: periodicReturns?.length ?? 0,
|
||||
fillCount: financial.projection.fills.length,
|
||||
metrics,
|
||||
unavailable,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -8,6 +8,7 @@ import {
|
|||
} from '@stock-bot/types';
|
||||
import {
|
||||
parseReplayProjectionValue,
|
||||
parseReplayReportValue,
|
||||
parseReplayResultValue,
|
||||
replayConfigSchema,
|
||||
replayTraceSchema,
|
||||
|
|
@ -20,6 +21,7 @@ import {
|
|||
type ReplayIdentity,
|
||||
type ReplayOutput,
|
||||
type ReplayProjectionResult,
|
||||
type ReplayReportResult,
|
||||
type ReplayResult,
|
||||
type ReplayResultFormat,
|
||||
type ReplayStep,
|
||||
|
|
@ -33,6 +35,7 @@ export type {
|
|||
ReplayStep,
|
||||
ReplayResult,
|
||||
ReplayProjectionResult,
|
||||
ReplayReportResult,
|
||||
ReplayOutput,
|
||||
ReplayResultFormat,
|
||||
DecisionContext,
|
||||
|
|
@ -197,6 +200,13 @@ export class NativeReplaySession {
|
|||
input => parseReplayProjectionValue(input, this.identity)
|
||||
);
|
||||
}
|
||||
report(): ReplayReportResult {
|
||||
const identity = JSON.stringify(this.identity);
|
||||
return this.finish(
|
||||
() => this.native.report(identity),
|
||||
input => parseReplayReportValue(input, this.identity)
|
||||
);
|
||||
}
|
||||
private finish<T>(native: () => string, validate: (input: unknown) => T): T {
|
||||
let start = performance.now();
|
||||
const raw = native();
|
||||
|
|
@ -243,6 +253,11 @@ interface ReplayOptions {
|
|||
resultFormat?: ReplayResultFormat;
|
||||
}
|
||||
/* eslint-disable no-redeclare -- TypeScript overloads preserve the existing trace result type. */
|
||||
export function runReplayConformance(
|
||||
session: NativeReplaySession,
|
||||
decide: Decide,
|
||||
options: ReplayOptions & { resultFormat: 'report' }
|
||||
): { result: ReplayReportResult; metrics: ReplayMetrics };
|
||||
export function runReplayConformance(
|
||||
session: NativeReplaySession,
|
||||
decide: Decide,
|
||||
|
|
@ -301,7 +316,12 @@ export function runReplayConformance(
|
|||
throw new Error(step.step.diagnostic);
|
||||
case 'complete': {
|
||||
const start = performance.now(),
|
||||
result = options.resultFormat === 'projection' ? session.project() : session.finalize();
|
||||
result =
|
||||
options.resultFormat === 'report'
|
||||
? session.report()
|
||||
: options.resultFormat === 'projection'
|
||||
? session.project()
|
||||
: session.finalize();
|
||||
metrics.finalizeMs = performance.now() - start;
|
||||
metrics.finalizeNativeMs = session.finalization.nativeMs;
|
||||
metrics.finalizeDecodeMs = session.finalization.decodeMs;
|
||||
|
|
@ -359,6 +379,10 @@ export function runReplayConformance(
|
|||
|
||||
/** Bounded fixed intent trace for conformance/debug, not a declarative strategy DSL. */
|
||||
/* eslint-disable no-redeclare -- TypeScript overloads narrow the selected result format. */
|
||||
export function executeReplayTrace(
|
||||
input: ReplayTraceRequest & { resultFormat: 'report' },
|
||||
onProgress?: (step: ReplayStep) => void
|
||||
): { result: ReplayReportResult; metrics: ReplayMetrics };
|
||||
export function executeReplayTrace(
|
||||
input: ReplayTraceRequest & { resultFormat: 'projection' },
|
||||
onProgress?: (step: ReplayStep) => void
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue