refactor: share research domain and simplify application workflows
This commit is contained in:
parent
805a9f8fd4
commit
8c39ccf7ea
58 changed files with 3805 additions and 3081 deletions
152
libs/research/src/dataset-contracts.ts
Normal file
152
libs/research/src/dataset-contracts.ts
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
import { z } from 'zod';
|
||||
|
||||
export const text = z.string().min(1);
|
||||
export const instant = z.number().int().nonnegative().max(8_640_000_000_000_000);
|
||||
export const sequence = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
export const price = z.number().finite().positive();
|
||||
export const day = z
|
||||
.string()
|
||||
.regex(/^\d{4}-\d{2}-\d{2}$/)
|
||||
.refine(value => {
|
||||
const parsed = Date.parse(value);
|
||||
return Number.isFinite(parsed) && new Date(parsed).toISOString().slice(0, 10) === value;
|
||||
}, 'Invalid session date');
|
||||
export const hash = z
|
||||
.string()
|
||||
.length(64)
|
||||
.regex(/^[a-f0-9]{64}$/);
|
||||
export const metadataSchema = z
|
||||
.object({
|
||||
calendars: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
id: text,
|
||||
venue: text,
|
||||
timeZone: text,
|
||||
revision: text,
|
||||
source: text,
|
||||
startDate: day,
|
||||
endDate: day,
|
||||
sessions: z
|
||||
.array(z.object({ date: day, open: instant, close: instant }).strict())
|
||||
.min(1),
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.min(1),
|
||||
series: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
id: text,
|
||||
instrumentId: text,
|
||||
interval: z.enum(['1m', '5m', '15m', '1h', '1d']),
|
||||
calendarId: text,
|
||||
venue: text,
|
||||
source: z.object({ provider: text, revision: text }).strict(),
|
||||
timestamp: z.enum(['session-date', 'interval-start', 'interval-end']),
|
||||
availability: z.enum(['explicit', 'interval-end-assumption']),
|
||||
adjustment: z.enum(['raw', 'provider-adjusted']),
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.min(1),
|
||||
executionSeries: z.array(z.object({ instrumentId: text, seriesId: text }).strict()).min(1),
|
||||
bounds: z.object({ warmupStart: instant, tradeStart: instant, tradeEnd: instant }).strict(),
|
||||
universe: z
|
||||
.object({
|
||||
selection: z.enum(['point-in-time', 'current-constituents', 'unknown']),
|
||||
asOf: instant.nullable(),
|
||||
revision: text,
|
||||
instrumentIds: z.array(text).min(1),
|
||||
})
|
||||
.strict(),
|
||||
corporateActions: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
instrumentId: text,
|
||||
status: z.enum(['unknown', 'action-free', 'known-actions']),
|
||||
start: instant,
|
||||
end: instant,
|
||||
revision: text,
|
||||
actions: z.array(
|
||||
z
|
||||
.object({
|
||||
effectiveAt: instant,
|
||||
kind: z.enum(['split', 'dividend', 'other']),
|
||||
reference: text,
|
||||
})
|
||||
.strict()
|
||||
),
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.min(1),
|
||||
})
|
||||
.strict();
|
||||
export const manifestSchema = metadataSchema
|
||||
.extend({
|
||||
version: z.literal(2),
|
||||
hash,
|
||||
normalizationRevision: z.literal('historical-normalization-v2'),
|
||||
parentDatasetHash: hash.nullable(),
|
||||
volumePolicy: z.literal('reported'),
|
||||
qualityPolicy: z.literal('reject-invalid-no-interpolation'),
|
||||
intradayPolicy: z.literal('full-duration-session-contained'),
|
||||
eligibility: z.enum(['eligible', 'exploratory', 'ineligible']),
|
||||
limitations: z.array(text),
|
||||
barCount: z.number().int().positive(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** Response shapes add cheap consistency checks; content/hash validation stays server-side. */
|
||||
export const responseMetadataSchema = metadataSchema.extend({
|
||||
calendars: metadataSchema.shape.calendars.element
|
||||
.extend({
|
||||
sessions: metadataSchema.shape.calendars.element.shape.sessions.element
|
||||
.refine(value => value.open < value.close)
|
||||
.array()
|
||||
.min(1),
|
||||
})
|
||||
.array()
|
||||
.min(1),
|
||||
bounds: metadataSchema.shape.bounds.refine(
|
||||
value => value.warmupStart <= value.tradeStart && value.tradeStart < value.tradeEnd
|
||||
),
|
||||
});
|
||||
export const preparationManifestSchema = responseMetadataSchema
|
||||
.extend({
|
||||
...manifestSchema.omit({
|
||||
calendars: true,
|
||||
series: true,
|
||||
executionSeries: true,
|
||||
bounds: true,
|
||||
universe: true,
|
||||
corporateActions: true,
|
||||
}).shape,
|
||||
parentDatasetHash: z.null(),
|
||||
barCount: z.number().int().positive().safe(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** Structural workbench policy, not authentication of retained dataset bytes. */
|
||||
export function datasetUnavailableReason(manifest: {
|
||||
eligibility: string;
|
||||
executionSeries: readonly unknown[];
|
||||
series: readonly unknown[];
|
||||
universe: { instrumentIds: readonly string[] };
|
||||
}): string | null {
|
||||
if (manifest.eligibility !== 'eligible') {
|
||||
return 'Canonical research requires an eligible dataset with known timing and action coverage';
|
||||
}
|
||||
if (
|
||||
manifest.executionSeries.length !== 1 ||
|
||||
manifest.series.length !== 1 ||
|
||||
manifest.universe.instrumentIds.length !== 1
|
||||
) {
|
||||
return 'Canonical workbench currently supports one execution asset and one retained series';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
532
libs/research/src/datasets.ts
Normal file
532
libs/research/src/datasets.ts
Normal file
|
|
@ -0,0 +1,532 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
parseInstrumentId,
|
||||
type HistoricalBarV2,
|
||||
type HistoricalDatasetInputV2,
|
||||
type HistoricalDatasetMetadataV2,
|
||||
type HistoricalDatasetV2,
|
||||
} from '@stock-bot/types';
|
||||
import {
|
||||
day,
|
||||
hash,
|
||||
instant,
|
||||
manifestSchema,
|
||||
metadataSchema,
|
||||
price,
|
||||
sequence,
|
||||
text,
|
||||
} from './dataset-contracts';
|
||||
|
||||
const prices = {
|
||||
open: price,
|
||||
high: price,
|
||||
low: price,
|
||||
close: price,
|
||||
volume: z.number().finite().nonnegative(),
|
||||
};
|
||||
const sourceBarSchema = z
|
||||
.object({
|
||||
seriesId: text,
|
||||
timestamp: z.union([day, instant]),
|
||||
availableAt: instant.optional(),
|
||||
sourceSequence: sequence,
|
||||
...prices,
|
||||
vwap: price.nullable().optional(),
|
||||
})
|
||||
.strict();
|
||||
const barSchema = z
|
||||
.object({
|
||||
seriesId: text,
|
||||
instrumentId: text,
|
||||
intervalStart: instant,
|
||||
intervalEnd: instant,
|
||||
eventTime: instant,
|
||||
availableAt: instant,
|
||||
sourceSequence: sequence,
|
||||
...prices,
|
||||
vwap: price.nullable(),
|
||||
})
|
||||
.strict();
|
||||
const durations = { '1m': 60_000, '5m': 300_000, '15m': 900_000, '1h': 3_600_000 };
|
||||
const prepared = new WeakSet<object>();
|
||||
const compare = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
|
||||
|
||||
function unique(values: readonly string[], label: string): void {
|
||||
if (new Set(values).size !== values.length) {
|
||||
throw new Error(`Duplicate ${label}`);
|
||||
}
|
||||
}
|
||||
|
||||
function parseMetadata(input: unknown) {
|
||||
const metadata = metadataSchema.parse(input);
|
||||
const { bounds, universe } = metadata;
|
||||
if (bounds.warmupStart > bounds.tradeStart || bounds.tradeStart >= bounds.tradeEnd) {
|
||||
throw new Error('Invalid warmup/trade bounds');
|
||||
}
|
||||
unique(
|
||||
metadata.calendars.map(c => c.id),
|
||||
'calendar'
|
||||
);
|
||||
metadata.calendars.sort((a, b) => compare(a.id, b.id));
|
||||
for (const calendar of metadata.calendars) {
|
||||
if (calendar.startDate >= calendar.endDate) {
|
||||
throw new Error('Invalid calendar coverage');
|
||||
}
|
||||
const formatter = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: calendar.timeZone,
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
});
|
||||
const localDate = (time: number) => {
|
||||
const parts = formatter.formatToParts(time);
|
||||
return ['year', 'month', 'day']
|
||||
.map(key => parts.find(part => part.type === key)?.value ?? '')
|
||||
.join('-');
|
||||
};
|
||||
if (
|
||||
localDate(bounds.warmupStart) < calendar.startDate ||
|
||||
localDate(bounds.tradeEnd - 1) >= calendar.endDate
|
||||
) {
|
||||
throw new Error('Calendar coverage must include warmup and trade bounds');
|
||||
}
|
||||
unique(
|
||||
calendar.sessions.map(s => s.date),
|
||||
'calendar session'
|
||||
);
|
||||
calendar.sessions.sort((a, b) => compare(a.date, b.date));
|
||||
let previousClose = -1;
|
||||
for (const session of calendar.sessions) {
|
||||
if (
|
||||
session.date < calendar.startDate ||
|
||||
session.date >= calendar.endDate ||
|
||||
session.open >= session.close ||
|
||||
session.open < previousClose ||
|
||||
localDate(session.open) !== session.date ||
|
||||
localDate(session.close) !== session.date
|
||||
) {
|
||||
throw new Error('Invalid retained calendar session');
|
||||
}
|
||||
previousClose = session.close;
|
||||
}
|
||||
}
|
||||
unique(
|
||||
metadata.series.map(s => s.id),
|
||||
'series'
|
||||
);
|
||||
metadata.series.sort((a, b) => compare(a.id, b.id));
|
||||
for (const series of metadata.series) {
|
||||
parseInstrumentId(series.instrumentId);
|
||||
const calendar = metadata.calendars.find(c => c.id === series.calendarId);
|
||||
if (
|
||||
!calendar ||
|
||||
calendar.venue !== series.venue ||
|
||||
(series.interval === '1d') !== (series.timestamp === 'session-date')
|
||||
) {
|
||||
throw new Error('Unknown calendar/venue or incompatible timestamp mapping');
|
||||
}
|
||||
}
|
||||
const instruments = [...new Set(metadata.series.map(s => s.instrumentId))].sort(compare);
|
||||
unique(
|
||||
metadata.executionSeries.map(s => s.instrumentId),
|
||||
'execution instrument'
|
||||
);
|
||||
unique(
|
||||
metadata.executionSeries.map(s => s.seriesId),
|
||||
'execution series'
|
||||
);
|
||||
metadata.executionSeries.sort((a, b) => compare(a.instrumentId, b.instrumentId));
|
||||
if (
|
||||
JSON.stringify(metadata.executionSeries.map(s => s.instrumentId)) !==
|
||||
JSON.stringify(instruments) ||
|
||||
metadata.executionSeries.some(
|
||||
e => !metadata.series.some(s => s.id === e.seriesId && s.instrumentId === e.instrumentId)
|
||||
)
|
||||
) {
|
||||
throw new Error('Choose exactly one execution series per instrument');
|
||||
}
|
||||
unique(universe.instrumentIds, 'universe instrument');
|
||||
universe.instrumentIds.sort(compare);
|
||||
if (
|
||||
JSON.stringify(universe.instrumentIds) !== JSON.stringify(instruments) ||
|
||||
(universe.selection === 'point-in-time' &&
|
||||
(universe.asOf === null || universe.asOf > bounds.tradeStart))
|
||||
) {
|
||||
throw new Error('Invalid universe/as-of selection');
|
||||
}
|
||||
unique(
|
||||
metadata.corporateActions.map(c => c.instrumentId),
|
||||
'action coverage'
|
||||
);
|
||||
metadata.corporateActions.sort((a, b) => compare(a.instrumentId, b.instrumentId));
|
||||
if (
|
||||
JSON.stringify(metadata.corporateActions.map(c => c.instrumentId)) !==
|
||||
JSON.stringify(instruments)
|
||||
) {
|
||||
throw new Error('Corporate-action coverage required for every instrument');
|
||||
}
|
||||
for (const coverage of metadata.corporateActions) {
|
||||
if (
|
||||
coverage.start > bounds.warmupStart ||
|
||||
coverage.end < bounds.tradeEnd ||
|
||||
coverage.start >= coverage.end ||
|
||||
(coverage.status === 'known-actions') !== coverage.actions.length > 0 ||
|
||||
coverage.actions.some(a => a.effectiveAt < coverage.start || a.effectiveAt >= coverage.end)
|
||||
) {
|
||||
throw new Error('Invalid corporate-action coverage');
|
||||
}
|
||||
unique(
|
||||
coverage.actions.map(a => a.reference),
|
||||
'corporate-action reference'
|
||||
);
|
||||
coverage.actions.sort(
|
||||
(a, b) => a.effectiveAt - b.effectiveAt || compare(a.reference, b.reference)
|
||||
);
|
||||
}
|
||||
return metadata;
|
||||
}
|
||||
|
||||
/** Validate and detach complete operator declarations before a stored-source read. */
|
||||
export function parseHistoricalDatasetMetadataV2(input: unknown): HistoricalDatasetMetadataV2 {
|
||||
return parseMetadata(input);
|
||||
}
|
||||
|
||||
function assess(metadata: HistoricalDatasetMetadataV2, parentDatasetHash: string | null) {
|
||||
const limitations = [
|
||||
'Open liquidity must use previously available volume; intraday partial bars are unsupported',
|
||||
];
|
||||
let eligibility: 'eligible' | 'exploratory' | 'ineligible' = 'eligible';
|
||||
if (parentDatasetHash) {
|
||||
limitations.push('Legacy v1 VWAP provenance is unavailable; converted VWAP is null');
|
||||
}
|
||||
if (metadata.universe.selection !== 'point-in-time') {
|
||||
eligibility = 'exploratory';
|
||||
limitations.push('Universe selection is not verified point-in-time');
|
||||
}
|
||||
for (const coverage of metadata.corporateActions) {
|
||||
if (coverage.status === 'unknown') {
|
||||
if (eligibility !== 'ineligible') {
|
||||
eligibility = 'exploratory';
|
||||
}
|
||||
limitations.push(`Unknown corporate-action coverage: ${coverage.instrumentId}`);
|
||||
}
|
||||
if (
|
||||
coverage.actions.some(
|
||||
a =>
|
||||
a.effectiveAt >= metadata.bounds.warmupStart && a.effectiveAt < metadata.bounds.tradeEnd
|
||||
)
|
||||
) {
|
||||
eligibility = 'ineligible';
|
||||
limitations.push(`Unsupported corporate actions in dataset range: ${coverage.instrumentId}`);
|
||||
}
|
||||
}
|
||||
for (const selection of metadata.executionSeries) {
|
||||
if (metadata.series.find(s => s.id === selection.seriesId)?.adjustment !== 'raw') {
|
||||
eligibility = 'ineligible';
|
||||
limitations.push(`Adjusted prices cannot execute: ${selection.seriesId}`);
|
||||
}
|
||||
}
|
||||
for (const series of metadata.series) {
|
||||
if (series.availability === 'interval-end-assumption') {
|
||||
limitations.push(`Availability assumes zero data delay at interval end: ${series.id}`);
|
||||
}
|
||||
}
|
||||
return { eligibility, limitations };
|
||||
}
|
||||
|
||||
/** Per-preparation indexes, not a cross-dataset cache. Session lookup is logarithmic. */
|
||||
function indexMetadata(metadata: HistoricalDatasetMetadataV2) {
|
||||
return {
|
||||
series: new Map(metadata.series.map(series => [series.id, series])),
|
||||
calendars: new Map(
|
||||
metadata.calendars.map(calendar => [
|
||||
calendar.id,
|
||||
{
|
||||
...calendar,
|
||||
byDate: new Map(calendar.sessions.map(session => [session.date, session])),
|
||||
},
|
||||
])
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function containingSession(
|
||||
sessions: HistoricalDatasetMetadataV2['calendars'][number]['sessions'],
|
||||
start: number,
|
||||
end: number
|
||||
) {
|
||||
let low = 0,
|
||||
high = sessions.length;
|
||||
while (low < high) {
|
||||
const middle = Math.floor((low + high) / 2);
|
||||
if ((sessions[middle]?.open ?? Infinity) <= start) {
|
||||
low = middle + 1;
|
||||
} else {
|
||||
high = middle;
|
||||
}
|
||||
}
|
||||
const session = sessions[low - 1];
|
||||
return session && end <= session.close ? session : undefined;
|
||||
}
|
||||
|
||||
function validateBars(
|
||||
metadata: HistoricalDatasetMetadataV2,
|
||||
input: readonly unknown[]
|
||||
): HistoricalBarV2[] {
|
||||
if (!input.length) {
|
||||
throw new Error('Dataset requires bars');
|
||||
}
|
||||
const index = indexMetadata(metadata);
|
||||
const intervals = new Set<string>(),
|
||||
sequences = new Set<string>(),
|
||||
seen = new Set<string>();
|
||||
const bars = input.map(value => {
|
||||
const bar = barSchema.parse(value);
|
||||
const series = index.series.get(bar.seriesId);
|
||||
const calendar = series && index.calendars.get(series.calendarId);
|
||||
const session =
|
||||
calendar && containingSession(calendar.sessions, bar.intervalStart, bar.intervalEnd);
|
||||
const duration = series?.interval === '1d' ? null : series ? durations[series.interval] : null;
|
||||
if (
|
||||
!series ||
|
||||
bar.instrumentId !== series.instrumentId ||
|
||||
!session ||
|
||||
bar.intervalStart >= bar.intervalEnd ||
|
||||
(duration === null
|
||||
? bar.intervalStart !== session.open || bar.intervalEnd !== session.close
|
||||
: bar.intervalEnd - bar.intervalStart !== duration) ||
|
||||
bar.eventTime !== bar.intervalEnd ||
|
||||
bar.availableAt < bar.eventTime ||
|
||||
(series.availability === 'interval-end-assumption' && bar.availableAt !== bar.intervalEnd) ||
|
||||
bar.intervalStart < metadata.bounds.warmupStart ||
|
||||
bar.intervalStart >= metadata.bounds.tradeEnd ||
|
||||
bar.intervalEnd > metadata.bounds.tradeEnd ||
|
||||
bar.high < Math.max(bar.open, bar.close) ||
|
||||
bar.low > Math.min(bar.open, bar.close)
|
||||
) {
|
||||
throw new Error('Invalid bar values, session interval or availability');
|
||||
}
|
||||
const intervalKey = JSON.stringify([bar.seriesId, bar.intervalStart, bar.intervalEnd]);
|
||||
const sequenceKey = JSON.stringify([bar.seriesId, bar.sourceSequence]);
|
||||
if (intervals.has(intervalKey) || sequences.has(sequenceKey)) {
|
||||
throw new Error('Duplicate or conflicting bar interval/source sequence');
|
||||
}
|
||||
intervals.add(intervalKey);
|
||||
sequences.add(sequenceKey);
|
||||
seen.add(bar.seriesId);
|
||||
return bar;
|
||||
});
|
||||
if (seen.size !== metadata.series.length) {
|
||||
throw new Error('Every declared series requires observations');
|
||||
}
|
||||
let previous: HistoricalBarV2 | undefined;
|
||||
for (const bar of [...bars].sort(
|
||||
(a, b) => compare(a.seriesId, b.seriesId) || a.intervalStart - b.intervalStart
|
||||
)) {
|
||||
if (previous?.seriesId === bar.seriesId && bar.intervalStart < previous.intervalEnd) {
|
||||
throw new Error('Overlapping intervals within one series');
|
||||
}
|
||||
previous = bar;
|
||||
}
|
||||
bars.sort(
|
||||
(a, b) =>
|
||||
a.availableAt - b.availableAt ||
|
||||
compare(a.instrumentId, b.instrumentId) ||
|
||||
compare(a.seriesId, b.seriesId) ||
|
||||
a.sourceSequence - b.sourceSequence
|
||||
);
|
||||
return bars;
|
||||
}
|
||||
|
||||
function freeze<T>(value: T): T {
|
||||
if (value && typeof value === 'object') {
|
||||
for (const child of Object.values(value)) {
|
||||
freeze(child);
|
||||
}
|
||||
Object.freeze(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function finish(
|
||||
metadata: ReturnType<typeof parseMetadata>,
|
||||
bars: HistoricalBarV2[],
|
||||
parentDatasetHash: string | null
|
||||
): HistoricalDatasetV2 {
|
||||
const manifest = {
|
||||
...metadata,
|
||||
version: 2 as const,
|
||||
normalizationRevision: 'historical-normalization-v2' as const,
|
||||
parentDatasetHash,
|
||||
volumePolicy: 'reported' as const,
|
||||
qualityPolicy: 'reject-invalid-no-interpolation' as const,
|
||||
intradayPolicy: 'full-duration-session-contained' as const,
|
||||
...assess(metadata, parentDatasetHash),
|
||||
barCount: bars.length,
|
||||
};
|
||||
const digest = createHash('sha256').update(`{"manifest":${JSON.stringify(manifest)},"bars":[`);
|
||||
bars.forEach((bar, index) => digest.update((index ? ',' : '') + JSON.stringify(bar)));
|
||||
const dataset = freeze({
|
||||
manifest: { ...manifest, hash: digest.update(']}').digest('hex') },
|
||||
bars,
|
||||
});
|
||||
prepared.add(dataset);
|
||||
return dataset;
|
||||
}
|
||||
|
||||
function create(input: unknown, parentDatasetHash: string | null): HistoricalDatasetV2 {
|
||||
const parsed = z
|
||||
.object({ metadata: metadataSchema, bars: z.array(sourceBarSchema).min(1) })
|
||||
.strict()
|
||||
.parse(input);
|
||||
const metadata = parseMetadata(parsed.metadata);
|
||||
const index = indexMetadata(metadata);
|
||||
const bars = parsed.bars.map(row => {
|
||||
const series = index.series.get(row.seriesId);
|
||||
const calendar = series && index.calendars.get(series.calendarId);
|
||||
if (!series || !calendar) {
|
||||
throw new Error('Unknown series/calendar mapping');
|
||||
}
|
||||
if (series.availability === 'explicit' && row.availableAt === undefined) {
|
||||
throw new Error('Explicit availability policy requires availableAt on every bar');
|
||||
}
|
||||
let intervalStart: number, intervalEnd: number;
|
||||
if (series.interval === '1d') {
|
||||
const session = typeof row.timestamp === 'string' && calendar.byDate.get(row.timestamp);
|
||||
if (!session) {
|
||||
throw new Error('Unknown daily session mapping');
|
||||
}
|
||||
intervalStart = session.open;
|
||||
intervalEnd = session.close;
|
||||
} else {
|
||||
if (typeof row.timestamp !== 'number') {
|
||||
throw new Error('Intraday timestamp requires an explicit instant');
|
||||
}
|
||||
const duration = durations[series.interval];
|
||||
intervalStart =
|
||||
series.timestamp === 'interval-start' ? row.timestamp : row.timestamp - duration;
|
||||
intervalEnd = intervalStart + duration;
|
||||
}
|
||||
return {
|
||||
seriesId: series.id,
|
||||
instrumentId: series.instrumentId,
|
||||
intervalStart,
|
||||
intervalEnd,
|
||||
eventTime: intervalEnd,
|
||||
availableAt: row.availableAt ?? intervalEnd,
|
||||
sourceSequence: row.sourceSequence,
|
||||
open: row.open,
|
||||
high: row.high,
|
||||
low: row.low,
|
||||
close: row.close,
|
||||
volume: row.volume,
|
||||
vwap: row.vwap ?? null,
|
||||
};
|
||||
});
|
||||
return finish(metadata, validateBars(metadata, bars), parentDatasetHash);
|
||||
}
|
||||
|
||||
/** No storage/provider access or implicit v1 cutover. Tables and timestamp semantics are mandatory. */
|
||||
export function createDatasetV2(input: HistoricalDatasetInputV2): HistoricalDatasetV2 {
|
||||
return create(input, null);
|
||||
}
|
||||
|
||||
/** Recompute constraints, eligibility and hash; untrusted values are detached before freezing. */
|
||||
export function validateDatasetV2(input: unknown): HistoricalDatasetV2 {
|
||||
if (input && typeof input === 'object' && prepared.has(input)) {
|
||||
return input as HistoricalDatasetV2;
|
||||
}
|
||||
const parsed = z
|
||||
.object({ manifest: manifestSchema, bars: z.array(barSchema).min(1) })
|
||||
.strict()
|
||||
.parse(input);
|
||||
const {
|
||||
version: _version,
|
||||
hash: expectedHash,
|
||||
normalizationRevision: _revision,
|
||||
parentDatasetHash,
|
||||
volumePolicy: _volume,
|
||||
qualityPolicy: _quality,
|
||||
intradayPolicy: _intraday,
|
||||
eligibility,
|
||||
limitations,
|
||||
barCount,
|
||||
...rawMetadata
|
||||
} = parsed.manifest;
|
||||
const metadata = parseMetadata(rawMetadata);
|
||||
const dataset = finish(metadata, validateBars(metadata, parsed.bars), parentDatasetHash);
|
||||
if (
|
||||
dataset.manifest.hash !== expectedHash ||
|
||||
barCount !== dataset.bars.length ||
|
||||
eligibility !== dataset.manifest.eligibility ||
|
||||
JSON.stringify(limitations) !== JSON.stringify(dataset.manifest.limitations) ||
|
||||
(parentDatasetHash !== null && dataset.bars.some(bar => bar.vwap !== null))
|
||||
) {
|
||||
throw new Error('Dataset v2 hash/content or derived policy mismatch');
|
||||
}
|
||||
return dataset;
|
||||
}
|
||||
|
||||
/** Exact retained v2 interval slice. V2 lineage belongs to the caller's manifest;
|
||||
* parentDatasetHash continues to describe only the original legacy-v1 conversion. */
|
||||
export function sliceDatasetV2(
|
||||
input: unknown,
|
||||
boundsInput: HistoricalDatasetMetadataV2['bounds']
|
||||
): HistoricalDatasetV2 {
|
||||
const source = validateDatasetV2(input);
|
||||
const bounds = metadataSchema.shape.bounds.parse(boundsInput);
|
||||
if (
|
||||
bounds.warmupStart < source.manifest.bounds.warmupStart ||
|
||||
bounds.tradeStart < source.manifest.bounds.tradeStart ||
|
||||
bounds.tradeEnd > source.manifest.bounds.tradeEnd
|
||||
) {
|
||||
throw new Error('Slice bounds must remain within the source warmup and evaluation bounds');
|
||||
}
|
||||
for (const boundary of [bounds.warmupStart, bounds.tradeStart, bounds.tradeEnd]) {
|
||||
if (source.bars.some(bar => bar.intervalStart < boundary && boundary < bar.intervalEnd)) {
|
||||
throw new Error('Slice boundaries cannot cut through a retained bar interval');
|
||||
}
|
||||
}
|
||||
const {
|
||||
version: _version,
|
||||
hash: _hash,
|
||||
normalizationRevision: _revision,
|
||||
parentDatasetHash,
|
||||
volumePolicy: _volume,
|
||||
qualityPolicy: _quality,
|
||||
intradayPolicy: _intraday,
|
||||
eligibility: _eligibility,
|
||||
limitations: _limitations,
|
||||
barCount: _count,
|
||||
...rawMetadata
|
||||
} = source.manifest;
|
||||
const metadata = parseMetadata({ ...rawMetadata, bounds });
|
||||
const bars = source.bars.filter(
|
||||
bar => bar.intervalStart >= bounds.warmupStart && bar.intervalEnd <= bounds.tradeEnd
|
||||
);
|
||||
return finish(metadata, validateBars(metadata, bars), parentDatasetHash);
|
||||
}
|
||||
|
||||
/** Unknown coverage remains exploratory; this assertion does not certify economic correctness. */
|
||||
export function assertDatasetV2Executable(input: unknown): HistoricalDatasetV2 {
|
||||
const dataset = validateDatasetV2(input);
|
||||
if (dataset.manifest.eligibility === 'ineligible') {
|
||||
throw new Error(`Dataset is not executable: ${dataset.manifest.limitations.join('; ')}`);
|
||||
}
|
||||
return dataset;
|
||||
}
|
||||
|
||||
/** Explicit legacy adapter only: retain the validated original-v1 hash. */
|
||||
export function createDatasetV2FromLegacy(
|
||||
input: HistoricalDatasetInputV2,
|
||||
parentHash: string
|
||||
): HistoricalDatasetV2 {
|
||||
const dataset = create(input, hash.parse(parentHash));
|
||||
// The old application adapter guaranteed this before calling private create().
|
||||
// Preserve that invariant at the new exported boundary, including prepared objects.
|
||||
if (dataset.bars.some(bar => bar.vwap !== null)) {
|
||||
throw new Error('Legacy v1 conversion requires unknown VWAP');
|
||||
}
|
||||
return dataset;
|
||||
}
|
||||
2
libs/research/src/index.ts
Normal file
2
libs/research/src/index.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
// The default entrypoint is browser safe; server validation is an explicit subpath.
|
||||
export * from './dataset-contracts';
|
||||
195
libs/research/src/results.ts
Normal file
195
libs/research/src/results.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 { ReplayReportResult } from '@stock-bot/stock-config/canonical-replay';
|
||||
import type {
|
||||
CanonicalBacktestAnalytics,
|
||||
CanonicalMetrics,
|
||||
CanonicalMetricsInput,
|
||||
CanonicalMetricUnavailableReason,
|
||||
CanonicalSessionReturn,
|
||||
} from '@stock-bot/types';
|
||||
|
||||
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,
|
||||
},
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue