fix(research): explain evaluation horizon and CAGR (RP04)
This commit is contained in:
parent
76eb1b1255
commit
302ba60e53
4 changed files with 117 additions and 2 deletions
|
|
@ -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({
|
|||
</section>
|
||||
<section className="space-y-3">
|
||||
<h3 className="font-semibold">Canonical metrics</h3>
|
||||
<dl aria-label="Evaluation horizon" className="grid gap-3 sm:grid-cols-3 text-sm">
|
||||
<div>
|
||||
<dt>Evaluation start (UTC)</dt>
|
||||
<dd>{canonicalTime(financial.reporting.tradeStart)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Evaluation end (UTC, exclusive)</dt>
|
||||
<dd>{canonicalTime(financial.reporting.tradeEnd)}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Elapsed calendar duration</dt>
|
||||
<dd>{calendarDuration(financial.reporting.elapsedMs)}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p className="text-sm text-text-secondary">
|
||||
{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)}
|
||||
</dd>
|
||||
{field.key === 'cagr' && (
|
||||
<dd className="text-xs text-text-secondary">
|
||||
CAGR extrapolates this evaluation interval to a 365-calendar-day year, including
|
||||
nontrading time. It is not an observed annual return or a forecast.
|
||||
</dd>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</dl>
|
||||
<p className="text-xs text-text-secondary">
|
||||
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)}%`}
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue