T-121: M1.3f — @stock-bot/research: pure signal-panel builder (MarketDataStore daily bars + as-of signal rows → Vault-safe forward-return SignalCrossSection[]) with an end-to-end ceoShorts signal study test (store → analyzeSignal → trial_ledger → DSR) and local benchmark (no new dependencies)
This commit is contained in:
parent
bfcc1cf49f
commit
ee69c216af
7 changed files with 2347 additions and 0 deletions
|
|
@ -2,5 +2,6 @@
|
|||
export * from './dataset-contracts';
|
||||
export * from './market-data-store';
|
||||
export * from './market-data-store-duckdb';
|
||||
export * from './signal-panel';
|
||||
export * from './signal-study';
|
||||
export * from './trial-ledger';
|
||||
|
|
|
|||
971
libs/research/src/signal-panel.ts
Normal file
971
libs/research/src/signal-panel.ts
Normal file
|
|
@ -0,0 +1,971 @@
|
|||
/**
|
||||
* Pure, dependency-free signal-panel builder that transforms `MarketDataStore`
|
||||
* daily bars and point-in-time signal observations into Vault-safe
|
||||
* `SignalCrossSection[]` panels for `analyzeSignal` (`design/MILESTONES.md` M1).
|
||||
*
|
||||
* Browser-safe and dependency-free: zero `node:*` imports, zero bare `process`
|
||||
* access, and no database drivers.
|
||||
*
|
||||
* UTC session-calendar derivation:
|
||||
* - Curated daily bars (`bars_1d.ts`) are stamped at `16:00 ET` (`20:00` or
|
||||
* `21:00 UTC`), so the UTC calendar date `Math.floor(bar.ts / 86_400_000)`
|
||||
* matches the exchange session date without timezone drift.
|
||||
*
|
||||
* Point-in-time (PIT) & Vault rules:
|
||||
* - For each listing and session `d`, only signal rows with
|
||||
* `knownAt <= bar.ts` are eligible; a signal known after the close takes
|
||||
* effect on the next trading session.
|
||||
* - No cross-section is emitted when either `d` or its forward session
|
||||
* `d + horizonSessions` reaches or exceeds `vaultCutoffDate`, and `bar.close`
|
||||
* is never accessed for any bar on or after `vaultCutoffDate`.
|
||||
*/
|
||||
|
||||
import type { SignalCrossSection } from '@stock-bot/calculations';
|
||||
import {
|
||||
type BarBatch,
|
||||
type BarRecord,
|
||||
MarketDataStoreValidationError,
|
||||
type Table,
|
||||
applyVaultFence,
|
||||
} from './market-data-store';
|
||||
|
||||
const INT32_MIN = -2_147_483_648;
|
||||
const INT32_MAX = 2_147_483_647;
|
||||
const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000;
|
||||
const MS_PER_DAY = 86_400_000;
|
||||
const MAX_DIRECT_DAY_SPAN = 200_000;
|
||||
const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
export type SignalPanelErrorCode =
|
||||
| 'invalid_input'
|
||||
| 'invalid_horizon'
|
||||
| 'invalid_option'
|
||||
| 'invalid_date'
|
||||
| 'invalid_bar'
|
||||
| 'invalid_signal'
|
||||
| 'duplicate_bar';
|
||||
|
||||
export interface SignalPanelErrorOptions {
|
||||
readonly cause?: unknown;
|
||||
}
|
||||
|
||||
/** Typed validation and data-integrity error thrown by the signal-panel builder helpers. */
|
||||
export class SignalPanelError extends Error {
|
||||
override readonly name = 'SignalPanelError';
|
||||
readonly code: SignalPanelErrorCode;
|
||||
override readonly cause?: unknown;
|
||||
|
||||
constructor(code: SignalPanelErrorCode, message: string, options?: SignalPanelErrorOptions) {
|
||||
super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);
|
||||
this.code = code;
|
||||
if (options?.cause !== undefined) {
|
||||
this.cause = options.cause;
|
||||
}
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
export const SHORTS_SIGNAL_FIELDS = ['shares_short', 'net_change', 'pct_float'] as const;
|
||||
const SHORTS_SIGNAL_FIELD_SET: ReadonlySet<string> = new Set<string>(SHORTS_SIGNAL_FIELDS);
|
||||
|
||||
export type ShortsSignalField = (typeof SHORTS_SIGNAL_FIELDS)[number];
|
||||
|
||||
/** Point-in-time signal observation aligned to a listing ID and UTC epoch-ms `knownAt`. */
|
||||
export interface SignalObservation {
|
||||
readonly listingId: number;
|
||||
readonly knownAt: number;
|
||||
readonly value: number;
|
||||
}
|
||||
|
||||
/** Input contract for {@link buildForwardReturnPanel}. */
|
||||
export interface BuildForwardReturnPanelInput {
|
||||
readonly bars: readonly BarRecord[];
|
||||
readonly signals: readonly SignalObservation[];
|
||||
readonly horizonSessions: number;
|
||||
readonly vaultCutoffDate: string;
|
||||
readonly maxSignalAgeSessions?: number;
|
||||
}
|
||||
|
||||
/** Per-run diagnostic counters reported by {@link buildForwardReturnPanel}. */
|
||||
export interface SignalPanelDiagnostics {
|
||||
readonly vaultExcludedDates: number;
|
||||
readonly droppedNoSignal: number;
|
||||
readonly droppedStaleSignal: number;
|
||||
readonly droppedMissingForwardBar: number;
|
||||
readonly droppedNonPositiveClose: number;
|
||||
readonly duplicateBars: number;
|
||||
}
|
||||
|
||||
/** Output contract returned by {@link buildForwardReturnPanel}. */
|
||||
export interface BuildForwardReturnPanelResult {
|
||||
readonly panel: SignalCrossSection[];
|
||||
readonly sessionDates: string[];
|
||||
readonly diagnostics: SignalPanelDiagnostics;
|
||||
}
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function normalizeZero(value: number): number {
|
||||
return value === 0 ? 0 : value;
|
||||
}
|
||||
|
||||
function isValidInt32(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === 'number' &&
|
||||
Number.isSafeInteger(value) &&
|
||||
value >= INT32_MIN &&
|
||||
value <= INT32_MAX
|
||||
);
|
||||
}
|
||||
|
||||
function isValidEpochMs(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === 'number' &&
|
||||
Number.isSafeInteger(value) &&
|
||||
Math.abs(value) <= MAX_ECMASCRIPT_EPOCH_MS
|
||||
);
|
||||
}
|
||||
|
||||
function parseStrictCalendarDayKey(value: unknown, field: string): number {
|
||||
if (typeof value !== 'string' || !DATE_ONLY_PATTERN.test(value)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_date',
|
||||
`Invalid "${field}": expected strict YYYY-MM-DD date string, got "${String(value)}".`
|
||||
);
|
||||
}
|
||||
try {
|
||||
const fenced = applyVaultFence(
|
||||
{ from: value, to: value, scope: 'vault_evaluation_only' },
|
||||
{ vaultCutoffTs: 0, vaultOperatorAuthorized: true }
|
||||
);
|
||||
return fenced.fromMs / MS_PER_DAY;
|
||||
} catch (error) {
|
||||
if (error instanceof MarketDataStoreValidationError) {
|
||||
throw new SignalPanelError('invalid_date', `Invalid "${field}": ${error.message}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function formatDayKeyUtc(dayKey: number): string {
|
||||
const date = new Date(dayKey * MS_PER_DAY);
|
||||
const year = String(date.getUTCFullYear()).padStart(4, '0');
|
||||
const month = String(date.getUTCMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getUTCDate()).padStart(2, '0');
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drains an `AsyncIterable<BarBatch>` (such as `MarketDataStore.bars`) into a
|
||||
* flat `BarRecord[]` without mutating any yielded batch or overflowing the call
|
||||
* stack on large batches.
|
||||
*/
|
||||
export async function collectBars(iterable: AsyncIterable<BarBatch>): Promise<BarRecord[]> {
|
||||
if (
|
||||
iterable === null ||
|
||||
(typeof iterable !== 'object' && typeof iterable !== 'function') ||
|
||||
typeof (iterable as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] !== 'function'
|
||||
) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_input',
|
||||
'Expected an AsyncIterable<BarBatch> with a [Symbol.asyncIterator] method.'
|
||||
);
|
||||
}
|
||||
|
||||
const out: BarRecord[] = [];
|
||||
let batchIndex = 0;
|
||||
for await (const batch of iterable) {
|
||||
if (!isPlainRecord(batch) || !Array.isArray(batch.rows)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_bar',
|
||||
`Expected batch[${batchIndex}] to be an object with a rows array.`
|
||||
);
|
||||
}
|
||||
const rows = batch.rows;
|
||||
for (let i = 0; i < rows.length; i += 1) {
|
||||
out.push(rows[i] as BarRecord);
|
||||
}
|
||||
batchIndex += 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a `MarketDataStore.shortsAsOf` `Table` into point-in-time
|
||||
* {@link SignalObservation} rows for the chosen field, skipping `null` cells
|
||||
* and rejecting malformed rows with {@link SignalPanelError}.
|
||||
*/
|
||||
export function shortsTableToSignalRows(
|
||||
table: Table,
|
||||
field: ShortsSignalField
|
||||
): SignalObservation[] {
|
||||
if (typeof field !== 'string' || !SHORTS_SIGNAL_FIELD_SET.has(field)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_input',
|
||||
`Invalid shorts signal field "${String(field)}": expected one of ${SHORTS_SIGNAL_FIELDS.join(', ')}.`
|
||||
);
|
||||
}
|
||||
if (!isPlainRecord(table) || !Array.isArray(table.columns) || !Array.isArray(table.rows)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_input',
|
||||
'Expected a Table object with array columns and rows.'
|
||||
);
|
||||
}
|
||||
|
||||
let hasListingIdCol = false;
|
||||
let hasKnownAtCol = false;
|
||||
let hasFieldCol = false;
|
||||
for (let i = 0; i < table.columns.length; i += 1) {
|
||||
const col: unknown = table.columns[i];
|
||||
if (col === 'listing_id') {
|
||||
hasListingIdCol = true;
|
||||
} else if (col === 'known_at') {
|
||||
hasKnownAtCol = true;
|
||||
} else if (col === field) {
|
||||
hasFieldCol = true;
|
||||
}
|
||||
}
|
||||
if (!hasListingIdCol || !hasKnownAtCol || !hasFieldCol) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_input',
|
||||
`Shorts table is missing required column(s): expected "listing_id", "known_at", and "${field}".`
|
||||
);
|
||||
}
|
||||
|
||||
const out: SignalObservation[] = [];
|
||||
const rows = table.rows;
|
||||
for (let i = 0; i < rows.length; i += 1) {
|
||||
const row: unknown = rows[i];
|
||||
if (!isPlainRecord(row)) {
|
||||
throw new SignalPanelError('invalid_signal', `Shorts table row[${i}] must be a plain object.`);
|
||||
}
|
||||
if (
|
||||
!Object.prototype.hasOwnProperty.call(row, 'listing_id') ||
|
||||
!Object.prototype.hasOwnProperty.call(row, 'known_at') ||
|
||||
!Object.prototype.hasOwnProperty.call(row, field)
|
||||
) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_signal',
|
||||
`Shorts table row[${i}] is missing required key "listing_id", "known_at", or "${field}".`
|
||||
);
|
||||
}
|
||||
|
||||
const listingId = row.listing_id;
|
||||
if (!isValidInt32(listingId)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_signal',
|
||||
`Invalid listing_id in shorts table row[${i}]: ${String(listingId)}.`
|
||||
);
|
||||
}
|
||||
|
||||
const knownAt = row.known_at;
|
||||
if (!isValidEpochMs(knownAt)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_signal',
|
||||
`Invalid known_at in shorts table row[${i}]: ${String(knownAt)}.`
|
||||
);
|
||||
}
|
||||
|
||||
const rawValue = row[field];
|
||||
if (rawValue === null) {
|
||||
continue;
|
||||
}
|
||||
if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_signal',
|
||||
`Invalid "${field}" value in shorts table row[${i}]: ${String(rawValue)}.`
|
||||
);
|
||||
}
|
||||
|
||||
out.push({
|
||||
listingId: normalizeZero(listingId),
|
||||
knownAt: normalizeZero(knownAt),
|
||||
value: normalizeZero(rawValue),
|
||||
});
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
interface BarSortScratch {
|
||||
sessionIdx: Int32Array;
|
||||
ts: Float64Array;
|
||||
close: Float64Array;
|
||||
}
|
||||
|
||||
interface SignalSortScratch {
|
||||
knownAt: Float64Array;
|
||||
value: Float64Array;
|
||||
}
|
||||
|
||||
function ensureBarScratch(scratch: BarSortScratch, len: number): void {
|
||||
if (scratch.sessionIdx.length < len) {
|
||||
scratch.sessionIdx = new Int32Array(len);
|
||||
scratch.ts = new Float64Array(len);
|
||||
scratch.close = new Float64Array(len);
|
||||
}
|
||||
}
|
||||
|
||||
function ensureSignalScratch(scratch: SignalSortScratch, len: number): void {
|
||||
if (scratch.knownAt.length < len) {
|
||||
scratch.knownAt = new Float64Array(len);
|
||||
scratch.value = new Float64Array(len);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterative bottom-up mergesort for a listing's bar slice `[start, end)` ordered
|
||||
* by `sessionIdx ASC`. Skips sorting when already non-decreasing.
|
||||
*/
|
||||
function sortBarSliceBySession(
|
||||
sessionIdx: Int32Array,
|
||||
ts: Float64Array,
|
||||
close: Float64Array,
|
||||
start: number,
|
||||
end: number,
|
||||
scratch: BarSortScratch
|
||||
): void {
|
||||
const len = end - start;
|
||||
if (len <= 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
let sorted = true;
|
||||
for (let i = start + 1; i < end; i += 1) {
|
||||
if ((sessionIdx[i] as number) < (sessionIdx[i - 1] as number)) {
|
||||
sorted = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (sorted) {
|
||||
return;
|
||||
}
|
||||
|
||||
ensureBarScratch(scratch, len);
|
||||
const tmpSession = scratch.sessionIdx;
|
||||
const tmpTs = scratch.ts;
|
||||
const tmpClose = scratch.close;
|
||||
|
||||
for (let width = 1; width < len; width *= 2) {
|
||||
for (let left = 0; left < len; left += 2 * width) {
|
||||
const mid = Math.min(left + width, len);
|
||||
const right = Math.min(left + 2 * width, len);
|
||||
let i = left;
|
||||
let j = mid;
|
||||
let k = left;
|
||||
|
||||
while (i < mid && j < right) {
|
||||
const si = sessionIdx[start + i] as number;
|
||||
const sj = sessionIdx[start + j] as number;
|
||||
if (si <= sj) {
|
||||
tmpSession[k] = si;
|
||||
tmpTs[k] = ts[start + i] as number;
|
||||
tmpClose[k] = close[start + i] as number;
|
||||
i += 1;
|
||||
} else {
|
||||
tmpSession[k] = sj;
|
||||
tmpTs[k] = ts[start + j] as number;
|
||||
tmpClose[k] = close[start + j] as number;
|
||||
j += 1;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
while (i < mid) {
|
||||
tmpSession[k] = sessionIdx[start + i] as number;
|
||||
tmpTs[k] = ts[start + i] as number;
|
||||
tmpClose[k] = close[start + i] as number;
|
||||
i += 1;
|
||||
k += 1;
|
||||
}
|
||||
while (j < right) {
|
||||
tmpSession[k] = sessionIdx[start + j] as number;
|
||||
tmpTs[k] = ts[start + j] as number;
|
||||
tmpClose[k] = close[start + j] as number;
|
||||
j += 1;
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
|
||||
for (let k = 0; k < len; k += 1) {
|
||||
sessionIdx[start + k] = tmpSession[k] as number;
|
||||
ts[start + k] = tmpTs[k] as number;
|
||||
close[start + k] = tmpClose[k] as number;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterative bottom-up mergesort for a listing's signal slice `[start, end)`
|
||||
* ordered by `(knownAt ASC, value ASC)` for deterministic tie-breaking.
|
||||
* Skips sorting when already sorted.
|
||||
*/
|
||||
function sortSignalSlice(
|
||||
knownAt: Float64Array,
|
||||
value: Float64Array,
|
||||
start: number,
|
||||
end: number,
|
||||
scratch: SignalSortScratch
|
||||
): void {
|
||||
const len = end - start;
|
||||
if (len <= 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
let sorted = true;
|
||||
for (let i = start + 1; i < end; i += 1) {
|
||||
const ka = knownAt[i] as number;
|
||||
const prevKa = knownAt[i - 1] as number;
|
||||
if (ka < prevKa || (ka === prevKa && (value[i] as number) < (value[i - 1] as number))) {
|
||||
sorted = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (sorted) {
|
||||
return;
|
||||
}
|
||||
|
||||
ensureSignalScratch(scratch, len);
|
||||
const tmpKnownAt = scratch.knownAt;
|
||||
const tmpValue = scratch.value;
|
||||
|
||||
for (let width = 1; width < len; width *= 2) {
|
||||
for (let left = 0; left < len; left += 2 * width) {
|
||||
const mid = Math.min(left + width, len);
|
||||
const right = Math.min(left + 2 * width, len);
|
||||
let i = left;
|
||||
let j = mid;
|
||||
let k = left;
|
||||
|
||||
while (i < mid && j < right) {
|
||||
const ki = knownAt[start + i] as number;
|
||||
const kj = knownAt[start + j] as number;
|
||||
const vi = value[start + i] as number;
|
||||
const vj = value[start + j] as number;
|
||||
if (ki < kj || (ki === kj && vi <= vj)) {
|
||||
tmpKnownAt[k] = ki;
|
||||
tmpValue[k] = vi;
|
||||
i += 1;
|
||||
} else {
|
||||
tmpKnownAt[k] = kj;
|
||||
tmpValue[k] = vj;
|
||||
j += 1;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
while (i < mid) {
|
||||
tmpKnownAt[k] = knownAt[start + i] as number;
|
||||
tmpValue[k] = value[start + i] as number;
|
||||
i += 1;
|
||||
k += 1;
|
||||
}
|
||||
while (j < right) {
|
||||
tmpKnownAt[k] = knownAt[start + j] as number;
|
||||
tmpValue[k] = value[start + j] as number;
|
||||
j += 1;
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
|
||||
for (let k = 0; k < len; k += 1) {
|
||||
knownAt[start + k] = tmpKnownAt[k] as number;
|
||||
value[start + k] = tmpValue[k] as number;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure, synchronous forward-return signal-panel builder.
|
||||
*
|
||||
* Joins daily bars (caller-supplied `'total'`-adjusted closes in any order)
|
||||
* with point-in-time signal observations (`knownAt <= bar.ts`), enforces the
|
||||
* exclusive `vaultCutoffDate` fence across both the signal date `d` and the
|
||||
* forward session `d + horizonSessions` without ever reading post-cutoff
|
||||
* closes, and emits deterministic `SignalCrossSection[]` slices ready for
|
||||
* `analyzeSignal`.
|
||||
*/
|
||||
export function buildForwardReturnPanel(
|
||||
input: BuildForwardReturnPanelInput
|
||||
): BuildForwardReturnPanelResult {
|
||||
if (!isPlainRecord(input)) {
|
||||
throw new SignalPanelError('invalid_input', 'Input must be a non-null plain object.');
|
||||
}
|
||||
|
||||
const horizonSessions = input.horizonSessions;
|
||||
if (
|
||||
typeof horizonSessions !== 'number' ||
|
||||
!Number.isSafeInteger(horizonSessions) ||
|
||||
horizonSessions < 1
|
||||
) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_horizon',
|
||||
`Invalid horizonSessions "${String(horizonSessions)}": expected a safe integer >= 1.`
|
||||
);
|
||||
}
|
||||
|
||||
const vaultCutoffDayKey = parseStrictCalendarDayKey(input.vaultCutoffDate, 'vaultCutoffDate');
|
||||
|
||||
const maxSignalAgeSessions = input.maxSignalAgeSessions;
|
||||
if (
|
||||
maxSignalAgeSessions !== undefined &&
|
||||
(typeof maxSignalAgeSessions !== 'number' ||
|
||||
!Number.isSafeInteger(maxSignalAgeSessions) ||
|
||||
maxSignalAgeSessions < 0)
|
||||
) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_option',
|
||||
`Invalid maxSignalAgeSessions "${String(maxSignalAgeSessions)}": expected a safe integer >= 0.`
|
||||
);
|
||||
}
|
||||
|
||||
if (!Array.isArray(input.bars)) {
|
||||
throw new SignalPanelError('invalid_input', 'input.bars must be an array of BarRecord.');
|
||||
}
|
||||
if (!Array.isArray(input.signals)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_input',
|
||||
'input.signals must be an array of SignalObservation.'
|
||||
);
|
||||
}
|
||||
|
||||
const bars = input.bars;
|
||||
const signals = input.signals;
|
||||
|
||||
// Pass 1 over bars: validate structure, build pre-cutoff calendar, count bars per listing.
|
||||
// Never access `bar.close` when the bar's UTC dayKey reaches or exceeds `vaultCutoffDayKey`.
|
||||
const postCutoffDays = new Set<number>();
|
||||
const preCutoffDayMaxTs = new Map<number, number>();
|
||||
const listingBarCounts = new Map<number, number>();
|
||||
let preCutoffBarTotal = 0;
|
||||
|
||||
for (let i = 0; i < bars.length; i += 1) {
|
||||
const rawBar: unknown = bars[i];
|
||||
if (!isPlainRecord(rawBar)) {
|
||||
throw new SignalPanelError('invalid_bar', `bars[${i}] must be a non-null plain object.`);
|
||||
}
|
||||
|
||||
const listingId = rawBar.listingId;
|
||||
if (!isValidInt32(listingId)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_bar',
|
||||
`Invalid listingId at bars[${i}]: ${String(listingId)}.`
|
||||
);
|
||||
}
|
||||
|
||||
const ts = rawBar.ts;
|
||||
if (!isValidEpochMs(ts)) {
|
||||
throw new SignalPanelError('invalid_bar', `Invalid ts at bars[${i}]: ${String(ts)}.`);
|
||||
}
|
||||
|
||||
const knownAt = rawBar.knownAt;
|
||||
if (!isValidEpochMs(knownAt)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_bar',
|
||||
`Invalid knownAt at bars[${i}]: ${String(knownAt)}.`
|
||||
);
|
||||
}
|
||||
|
||||
const dayKey = Math.floor(ts / MS_PER_DAY);
|
||||
if (dayKey >= vaultCutoffDayKey) {
|
||||
postCutoffDays.add(dayKey);
|
||||
continue;
|
||||
}
|
||||
|
||||
const close = rawBar.close;
|
||||
if (typeof close !== 'number') {
|
||||
throw new SignalPanelError('invalid_bar', `Invalid close at bars[${i}]: expected a number.`);
|
||||
}
|
||||
|
||||
const prevMaxTs = preCutoffDayMaxTs.get(dayKey);
|
||||
if (prevMaxTs === undefined || ts > prevMaxTs) {
|
||||
preCutoffDayMaxTs.set(dayKey, ts);
|
||||
}
|
||||
|
||||
const normListingId = normalizeZero(listingId);
|
||||
listingBarCounts.set(normListingId, (listingBarCounts.get(normListingId) ?? 0) + 1);
|
||||
preCutoffBarTotal += 1;
|
||||
}
|
||||
|
||||
// Build strictly ascending pre-cutoff session calendar.
|
||||
const preCount = preCutoffDayMaxTs.size;
|
||||
const preDayKeys = new Int32Array(preCount);
|
||||
{
|
||||
let idx = 0;
|
||||
for (const dayKey of preCutoffDayMaxTs.keys()) {
|
||||
preDayKeys[idx] = dayKey;
|
||||
idx += 1;
|
||||
}
|
||||
preDayKeys.sort();
|
||||
}
|
||||
|
||||
const sessionMaxTs = new Float64Array(preCount);
|
||||
const sessionDates: string[] = new Array<string>(preCount);
|
||||
for (let i = 0; i < preCount; i += 1) {
|
||||
const dk = preDayKeys[i] as number;
|
||||
sessionMaxTs[i] = preCutoffDayMaxTs.get(dk) as number;
|
||||
sessionDates[i] = formatDayKeyUtc(dk);
|
||||
}
|
||||
|
||||
const emittableDateLimit = Math.max(0, preCount - horizonSessions);
|
||||
const hasPostCutoff = postCutoffDays.size > 0;
|
||||
const vaultExcludedDates = hasPostCutoff
|
||||
? preCount - emittableDateLimit + postCutoffDays.size
|
||||
: 0;
|
||||
|
||||
// Sort unique listingIds ascending so output cross-section `ids` are strictly ascending
|
||||
// with zero per-date sorting.
|
||||
const listingCount = listingBarCounts.size;
|
||||
const sortedListingIds = new Int32Array(listingCount);
|
||||
{
|
||||
let idx = 0;
|
||||
for (const lid of listingBarCounts.keys()) {
|
||||
sortedListingIds[idx] = lid;
|
||||
idx += 1;
|
||||
}
|
||||
sortedListingIds.sort();
|
||||
}
|
||||
|
||||
const listingIdToIdx = new Map<number, number>();
|
||||
const barOffsets = new Int32Array(listingCount + 1);
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
const lid = sortedListingIds[l] as number;
|
||||
listingIdToIdx.set(lid, l);
|
||||
barOffsets[l + 1] = (barOffsets[l] as number) + (listingBarCounts.get(lid) as number);
|
||||
}
|
||||
|
||||
// Validate all signals upfront (even if bars is empty) and count signals per known listing.
|
||||
const sigCounts = new Int32Array(listingCount);
|
||||
let matchedSignalTotal = 0;
|
||||
for (let i = 0; i < signals.length; i += 1) {
|
||||
const rawSig: unknown = signals[i];
|
||||
if (!isPlainRecord(rawSig)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_signal',
|
||||
`signals[${i}] must be a non-null plain object.`
|
||||
);
|
||||
}
|
||||
|
||||
const listingId = rawSig.listingId;
|
||||
if (!isValidInt32(listingId)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_signal',
|
||||
`Invalid listingId at signals[${i}]: ${String(listingId)}.`
|
||||
);
|
||||
}
|
||||
|
||||
const knownAt = rawSig.knownAt;
|
||||
if (!isValidEpochMs(knownAt)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_signal',
|
||||
`Invalid knownAt at signals[${i}]: ${String(knownAt)}.`
|
||||
);
|
||||
}
|
||||
|
||||
const value = rawSig.value;
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_signal',
|
||||
`Invalid signal value at signals[${i}]: ${String(value)}.`
|
||||
);
|
||||
}
|
||||
|
||||
const l = listingIdToIdx.get(normalizeZero(listingId));
|
||||
if (l !== undefined) {
|
||||
sigCounts[l] = (sigCounts[l] as number) + 1;
|
||||
matchedSignalTotal += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (preCutoffBarTotal === 0) {
|
||||
return {
|
||||
panel: [],
|
||||
sessionDates,
|
||||
diagnostics: {
|
||||
vaultExcludedDates,
|
||||
droppedNoSignal: 0,
|
||||
droppedStaleSignal: 0,
|
||||
droppedMissingForwardBar: 0,
|
||||
droppedNonPositiveClose: 0,
|
||||
duplicateBars: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Build O(1) dayKey -> sessionIdx lookup (direct Int32Array when span <= 200_000, else Map).
|
||||
const minDayKey = preDayKeys[0] as number;
|
||||
const maxDayKey = preDayKeys[preCount - 1] as number;
|
||||
const daySpan = maxDayKey - minDayKey + 1;
|
||||
let dayKeyToIdxArr: Int32Array | null = null;
|
||||
let dayKeyToIdxMap: Map<number, number> | null = null;
|
||||
if (daySpan <= MAX_DIRECT_DAY_SPAN) {
|
||||
dayKeyToIdxArr = new Int32Array(daySpan);
|
||||
dayKeyToIdxArr.fill(-1);
|
||||
for (let i = 0; i < preCount; i += 1) {
|
||||
dayKeyToIdxArr[(preDayKeys[i] as number) - minDayKey] = i;
|
||||
}
|
||||
} else {
|
||||
dayKeyToIdxMap = new Map<number, number>();
|
||||
for (let i = 0; i < preCount; i += 1) {
|
||||
dayKeyToIdxMap.set(preDayKeys[i] as number, i);
|
||||
}
|
||||
}
|
||||
|
||||
// Scatter pre-cutoff bars into CSR typed arrays grouped by listing index.
|
||||
const barSessionIdx = new Int32Array(preCutoffBarTotal);
|
||||
const barTs = new Float64Array(preCutoffBarTotal);
|
||||
const barClose = new Float64Array(preCutoffBarTotal);
|
||||
const barCursor = new Int32Array(listingCount);
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
barCursor[l] = barOffsets[l] as number;
|
||||
}
|
||||
|
||||
for (let i = 0; i < bars.length; i += 1) {
|
||||
const bar = bars[i] as BarRecord;
|
||||
const dayKey = Math.floor(bar.ts / MS_PER_DAY);
|
||||
if (dayKey >= vaultCutoffDayKey) {
|
||||
continue;
|
||||
}
|
||||
const l = listingIdToIdx.get(normalizeZero(bar.listingId)) as number;
|
||||
const pos = barCursor[l] as number;
|
||||
barCursor[l] = pos + 1;
|
||||
|
||||
const sIdx =
|
||||
dayKeyToIdxArr !== null
|
||||
? (dayKeyToIdxArr[dayKey - minDayKey] as number)
|
||||
: ((dayKeyToIdxMap as Map<number, number>).get(dayKey) as number);
|
||||
barSessionIdx[pos] = sIdx;
|
||||
barTs[pos] = normalizeZero(bar.ts);
|
||||
barClose[pos] = bar.close;
|
||||
}
|
||||
|
||||
// Scatter matched signals into CSR typed arrays grouped by listing index.
|
||||
const sigOffsets = new Int32Array(listingCount + 1);
|
||||
const sigCursor = new Int32Array(listingCount);
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
sigOffsets[l + 1] = (sigOffsets[l] as number) + (sigCounts[l] as number);
|
||||
sigCursor[l] = sigOffsets[l] as number;
|
||||
}
|
||||
|
||||
const sigKnownAt = new Float64Array(matchedSignalTotal);
|
||||
const sigValue = new Float64Array(matchedSignalTotal);
|
||||
if (matchedSignalTotal > 0) {
|
||||
for (let i = 0; i < signals.length; i += 1) {
|
||||
const sig = signals[i] as SignalObservation;
|
||||
const l = listingIdToIdx.get(normalizeZero(sig.listingId));
|
||||
if (l === undefined) {
|
||||
continue;
|
||||
}
|
||||
const pos = sigCursor[l] as number;
|
||||
sigCursor[l] = pos + 1;
|
||||
sigKnownAt[pos] = normalizeZero(sig.knownAt);
|
||||
sigValue[pos] = normalizeZero(sig.value);
|
||||
}
|
||||
}
|
||||
|
||||
// Per-date growable typed-array buckets for emitted observations.
|
||||
const initialBucketCap = Math.max(
|
||||
8,
|
||||
Math.min(listingCount, Math.ceil(preCutoffBarTotal / Math.max(1, preCount)))
|
||||
);
|
||||
const bucketLengths = new Int32Array(emittableDateLimit);
|
||||
const bucketIds: (Int32Array | null)[] = new Array<Int32Array | null>(emittableDateLimit).fill(
|
||||
null
|
||||
);
|
||||
const bucketSignals: (Float64Array | null)[] = new Array<Float64Array | null>(
|
||||
emittableDateLimit
|
||||
).fill(null);
|
||||
const bucketReturns: (Float64Array | null)[] = new Array<Float64Array | null>(
|
||||
emittableDateLimit
|
||||
).fill(null);
|
||||
|
||||
const barScratch: BarSortScratch = {
|
||||
sessionIdx: new Int32Array(0),
|
||||
ts: new Float64Array(0),
|
||||
close: new Float64Array(0),
|
||||
};
|
||||
const sigScratch: SignalSortScratch = {
|
||||
knownAt: new Float64Array(0),
|
||||
value: new Float64Array(0),
|
||||
};
|
||||
|
||||
let droppedNoSignal = 0;
|
||||
let droppedStaleSignal = 0;
|
||||
let droppedMissingForwardBar = 0;
|
||||
let droppedNonPositiveClose = 0;
|
||||
let duplicateBars = 0;
|
||||
|
||||
// One linear merge pass per listing in ascending listingId order.
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
const listingId = sortedListingIds[l] as number;
|
||||
const bStart = barOffsets[l] as number;
|
||||
const bEnd = barOffsets[l + 1] as number;
|
||||
if (bStart >= bEnd) {
|
||||
continue;
|
||||
}
|
||||
|
||||
sortBarSliceBySession(barSessionIdx, barTs, barClose, bStart, bEnd, barScratch);
|
||||
|
||||
// Compact exact duplicates in place; reject conflicting duplicates on the same (listingId, date).
|
||||
let write = bStart;
|
||||
for (let i = bStart + 1; i < bEnd; i += 1) {
|
||||
if (barSessionIdx[i] === barSessionIdx[write]) {
|
||||
const prevTs = barTs[write] as number;
|
||||
const currTs = barTs[i] as number;
|
||||
const prevClose = barClose[write] as number;
|
||||
const currClose = barClose[i] as number;
|
||||
const sameClose =
|
||||
prevClose === currClose || (Number.isNaN(prevClose) && Number.isNaN(currClose));
|
||||
if (currTs === prevTs && sameClose) {
|
||||
duplicateBars += 1;
|
||||
continue;
|
||||
}
|
||||
const conflictDate = sessionDates[barSessionIdx[i] as number] as string;
|
||||
throw new SignalPanelError(
|
||||
'duplicate_bar',
|
||||
`Conflicting duplicate bars for listingId ${listingId} on session ${conflictDate}.`
|
||||
);
|
||||
}
|
||||
write += 1;
|
||||
if (write !== i) {
|
||||
barSessionIdx[write] = barSessionIdx[i] as number;
|
||||
barTs[write] = barTs[i] as number;
|
||||
barClose[write] = barClose[i] as number;
|
||||
}
|
||||
}
|
||||
const uniqueEnd = write + 1;
|
||||
|
||||
const sStart = sigOffsets[l] as number;
|
||||
const sEnd = sigOffsets[l + 1] as number;
|
||||
sortSignalSlice(sigKnownAt, sigValue, sStart, sEnd, sigScratch);
|
||||
|
||||
let sigPtr = sStart - 1;
|
||||
let fwdPtr = bStart;
|
||||
let ageCalPtr = 0;
|
||||
let firstActionableSessionIdx = -1;
|
||||
|
||||
for (let i = bStart; i < uniqueEnd; i += 1) {
|
||||
const t = barSessionIdx[i] as number;
|
||||
if (hasPostCutoff && t >= emittableDateLimit) {
|
||||
break;
|
||||
}
|
||||
|
||||
const ts = barTs[i] as number;
|
||||
const prevSigPtr = sigPtr;
|
||||
while (sigPtr + 1 < sEnd && (sigKnownAt[sigPtr + 1] as number) <= ts) {
|
||||
sigPtr += 1;
|
||||
}
|
||||
|
||||
if (sigPtr < sStart) {
|
||||
droppedNoSignal += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (maxSignalAgeSessions !== undefined) {
|
||||
if (sigPtr !== prevSigPtr) {
|
||||
const activeKnownAt = sigKnownAt[sigPtr] as number;
|
||||
while (ageCalPtr < preCount && (sessionMaxTs[ageCalPtr] as number) < activeKnownAt) {
|
||||
ageCalPtr += 1;
|
||||
}
|
||||
firstActionableSessionIdx = ageCalPtr;
|
||||
}
|
||||
if (t - firstActionableSessionIdx > maxSignalAgeSessions) {
|
||||
droppedStaleSignal += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
const targetSession = t + horizonSessions;
|
||||
if (targetSession >= preCount) {
|
||||
droppedMissingForwardBar += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
while (fwdPtr < uniqueEnd && (barSessionIdx[fwdPtr] as number) < targetSession) {
|
||||
fwdPtr += 1;
|
||||
}
|
||||
if (fwdPtr >= uniqueEnd || (barSessionIdx[fwdPtr] as number) !== targetSession) {
|
||||
droppedMissingForwardBar += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const close0 = barClose[i] as number;
|
||||
const close1 = barClose[fwdPtr] as number;
|
||||
if (!Number.isFinite(close0) || close0 <= 0 || !Number.isFinite(close1) || close1 <= 0) {
|
||||
droppedNonPositiveClose += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const fwdRet = close1 / close0 - 1;
|
||||
if (!Number.isFinite(fwdRet)) {
|
||||
droppedNonPositiveClose += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Append to bucket `t`.
|
||||
const len = bucketLengths[t] as number;
|
||||
let ids = bucketIds[t] ?? null;
|
||||
let sigs = bucketSignals[t] ?? null;
|
||||
let rets = bucketReturns[t] ?? null;
|
||||
if (ids === null || sigs === null || rets === null) {
|
||||
ids = new Int32Array(initialBucketCap);
|
||||
sigs = new Float64Array(initialBucketCap);
|
||||
rets = new Float64Array(initialBucketCap);
|
||||
bucketIds[t] = ids;
|
||||
bucketSignals[t] = sigs;
|
||||
bucketReturns[t] = rets;
|
||||
} else if (len === ids.length) {
|
||||
const nextCap = Math.min(listingCount, ids.length * 2);
|
||||
const nextIds = new Int32Array(nextCap);
|
||||
const nextSigs = new Float64Array(nextCap);
|
||||
const nextRets = new Float64Array(nextCap);
|
||||
nextIds.set(ids);
|
||||
nextSigs.set(sigs);
|
||||
nextRets.set(rets);
|
||||
ids = nextIds;
|
||||
sigs = nextSigs;
|
||||
rets = nextRets;
|
||||
bucketIds[t] = ids;
|
||||
bucketSignals[t] = sigs;
|
||||
bucketReturns[t] = rets;
|
||||
}
|
||||
|
||||
ids[len] = listingId;
|
||||
sigs[len] = normalizeZero(sigValue[sigPtr] as number);
|
||||
rets[len] = normalizeZero(fwdRet);
|
||||
bucketLengths[t] = len + 1;
|
||||
}
|
||||
}
|
||||
|
||||
const panel: SignalCrossSection[] = [];
|
||||
for (let t = 0; t < emittableDateLimit; t += 1) {
|
||||
const len = bucketLengths[t] as number;
|
||||
if (len === 0) {
|
||||
continue;
|
||||
}
|
||||
const ids = bucketIds[t] as Int32Array;
|
||||
const sigs = bucketSignals[t] as Float64Array;
|
||||
const rets = bucketReturns[t] as Float64Array;
|
||||
panel.push({
|
||||
date: sessionDates[t] as string,
|
||||
ids: len === ids.length ? ids : ids.slice(0, len),
|
||||
signal: len === sigs.length ? sigs : sigs.slice(0, len),
|
||||
forwardReturn: len === rets.length ? rets : rets.slice(0, len),
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
panel,
|
||||
sessionDates,
|
||||
diagnostics: {
|
||||
vaultExcludedDates,
|
||||
droppedNoSignal,
|
||||
droppedStaleSignal,
|
||||
droppedMissingForwardBar,
|
||||
droppedNonPositiveClose,
|
||||
duplicateBars,
|
||||
},
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue