From 302ba60e53cb104c32ad414432767e953f4b0777 Mon Sep 17 00:00:00 2001 From: Boki Date: Tue, 27 Oct 2026 01:07:32 -0400 Subject: [PATCH] fix(research): explain evaluation horizon and CAGR (RP04) --- .../backtest/components/CanonicalResults.tsx | 42 +++++++++++- docs/development/backlog/tasks/RP04.md | 2 + test/e2e/workbench.test.ts | 10 +++ test/integration/canonical-workbench.test.tsx | 65 +++++++++++++++++++ 4 files changed, 117 insertions(+), 2 deletions(-) diff --git a/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx b/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx index 35d42716..eb839c9b 100644 --- a/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx +++ b/apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx @@ -10,6 +10,24 @@ export function canonicalTime(timestamp: number): string { const date = new Date(timestamp); return Number.isFinite(date.getTime()) ? date.toISOString() : `${timestamp} ms since Unix epoch`; } +function calendarDuration(milliseconds: string): string { + let remaining = BigInt(milliseconds); + const parts: string[] = []; + for (const [size, unit] of [ + [86_400_000n, 'day'], + [3_600_000n, 'hour'], + [60_000n, 'minute'], + [1000n, 'second'], + [1n, 'millisecond'], + ] as const) { + const count = remaining / size; + remaining %= size; + if (count > 0n) { + parts.push(`${count} ${unit}${count === 1n ? '' : 's'}`); + } + } + return parts.join(', ') || '0 seconds'; +} const reasonText = (reason: string | undefined) => reason?.replace(/-/g, ' ') ?? 'not reported'; const metricFields: { key: keyof CanonicalMetrics; label: string; percentage?: boolean }[] = [ { key: 'totalReturn', label: 'Total return', percentage: true }, @@ -200,6 +218,20 @@ export function CanonicalResults({

Canonical metrics

+
+
+
Evaluation start (UTC)
+
{canonicalTime(financial.reporting.tradeStart)}
+
+
+
Evaluation end (UTC, exclusive)
+
{canonicalTime(financial.reporting.tradeEnd)}
+
+
+
Elapsed calendar duration
+
{calendarDuration(financial.reporting.elapsedMs)}
+
+

{analytics.fillCount} fills · {analytics.completePeriodCount} complete periods ·{' '} {analytics.periodicSampleCount} statistical samples. Returns use fractions, displayed as @@ -219,14 +251,20 @@ export function CanonicalResults({ ? `${(value * 100).toFixed(2)}%` : value.toFixed(2)} + {field.key === 'cagr' && ( +

+ CAGR extrapolates this evaluation interval to a 365-calendar-day year, including + nontrading time. It is not an observed annual return or a forecast. +
+ )} ); })}

Period calendar: {analytics.policy.calendarId}, revision{' '} - {analytics.policy.calendarRevision}. Annualization: {analytics.policy.periodsPerYear}{' '} - periods/year. Risk-free rate:{' '} + {analytics.policy.calendarRevision}. Annualization for periodic statistics:{' '} + {analytics.policy.periodsPerYear} periods/year. Risk-free rate:{' '} {analytics.policy.annualRiskFreeRate === null ? 'unknown' : `${(analytics.policy.annualRiskFreeRate * 100).toFixed(2)}%`} diff --git a/docs/development/backlog/tasks/RP04.md b/docs/development/backlog/tasks/RP04.md index 4c0f1e89..9c112ea1 100644 --- a/docs/development/backlog/tasks/RP04.md +++ b/docs/development/backlog/tasks/RP04.md @@ -9,3 +9,5 @@ Scope: in `apps/stock/web-app/src/features/backtest/components/CanonicalResults. Acceptance/tests: realistic partial-session result displays exact UTC interval/duration and CAGR explanation with stored CAGR unchanged; multi-day/overnight duration is calendar elapsed time; null CAGR reason and existing fill-only view remain correct; periodic annualization label is unambiguous. Add focused production-component regression assertions in the existing result/UI suite; root may add browser assertions to its owned workbench scenario. Loading/error/empty behavior stays in the existing parent run view; no new backend/data dependency or request. Locks: CanonicalResults and its focused result tests only. Parallel with RP03; do not modify shared workbench E2E or manifest. Gates: focused UI tests, authored test/app types, strict lint and production build, root combined check/browser gate, independent review. Regression risk low; the primary risk is misstating the existing computation's time basis. + +Accepted October 27, 2026: retained UTC bounds and exact calendar duration now accompany the unchanged metrics. Independent review passed 21 UI tests / 157 assertions; the root actual-native browser smoke verifies the displayed reporting interval and explanation. Full repository check, application/authored-test types, strict lint and production build passed. [Combined evidence](../../real-data-research.md) records final integration results and test-run limitations. diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.test.ts index 87cbe45e..c8e9c0e5 100644 --- a/test/e2e/workbench.test.ts +++ b/test/e2e/workbench.test.ts @@ -1873,6 +1873,16 @@ test('canonical_native_smoke', async () => { (await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id=$1', [runId])).rowCount ).toBe(1); await visible(f.page, 'Canonical research result'); + const interval = f.page.locator('[aria-label="Evaluation horizon"]'); + await interval.waitFor({ state: 'visible' }); + expect(await interval.textContent()).toContain( + new Date(result.financial.reporting.tradeStart).toISOString() + ); + expect(await interval.textContent()).toContain( + new Date(result.financial.reporting.tradeEnd).toISOString() + ); + await visible(f.page, /CAGR extrapolates this evaluation interval to a 365-calendar-day year/); + await visible(f.page, /Annualization for periodic statistics:/); await f.page.getByRole('button', { name: 'Trades', exact: true }).click(); await visible(f.page, result.financial.projection.fills[0].side); await visible(f.page, result.financial.projection.fills[0].price); diff --git a/test/integration/canonical-workbench.test.tsx b/test/integration/canonical-workbench.test.tsx index b6412a81..10454570 100644 --- a/test/integration/canonical-workbench.test.tsx +++ b/test/integration/canonical-workbench.test.tsx @@ -717,6 +717,8 @@ describe('canonical research workbench', () => { expect(host.textContent).toContain('40.00000000'); expect(host.textContent).toContain('order'); expect(host.textContent).toContain('Win rate and round-trip statistics are unavailable'); + expect(host.querySelector('[aria-label="Evaluation horizon"]')).toBeNull(); + expect(host.textContent).not.toContain('CAGR extrapolates'); value.financial.projection.fills = []; await flush(() => root!.render(createElement(CanonicalResults, { result: value, fillsOnly: true })) @@ -724,6 +726,69 @@ describe('canonical research workbench', () => { expect(host.textContent).toContain('No fills'); }); + test('explains a partial-session evaluation horizon alongside the unchanged retained CAGR', async () => { + const value = report(); + value.financial.reporting.tradeStart = Date.parse('2024-10-01T14:30:00Z'); + value.financial.reporting.tradeEnd = Date.parse('2024-10-01T20:00:00Z'); + value.financial.reporting.elapsedMs = '19800000'; + value.financial.reporting.sessions = value.financial.reporting.sessions.map(session => ({ + ...session, + periodStart: value.financial.reporting.tradeStart, + periodEnd: value.financial.reporting.tradeEnd, + partialStart: true, + partialEnd: true, + })); + // Retained metrics are presentation inputs; the view must not recalculate them from balances. + value.analytics.metrics.totalReturn = -0.0005457499930000553; + value.analytics.metrics.cagr = -0.5808255828609735; + const before = structuredClone(value); + await mount(createElement(CanonicalResults, { result: value })); + const horizon = host.querySelector('[aria-label="Evaluation horizon"]'); + expect(horizon?.textContent).toContain('2024-10-01T14:30:00.000Z'); + expect(horizon?.textContent).toContain('2024-10-01T20:00:00.000Z'); + expect(horizon?.textContent).toContain('5 hours, 30 minutes'); + const cagr = [...host.querySelectorAll('dt')].find(el => el.textContent === 'CAGR'); + expect(cagr?.nextElementSibling?.textContent).toBe('-58.08%'); + expect(cagr?.nextElementSibling?.getAttribute('title')).toBe('-0.5808255828609735'); + expect(cagr?.parentElement?.textContent).toContain( + 'CAGR extrapolates this evaluation interval to a 365-calendar-day year, including nontrading time. It is not an observed annual return or a forecast.' + ); + expect(host.textContent).toContain('Annualization for periodic statistics: 252 periods/year'); + expect(value).toEqual(before); + expect(requests).toHaveLength(0); + }); + + test('shows overnight calendar duration exactly and preserves unavailable CAGR reasons', async () => { + const value = report(); + // A Friday-to-Monday interval includes the weekend and retains sub-second precision. + value.financial.reporting.tradeStart = Date.parse('2024-10-04T14:30:00Z'); + value.financial.reporting.tradeEnd = Date.parse('2024-10-07T20:00:01.123Z'); + value.financial.reporting.elapsedMs = '279001123'; + value.analytics.metrics.cagr = null; + value.analytics.unavailable.cagr = 'nonfinite-result'; + await mount(createElement(CanonicalResults, { result: value })); + const horizon = host.querySelector('[aria-label="Evaluation horizon"]'); + expect(horizon?.textContent).toContain('2024-10-04T14:30:00.000Z'); + expect(horizon?.textContent).toContain('2024-10-07T20:00:01.123Z'); + expect(horizon?.textContent).toContain( + '3 days, 5 hours, 30 minutes, 1 second, 123 milliseconds' + ); + const cagr = [...host.querySelectorAll('dt')].find(el => el.textContent === 'CAGR'); + expect(cagr?.nextElementSibling?.textContent).toBe('Unavailable — nonfinite result'); + expect(cagr?.parentElement?.textContent).toContain('365-calendar-day year'); + value.financial.reporting.tradeEnd = value.financial.reporting.tradeStart; + value.financial.reporting.elapsedMs = '0'; + value.analytics.unavailable.cagr = 'zero-duration'; + await flush(() => root!.render(createElement(CanonicalResults, { result: value }))); + expect(host.querySelector('[aria-label="Evaluation horizon"]')?.textContent).toContain( + '0 seconds' + ); + expect( + [...host.querySelectorAll('dt')].find(el => el.textContent === 'CAGR')?.nextElementSibling + ?.textContent + ).toBe('Unavailable — zero duration'); + }); + test('setup validates explicit policy and saves exact non-midnight daily bounds without legacy policy leakage', async () => { const saves: CreateBacktestRequest[] = []; await mount(