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
|
|
@ -20,9 +20,10 @@ const risk = returnStatistics(returns);
|
|||
|
||||
- `./returns`: simple/log returns, explicit percentage-point conversion, CAGR and
|
||||
annualization. Inputs must be finite. Invalid price baselines throw, not return zero.
|
||||
CAGR is `null` for zero elapsed time, nonpositive ending capital or unrepresentable
|
||||
output. Other nonrepresentable outputs throw. Annualization requires an explicit
|
||||
positive number of periods/year; return statistics below intentionally use daily data.
|
||||
CAGR is `null` for zero elapsed time, negative ending capital or unrepresentable
|
||||
output. With positive initial capital and elapsed time, zero terminal capital has
|
||||
CAGR −1. Other nonrepresentable outputs throw. Annualization requires an explicit
|
||||
positive number of periods/year.
|
||||
- `./indicators`: O(n) batch SMA plus trailing mean, population deviation and crossover
|
||||
helpers shared with the supported TypeScript strategies. SMA output index 0 belongs
|
||||
to source index `period - 1`; incomplete batch warm-up is `[]`, scalar warm-up is
|
||||
|
|
@ -42,8 +43,13 @@ const risk = returnStatistics(returns);
|
|||
identity: partition qualified venue/instrument IDs before calculating any feature.
|
||||
- `./analytics`: the existing tested fraction-based equity/drawdown, observed daily
|
||||
return/factor, closed-trade and performance calculations, moved from the orchestrator.
|
||||
Daily statistics use 252 periods/year, UTC grouping, sample volatility and explicit
|
||||
`null` for undefined ratios. Trade holding periods are minutes. Persisted strategy
|
||||
`returnStatistics(returns, annualRiskFree, periodsPerYear)` supports an explicit
|
||||
frequency and nullable risk-free input; omitted arguments retain the legacy 2%/252
|
||||
defaults. Null risk-free leaves target-dependent metrics unavailable while preserving
|
||||
independently defined volatility/tail statistics. `drawdownAnalysis` uses numeric
|
||||
timestamps without UTC grouping; `equityAnalysis` and legacy performance reporting
|
||||
retain their UTC grouping. Undefined ratios are `null`, sample deviation uses n−1,
|
||||
and downside deviation uses full-series RMS. Trade holding periods are minutes. Persisted strategy
|
||||
versions and execution/checkpoint behavior are unchanged. The legacy Kelly/leverage
|
||||
fields in `performanceAnalysis` remain compatibility heuristics, not optimizers.
|
||||
|
||||
|
|
|
|||
|
|
@ -27,7 +27,8 @@ export function ratio(numerator: number, denominator: number): number | null {
|
|||
: nullable(numerator / denominator);
|
||||
}
|
||||
|
||||
export function equityAnalysis(points: readonly EquityPoint[], initialCapital: number) {
|
||||
/** Sampled drawdowns only; no UTC grouping or JavaScript Date range restriction. */
|
||||
export function drawdownAnalysis(points: readonly EquityPoint[], initialCapital: number) {
|
||||
if (finite(initialCapital) <= 0) {
|
||||
throw new Error('Initial capital must be positive');
|
||||
}
|
||||
|
|
@ -37,8 +38,6 @@ export function equityAnalysis(points: readonly EquityPoint[], initialCapital: n
|
|||
let maxDrawdown = 0;
|
||||
const periods: DrawdownPeriod[] = [];
|
||||
const underwater: EquityPoint[] = [];
|
||||
const daily = new Map<string, number>();
|
||||
const monthly = new Map<string, number>();
|
||||
for (const [index, point] of points.entries()) {
|
||||
finite(point.timestamp);
|
||||
finite(point.value);
|
||||
|
|
@ -46,9 +45,6 @@ export function equityAnalysis(points: readonly EquityPoint[], initialCapital: n
|
|||
throw new Error('Equity observations must be ordered');
|
||||
}
|
||||
previousTimestamp = point.timestamp;
|
||||
const iso = new Date(point.timestamp).toISOString();
|
||||
daily.set(iso.slice(0, 10), point.value);
|
||||
monthly.set(iso.slice(0, 7), point.value);
|
||||
if (point.value >= peak) {
|
||||
if (active) {
|
||||
periods.push({
|
||||
|
|
@ -80,6 +76,24 @@ export function equityAnalysis(points: readonly EquityPoint[], initialCapital: n
|
|||
if (active) {
|
||||
periods.push(active);
|
||||
}
|
||||
return {
|
||||
maxDrawdown,
|
||||
currentDrawdown: Math.abs(underwater[underwater.length - 1]?.value ?? 0),
|
||||
maxDrawdownDuration: periods.reduce((max, period) => Math.max(max, period.duration), 0),
|
||||
periods,
|
||||
underwater,
|
||||
};
|
||||
}
|
||||
|
||||
export function equityAnalysis(points: readonly EquityPoint[], initialCapital: number) {
|
||||
const drawdown = drawdownAnalysis(points, initialCapital);
|
||||
const daily = new Map<string, number>();
|
||||
const monthly = new Map<string, number>();
|
||||
for (const point of points) {
|
||||
const iso = new Date(point.timestamp).toISOString();
|
||||
daily.set(iso.slice(0, 10), point.value);
|
||||
monthly.set(iso.slice(0, 7), point.value);
|
||||
}
|
||||
const first = points[0];
|
||||
const last = points[points.length - 1];
|
||||
const elapsedDays = first && last ? (last.timestamp - first.timestamp) / dayMs : 0;
|
||||
|
|
@ -93,11 +107,11 @@ export function equityAnalysis(points: readonly EquityPoint[], initialCapital: n
|
|||
totalReturn,
|
||||
annualizedReturn,
|
||||
elapsedDays,
|
||||
maxDrawdown,
|
||||
currentDrawdown: Math.abs(underwater[underwater.length - 1]?.value ?? 0),
|
||||
maxDrawdownDuration: periods.reduce((max, period) => Math.max(max, period.duration), 0),
|
||||
periods,
|
||||
underwater,
|
||||
maxDrawdown: drawdown.maxDrawdown,
|
||||
currentDrawdown: drawdown.currentDrawdown,
|
||||
maxDrawdownDuration: drawdown.maxDrawdownDuration,
|
||||
periods: drawdown.periods,
|
||||
underwater: drawdown.underwater,
|
||||
// First observed period uses starting capital; no first-day loss/gain is discarded.
|
||||
dailyReturns: [...periodReturns(daily, initialCapital).values()],
|
||||
monthlyReturns: Object.fromEntries(periodReturns(monthly, initialCapital)),
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
export { dayMs, equityAnalysis, finite, nullable, ratio } from './equity';
|
||||
export { dayMs, drawdownAnalysis, equityAnalysis, finite, nullable, ratio } from './equity';
|
||||
export type { DrawdownPeriod, EquityPoint } from './equity';
|
||||
export { factorStatistics, mean, returnStatistics, sampleDeviation } from './return-statistics';
|
||||
export { tradeStatistics } from './trade-statistics';
|
||||
|
|
|
|||
|
|
@ -12,7 +12,15 @@ export function mean(values: readonly number[]): number | null {
|
|||
}
|
||||
export function sampleDeviation(values: readonly number[]): number | null {
|
||||
const average = mean(values);
|
||||
if (values.length < 2 || average === null) {
|
||||
if (values.length < 2) {
|
||||
return null;
|
||||
}
|
||||
// Summing identical nonbinary fractions can perturb their mean. An exactly
|
||||
// constant finite series has zero variance, without an arbitrary epsilon.
|
||||
if (values.every(value => value === values[0])) {
|
||||
return 0;
|
||||
}
|
||||
if (average === null) {
|
||||
return null;
|
||||
}
|
||||
return nullable(
|
||||
|
|
@ -20,26 +28,40 @@ export function sampleDeviation(values: readonly number[]): number | null {
|
|||
);
|
||||
}
|
||||
|
||||
/** Observed daily fractions; 252 periods/year, arithmetic excess returns, full-series downside RMS. */
|
||||
export function returnStatistics(returns: readonly number[], annualRiskFree = 0.02) {
|
||||
finite(annualRiskFree);
|
||||
/** Periodic fractions, arithmetic excess returns and full-series downside RMS.
|
||||
* Existing callers retain 252 periods/year and 2% annual risk-free defaults.
|
||||
* Explicit null means the target is unavailable, not an assumed zero rate. */
|
||||
export function returnStatistics(
|
||||
returns: readonly number[],
|
||||
annualRiskFree: number | null = 0.02,
|
||||
periodsPerYear = 252
|
||||
) {
|
||||
if (annualRiskFree !== null) {
|
||||
finite(annualRiskFree);
|
||||
}
|
||||
if (finite(periodsPerYear) <= 0) {
|
||||
throw new RangeError('Periods per year must be positive');
|
||||
}
|
||||
for (const value of returns) {
|
||||
finite(value);
|
||||
}
|
||||
const average = mean(returns);
|
||||
const deviation = sampleDeviation(returns);
|
||||
const annualExcess = average === null ? null : nullable(average * 252 - annualRiskFree);
|
||||
const volatility = deviation === null ? null : nullable(deviation * Math.sqrt(252));
|
||||
const annualExcess =
|
||||
average === null || annualRiskFree === null
|
||||
? null
|
||||
: nullable(average * periodsPerYear - annualRiskFree);
|
||||
const volatility = deviation === null ? null : nullable(deviation * Math.sqrt(periodsPerYear));
|
||||
const downsideDeviation =
|
||||
returns.length < 2
|
||||
returns.length < 2 || annualRiskFree === null
|
||||
? null
|
||||
: nullable(
|
||||
Math.sqrt(
|
||||
returns.reduce(
|
||||
(sum, value) => sum + Math.min(value - annualRiskFree / 252, 0) ** 2,
|
||||
(sum, value) => sum + Math.min(value - annualRiskFree / periodsPerYear, 0) ** 2,
|
||||
0
|
||||
) / returns.length
|
||||
) * Math.sqrt(252)
|
||||
) * Math.sqrt(periodsPerYear)
|
||||
);
|
||||
const sorted = [...returns].sort((a, b) => a - b);
|
||||
const tail = (confidence: number) => {
|
||||
|
|
|
|||
|
|
@ -54,9 +54,11 @@ export function cagr(start: number, end: number, years: number): number | null {
|
|||
if (finite(years) < 0) {
|
||||
throw new RangeError('Years must be nonnegative');
|
||||
}
|
||||
return years === 0 || end <= 0
|
||||
return years === 0 || end < 0
|
||||
? null
|
||||
: nullable(Math.expm1((Math.log(end) - Math.log(start)) / years));
|
||||
: end === 0
|
||||
? -1
|
||||
: nullable(Math.expm1((Math.log(end) - Math.log(start)) / years));
|
||||
}
|
||||
|
||||
export function annualizeReturn(periodicReturn: number, periodsPerYear: number): number {
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ describe('reviewed shared calculation contracts', () => {
|
|||
test('annualization has explicit undefined CAGR and validates sampling units', () => {
|
||||
expect(cagr(100, 121, 2)).toBeCloseTo(0.1);
|
||||
expect(cagr(100, 110, 0)).toBeNull();
|
||||
expect(cagr(100, 0, 1)).toBeNull();
|
||||
expect(cagr(100, 0, 1)).toBe(-1);
|
||||
expect(cagr(100, -10, 1)).toBeNull();
|
||||
expect(cagr(1, 2, Number.MIN_VALUE)).toBeNull();
|
||||
expect(() => cagr(0, 10, 1)).toThrow();
|
||||
|
|
@ -85,7 +85,7 @@ describe('reviewed shared calculation contracts', () => {
|
|||
for (let end = 1; end <= prices.length; end++) {
|
||||
const prefix = prices.slice(0, end);
|
||||
expect(sma(prices, 3).slice(0, Math.max(0, end - 2))).toEqual(sma(prefix, 3));
|
||||
expect(trailingMean(prefix, 3)).toBe(sma(prefix, 3).at(-1));
|
||||
expect<number | undefined>(trailingMean(prefix, 3)).toBe(sma(prefix, 3).at(-1));
|
||||
}
|
||||
expect(movingAverageCrossover([3, 2, 1, 4], 2, 3)?.goldenCross).toBe(true);
|
||||
expect(() => sma([1, 2], 0)).toThrow();
|
||||
|
|
|
|||
45
libs/calculations/test/reporting-primitives.test.ts
Normal file
45
libs/calculations/test/reporting-primitives.test.ts
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { drawdownAnalysis, equityAnalysis } from '../src/analytics/equity';
|
||||
import { cagr } from '../src/returns';
|
||||
|
||||
test('sampled drawdown handles safe-integer timestamps beyond JavaScript Date range', () => {
|
||||
const points = [
|
||||
{ timestamp: -Number.MAX_SAFE_INTEGER, value: 100 },
|
||||
{ timestamp: 0, value: 80 },
|
||||
{ timestamp: Number.MAX_SAFE_INTEGER, value: 90 },
|
||||
];
|
||||
expect(drawdownAnalysis(points, 100).maxDrawdown).toBeCloseTo(0.2);
|
||||
expect(drawdownAnalysis(points, 100).currentDrawdown).toBeCloseTo(0.1);
|
||||
expect(() => drawdownAnalysis([...points].reverse(), 100)).toThrow('ordered');
|
||||
expect(() => drawdownAnalysis(points, 0)).toThrow('positive');
|
||||
});
|
||||
|
||||
test('extracted drawdowns preserve the legacy equity analysis values and recovery periods', () => {
|
||||
const points = [100, 110, 80, 90, 120, 100].map((value, i) => ({
|
||||
timestamp: i * 86400000,
|
||||
value,
|
||||
}));
|
||||
const sampled = drawdownAnalysis(points, 100);
|
||||
const legacy = equityAnalysis(points, 100);
|
||||
expect(legacy).toMatchObject(sampled);
|
||||
expect(sampled.periods).toHaveLength(2);
|
||||
expect(sampled.periods[0]?.recovery).toBe(4);
|
||||
expect(sampled.periods[1]?.recovery).toBeNull();
|
||||
});
|
||||
|
||||
test('CAGR zero terminal is total loss for positive elapsed time while negative terminal is unsupported', () => {
|
||||
expect(cagr(100, 0, 0.5)).toBe(-1);
|
||||
expect(cagr(100, 0, 0)).toBeNull();
|
||||
expect(cagr(100, -1, 1)).toBeNull();
|
||||
expect(cagr(100, 121, 2)).toBeCloseTo(0.1);
|
||||
// Legacy UTC equity reporting retains its historical zero-terminal convention.
|
||||
expect(
|
||||
equityAnalysis(
|
||||
[
|
||||
{ timestamp: 0, value: 100 },
|
||||
{ timestamp: 86400000, value: 0 },
|
||||
],
|
||||
100
|
||||
).annualizedReturn
|
||||
).toBeNull();
|
||||
});
|
||||
83
libs/calculations/test/return-statistics.test.ts
Normal file
83
libs/calculations/test/return-statistics.test.ts
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { returnStatistics, sampleDeviation } from '../src/analytics/return-statistics';
|
||||
|
||||
describe('explicit periodic return policy', () => {
|
||||
test('legacy defaults remain equivalent to explicit 252 periods and 2% annual risk-free', () => {
|
||||
const returns = [-0.02, 0.01, 0.03, -0.01];
|
||||
expect(returnStatistics(returns)).toEqual(returnStatistics(returns, 0.02, 252));
|
||||
});
|
||||
|
||||
test('arithmetic excess and full-series downside RMS use the declared period count', () => {
|
||||
// Mean=.01, sample variance=.0008; periodic target=.12/12=.01.
|
||||
// Full-series downside variance=(.02^2+0)/2=.0002.
|
||||
const result = returnStatistics([-0.01, 0.03], 0.12, 12);
|
||||
expect(result.volatility).toBeCloseTo(Math.sqrt(0.0008 * 12));
|
||||
expect(result.downsideDeviation).toBeCloseTo(Math.sqrt(0.0002 * 12));
|
||||
expect(result.sharpeRatio).toBeCloseTo(0);
|
||||
expect(result.sortinoRatio).toBeCloseTo(0);
|
||||
expect(returnStatistics([-0.01, 0.03], 0, 4).sharpeRatio).toBeCloseTo(
|
||||
0.04 / Math.sqrt(0.0008 * 4)
|
||||
);
|
||||
});
|
||||
|
||||
test('constant_negative_returns have zero variance but nonzero downside and negative Sortino', () => {
|
||||
for (const value of [-0.01, -0.1]) {
|
||||
const result = returnStatistics([value, value, value], 0, 252);
|
||||
expect(sampleDeviation([value, value, value])).toBe(0);
|
||||
expect(result.volatility).toBe(0);
|
||||
expect(result.sharpeRatio).toBeNull();
|
||||
expect(result.downsideDeviation).toBeCloseTo(-value * Math.sqrt(252));
|
||||
expect(result.sortinoRatio).toBeCloseTo(-Math.sqrt(252));
|
||||
}
|
||||
});
|
||||
|
||||
test('zero_variance is exact without treating a small genuine deviation as zero', () => {
|
||||
expect(sampleDeviation([0.1, 0.1, 0.1])).toBe(0);
|
||||
expect(sampleDeviation([Number.MAX_VALUE, Number.MAX_VALUE])).toBe(0);
|
||||
expect(sampleDeviation([0.1, 0.1 + Number.EPSILON])).toBeGreaterThan(0);
|
||||
expect(returnStatistics([0, 0], 0)).toMatchObject({
|
||||
volatility: 0,
|
||||
downsideDeviation: 0,
|
||||
sharpeRatio: null,
|
||||
sortinoRatio: null,
|
||||
});
|
||||
expect(returnStatistics([0.01, 0.02], 0).sortinoRatio).toBeNull();
|
||||
expect(returnStatistics([0.01], 0).volatility).toBeNull();
|
||||
expect(sampleDeviation([])).toBeNull();
|
||||
expect(() => sampleDeviation([NaN, NaN])).toThrow('finite');
|
||||
});
|
||||
|
||||
test('missing risk-free leaves independent volatility and tail statistics available', () => {
|
||||
const returns = Array.from({ length: 100 }, (_, i) => i / 1000 - 0.05);
|
||||
const missing = returnStatistics(returns, null, 365);
|
||||
const explicitZero = returnStatistics(returns, 0, 365);
|
||||
expect(missing).toMatchObject({
|
||||
sharpeRatio: null,
|
||||
sortinoRatio: null,
|
||||
downsideDeviation: null,
|
||||
});
|
||||
for (const key of [
|
||||
'volatility',
|
||||
'var95',
|
||||
'cvar95',
|
||||
'var99',
|
||||
'skewness',
|
||||
'kurtosis',
|
||||
'tailRatio',
|
||||
] as const) {
|
||||
expect(missing[key]).toEqual(explicitZero[key]);
|
||||
}
|
||||
expect(explicitZero.sharpeRatio).not.toBeNull();
|
||||
});
|
||||
|
||||
test('invalid rates, period counts and observations reject', () => {
|
||||
for (const periods of [0, -1, NaN, Infinity]) {
|
||||
expect(() => returnStatistics([], 0, periods)).toThrow();
|
||||
}
|
||||
for (const rate of [NaN, Infinity, -Infinity]) {
|
||||
expect(() => returnStatistics([], rate, 252)).toThrow();
|
||||
}
|
||||
expect(() => returnStatistics([Infinity], null, 252)).toThrow();
|
||||
expect(() => returnStatistics(Array<number>(2), null, 252)).toThrow();
|
||||
});
|
||||
});
|
||||
85
libs/core/types/src/canonical-analytics.ts
Normal file
85
libs/core/types/src/canonical-analytics.ts
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
/** Explicit reporting inputs, independent from financial/execution policy. */
|
||||
export interface CanonicalMetricsInput {
|
||||
version: 1;
|
||||
periodsPerYear: number;
|
||||
annualRiskFreeRate: number | null;
|
||||
/** Benchmark-dependent reporting is unsupported in version 1. */
|
||||
benchmark: null;
|
||||
}
|
||||
|
||||
export interface CanonicalMetricsPolicy extends CanonicalMetricsInput {
|
||||
calendarId: string;
|
||||
calendarRevision: string;
|
||||
sampling: 'account-boundary-after-observations-v1';
|
||||
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: 'elapsed-calendar-time';
|
||||
cagrBasis: 'elapsed-calendar-days-365';
|
||||
zeroTerminalCagr: 'negative-one-for-positive-elapsed-time';
|
||||
}
|
||||
|
||||
export type CanonicalMetricUnavailableReason =
|
||||
| 'nonpositive-baseline'
|
||||
| 'negative-terminal-equity'
|
||||
| 'zero-duration'
|
||||
| 'nonfinite-result'
|
||||
| 'undefined-period-return'
|
||||
| 'insufficient-periods'
|
||||
| 'missing-risk-free'
|
||||
| 'missing-benchmark'
|
||||
| 'zero-variance'
|
||||
| 'zero-downside-deviation'
|
||||
| 'unsupported-round-trips';
|
||||
|
||||
export interface CanonicalSessionReturn {
|
||||
sessionId: string;
|
||||
periodStart: number;
|
||||
periodEnd: number;
|
||||
partialStart: boolean;
|
||||
partialEnd: boolean;
|
||||
value: number | null;
|
||||
/** Complete period with a defined return; an undefined complete period invalidates
|
||||
* the entire periodic-statistics sequence, not just this individual sample. */
|
||||
eligible: boolean;
|
||||
reason?: 'nonpositive-baseline' | 'nonfinite-result';
|
||||
}
|
||||
|
||||
/** Statistical numbers are approximate reporting values, never ledger postings. */
|
||||
export interface CanonicalMetrics {
|
||||
totalReturn: number | null;
|
||||
cagr: number | null;
|
||||
maxDrawdown: number | null;
|
||||
exposureTime: number | null;
|
||||
volatility: number | null;
|
||||
downsideDeviation: number | null;
|
||||
sharpeRatio: number | null;
|
||||
sortinoRatio: number | null;
|
||||
var95: number | null;
|
||||
cvar95: number | null;
|
||||
var99: number | null;
|
||||
alpha: null;
|
||||
beta: null;
|
||||
informationRatio: null;
|
||||
roundTripCount: null;
|
||||
winRate: null;
|
||||
profitFactor: null;
|
||||
avgWin: null;
|
||||
avgLoss: null;
|
||||
}
|
||||
|
||||
export interface CanonicalBacktestAnalytics {
|
||||
version: 1;
|
||||
policy: CanonicalMetricsPolicy;
|
||||
sessionReturns: CanonicalSessionReturn[];
|
||||
completePeriodCount: number;
|
||||
/** Zero if any complete-period return is undefined; do not shorten the sequence. */
|
||||
periodicSampleCount: number;
|
||||
fillCount: number;
|
||||
metrics: CanonicalMetrics;
|
||||
unavailable: Partial<Record<keyof CanonicalMetrics, CanonicalMetricUnavailableReason>>;
|
||||
}
|
||||
|
|
@ -51,6 +51,14 @@ export type {
|
|||
BacktestRunTrade,
|
||||
BacktestRunResult,
|
||||
} from './backtest-run';
|
||||
export type {
|
||||
CanonicalMetricsInput,
|
||||
CanonicalMetricsPolicy,
|
||||
CanonicalMetricUnavailableReason,
|
||||
CanonicalSessionReturn,
|
||||
CanonicalMetrics,
|
||||
CanonicalBacktestAnalytics,
|
||||
} from './canonical-analytics';
|
||||
|
||||
// Export helper types
|
||||
export type { HasClose, HasOHLC, HasTimestamp, HasVolume } from './helpers';
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue