diff --git a/libs/research/README.md b/libs/research/README.md index 4fd83b00..5f1a716a 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -111,3 +111,40 @@ Fixed-seed (`20261129`) local benchmark planning `120,000` mixed queries across - **Command:** `bun run libs/research/scripts/benchmark-market-data-store-duckdb.ts` - **Observed (Bun 1.2.16):** `elapsedMs = 218.55 ms`, `queriesPerSec = 549,073 queries/s` (`120,000` queries, `758,061` bound params, pinned checksum `8606c98c`) + +## Signal Panel Builder + +Exported from both `@stock-bot/research` and `@stock-bot/research/signal-panel` (`libs/research/src/signal-panel.ts`). The module is pure, synchronous (except `collectBars`), dependency-free, and browser-safe (zero `node:*` imports, zero bare `process` access, no database drivers). + +### API + +- **`buildForwardReturnPanel({ bars, signals, horizonSessions, vaultCutoffDate, maxSignalAgeSessions? })`** — Joins daily `BarRecord[]` (caller-supplied `'total'`-adjusted closes in any order) with point-in-time `SignalObservation[]` (`{ listingId, knownAt, value }`) into Vault-safe `SignalCrossSection[]` slices ready for `analyzeSignal`. Returns `{ panel, sessionDates, diagnostics }` with strictly ascending `date`s, `ids: Int32Array` sorted ascending by `listingId`, and `signal` / `forwardReturn` as `Float64Array`, deterministic under any input permutation and without mutating caller inputs. +- **`shortsTableToSignalRows(table, field)`** — Maps a `MarketDataStore.shortsAsOf` `Table` into `SignalObservation[]` for `field: 'shares_short' | 'net_change' | 'pct_float'`, skipping `null` cells, normalizing `-0` to `0`, and rejecting missing columns or malformed rows with `SignalPanelError`. +- **`collectBars(iterable)`** — Drains `AsyncIterable` (such as `MarketDataStore.bars`) into a flat `BarRecord[]` using indexed loops without mutating yielded batches. + +### UTC Session Calendar, PIT Alignment & Vault Rules + +- **UTC session calendar:** Daily curated bars (`bars_1d.ts`) are stamped at `16:00 ET` (`20:00` or `21:00 UTC`), so the integer UTC day key `Math.floor(bar.ts / 86_400_000)` maps 1:1 to the exchange session date `YYYY-MM-DD`. +- **Strict point-in-time (`knownAt <= bar.ts`):** For each listing and session `d`, the active signal is the latest row with `knownAt <= bar.ts` (ties on identical `(listingId, knownAt)` break deterministically by `value ASC` so the highest value wins regardless of input order). A signal known after the close (e.g. `17:00 ET`) is never applied on `d` and first takes effect on `d + 1`. +- **Signal staleness (`maxSignalAgeSessions`):** When set (`>= 0`), age is measured in calendar sessions elapsed since the first actionable session where `sessionMaxTs[s] >= knownAt` (so a `17:00 ET` after-close signal has age `0` on the next trading day). Expired observations are dropped and counted in `diagnostics.droppedStaleSignal`. +- **Exact horizon alignment & close validation:** `forwardReturn = close[d + h] / close[d] - 1` uses the listing's own bar exactly `horizonSessions` calendar sessions ahead; missing forward bars are dropped (`diagnostics.droppedMissingForwardBar`) and never shifted to `d + h + 1`. Non-positive or non-finite closes (`<= 0`, `NaN`, `±Infinity`) drop cleanly into `diagnostics.droppedNonPositiveClose` without throwing. Exact pre-cutoff duplicate bars (`ts` and `close` identical) are deduplicated into `diagnostics.duplicateBars`; conflicting duplicates on the same `(listingId, date)` throw `SignalPanelError('duplicate_bar')`. +- **Vault holdout fence:** `sessionDates` contains only dates strictly `< vaultCutoffDate`. No cross-section is emitted when either `d` or its forward session `d + horizonSessions` reaches or exceeds `vaultCutoffDate` (counted in `diagnostics.vaultExcludedDates`), and `bar.close` is never accessed for any bar on or after `vaultCutoffDate`. + +### `SignalPanelError` Codes + +| Code | Meaning | +| --- | --- | +| `'invalid_input'` | Non-object input envelope, non-array `bars`/`signals`, invalid `AsyncIterable`, invalid shorts field, or missing required table columns | +| `'invalid_horizon'` | `horizonSessions` is not a safe integer `>= 1` | +| `'invalid_option'` | `maxSignalAgeSessions` is defined and not a safe integer `>= 0` | +| `'invalid_date'` | `vaultCutoffDate` is not a valid strict calendar `YYYY-MM-DD` date | +| `'invalid_bar'` | Malformed bar record, invalid `INT32` `listingId`, invalid epoch-ms `ts`/`knownAt`, non-number pre-cutoff `close`, or malformed `BarBatch` | +| `'invalid_signal'` | Malformed signal or shorts table row, invalid `listingId`/`knownAt`, or non-finite non-null signal value | +| `'duplicate_bar'` | Two pre-cutoff bars for the same `(listingId, date)` disagree on `ts` or `close` | + +### Local In-Memory Benchmark (`buildForwardReturnPanel`) + +Fixed-seed (`20261129`) local benchmark covering `5,040` business sessions × `3,000` listings (`15,120,000` input bars, `720,000` monthly-ish `17:00 ET` signal rows, `horizonSessions = 5`, `vaultCutoffDate = '2025-03-31'`): + +- **Command:** `bun run libs/research/scripts/benchmark-signal-panel.ts` +- **Observed (Bun 1.2.16):** `elapsedMs = 817.24 ms`, `rowsPerSec = 18,501,301 rows/s` (`5,014` emitted panel dates, `15,042,000` emitted observations, `25` Vault-excluded dates, pinned checksum `f0f28bdf`) diff --git a/libs/research/package.json b/libs/research/package.json index 9c2f57a9..a3ad5417 100644 --- a/libs/research/package.json +++ b/libs/research/package.json @@ -13,6 +13,7 @@ "./market-data-store": "./src/market-data-store.ts", "./market-data-store-duckdb": "./src/market-data-store-duckdb.ts", "./results": "./src/results.ts", + "./signal-panel": "./src/signal-panel.ts", "./signal-study": "./src/signal-study.ts", "./strategy-api": "./src/strategy-api.ts", "./trial-ledger": "./src/trial-ledger.ts" diff --git a/libs/research/scripts/benchmark-signal-panel.ts b/libs/research/scripts/benchmark-signal-panel.ts new file mode 100644 index 00000000..b6b41fb4 --- /dev/null +++ b/libs/research/scripts/benchmark-signal-panel.ts @@ -0,0 +1,196 @@ +import type { BarRecord } from '../src/market-data-store'; +import { type SignalObservation, buildForwardReturnPanel } from '../src/signal-panel'; + +const SEED = 20261129; +const SESSIONS = 5_040; +const LISTINGS = 3_000; +const SIGNAL_STRIDE_SESSIONS = 21; +const HORIZON_SESSIONS = 5; +const PRE_CUTOFF_SESSIONS = 5_020; + +function createMulberry32(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; + +function generateBusinessCalendar(count: number, startYear: number): { + dates: string[]; + closeTs: Float64Array; + afterCloseTs: Float64Array; +} { + const dates: string[] = new Array(count); + const closeTs = new Float64Array(count); + const afterCloseTs = new Float64Array(count); + let year = startYear; + let month = 1; + let day = 1; + // 2006-01-01 was a Sunday (dow = 0) + let dow = 0; + let produced = 0; + + while (produced < count) { + if (dow !== 0 && dow !== 6) { + const yyyy = String(year).padStart(4, '0'); + const mm = String(month).padStart(2, '0'); + const dd = String(day).padStart(2, '0'); + dates[produced] = `${yyyy}-${mm}-${dd}`; + closeTs[produced] = Date.UTC(year, month - 1, day, 21, 0, 0, 0); // 16:00 ET + afterCloseTs[produced] = Date.UTC(year, month - 1, day, 22, 0, 0, 0); // 17:00 ET + produced += 1; + } + + dow = (dow + 1) % 7; + day += 1; + const baseDays = DAYS_IN_MONTH[month] ?? 31; + const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays; + if (day > maxDay) { + day = 1; + month += 1; + if (month > 12) { + month = 1; + year += 1; + } + } + } + + return { dates, closeTs, afterCloseTs }; +} + +function fnv1aByte(hash: number, byte: number): number { + return Math.imul((hash ^ (byte & 0xff)) >>> 0, 0x01000193) >>> 0; +} + +function fnv1aUint32(hash: number, value: number): number { + const v = value >>> 0; + let h = fnv1aByte(hash, v & 0xff); + h = fnv1aByte(h, (v >>> 8) & 0xff); + h = fnv1aByte(h, (v >>> 16) & 0xff); + h = fnv1aByte(h, (v >>> 24) & 0xff); + return h; +} + +function fnv1aBytes(hash: number, bytes: Uint8Array): number { + let h = hash >>> 0; + for (let i = 0; i < bytes.length; i += 1) { + h = Math.imul((h ^ (bytes[i] as number)) >>> 0, 0x01000193) >>> 0; + } + return h; +} + +const rng = createMulberry32(SEED); +const calendar = generateBusinessCalendar(SESSIONS, 2006); +const vaultCutoffDate = calendar.dates[PRE_CUTOFF_SESSIONS] as string; + +const totalBars = SESSIONS * LISTINGS; +const bars: BarRecord[] = new Array(totalBars); +const signalsPerListing = Math.ceil(SESSIONS / SIGNAL_STRIDE_SESSIONS); +const signals: SignalObservation[] = new Array(LISTINGS * signalsPerListing); + +let barIdx = 0; +let sigIdx = 0; + +for (let l = 0; l < LISTINGS; l += 1) { + const listingId = l + 1; + let price = 10 + (l % 200) * 0.5; + for (let t = 0; t < SESSIONS; t += 1) { + const ts = calendar.closeTs[t] as number; + price = Math.max(1, price * (1 + (rng() - 0.4995) * 0.02)); + bars[barIdx++] = { + listingId, + ts, + open: price, + high: price, + low: price, + close: price, + volume: 10_000, + vwap: price, + knownAt: ts, + }; + if (t % SIGNAL_STRIDE_SESSIONS === 0) { + signals[sigIdx++] = { + listingId, + knownAt: calendar.afterCloseTs[t] as number, + value: rng() * 2 - 1, + }; + } + } +} + +// Timed section: pure buildForwardReturnPanel execution (no fixture generation or checksum). +const started = performance.now(); +const result = buildForwardReturnPanel({ + bars, + signals, + horizonSessions: HORIZON_SESSIONS, + vaultCutoffDate, +}); +const elapsedMs = performance.now() - started; + +// Untimed verification pass: FNV-1a 32-bit checksum over lengths, diagnostics, and typed-array bytes. +let checksum = 0x811c9dc5; +checksum = fnv1aUint32(checksum, result.panel.length); +checksum = fnv1aUint32(checksum, result.sessionDates.length); +checksum = fnv1aUint32(checksum, result.diagnostics.vaultExcludedDates); +checksum = fnv1aUint32(checksum, result.diagnostics.droppedNoSignal); +checksum = fnv1aUint32(checksum, result.diagnostics.droppedStaleSignal); +checksum = fnv1aUint32(checksum, result.diagnostics.droppedMissingForwardBar); +checksum = fnv1aUint32(checksum, result.diagnostics.droppedNonPositiveClose); +checksum = fnv1aUint32(checksum, result.diagnostics.duplicateBars); + +let emittedObservations = 0; +for (let i = 0; i < result.panel.length; i += 1) { + const slice = result.panel[i]; + if (slice === undefined) { + continue; + } + const ids = slice.ids as Int32Array; + const sig = slice.signal as Float64Array; + const ret = slice.forwardReturn as Float64Array; + emittedObservations += ids.length; + checksum = fnv1aBytes(checksum, new Uint8Array(ids.buffer, ids.byteOffset, ids.byteLength)); + checksum = fnv1aBytes(checksum, new Uint8Array(sig.buffer, sig.byteOffset, sig.byteLength)); + checksum = fnv1aBytes(checksum, new Uint8Array(ret.buffer, ret.byteOffset, ret.byteLength)); +} +const checksumHex = checksum.toString(16).padStart(8, '0'); + +const EXPECTED_CHECKSUM = 'f0f28bdf'; +if (checksumHex !== EXPECTED_CHECKSUM) { + throw new Error( + `Benchmark checksum mismatch: expected ${EXPECTED_CHECKSUM}, got ${checksumHex}.` + ); +} + +const rowsPerSec = Math.round(totalBars / (elapsedMs / 1000)); + +console.log( + JSON.stringify( + { + seed: SEED, + sessions: SESSIONS, + listings: LISTINGS, + horizonSessions: HORIZON_SESSIONS, + vaultCutoffDate, + inputBars: totalBars, + inputSignals: signals.length, + panelDates: result.panel.length, + emittedObservations, + elapsedMs: Number(elapsedMs.toFixed(2)), + rowsPerSec, + diagnostics: result.diagnostics, + checksum: checksumHex, + }, + null, + 2 + ) +); diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index 927bd71e..4f867394 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -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'; diff --git a/libs/research/src/signal-panel.ts b/libs/research/src/signal-panel.ts new file mode 100644 index 00000000..e293d462 --- /dev/null +++ b/libs/research/src/signal-panel.ts @@ -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 = new Set(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 { + 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` (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): Promise { + 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 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(); + const preCutoffDayMaxTs = new Map(); + const listingBarCounts = new Map(); + 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(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(); + 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 | 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(); + 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).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(emittableDateLimit).fill( + null + ); + const bucketSignals: (Float64Array | null)[] = new Array( + emittableDateLimit + ).fill(null); + const bucketReturns: (Float64Array | null)[] = new Array( + 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, + }, + }; +} diff --git a/libs/research/test/signal-panel-e2e.test.ts b/libs/research/test/signal-panel-e2e.test.ts new file mode 100644 index 00000000..f221c65c --- /dev/null +++ b/libs/research/test/signal-panel-e2e.test.ts @@ -0,0 +1,375 @@ +import { describe, expect, it } from 'bun:test'; +import { + analyzeSignal, + buildForwardReturnPanel, + collectBars, + createDuckDbMarketDataStore, + shortsTableToSignalRows, + type DuckDbExecutor, + type DuckDbParam, + type TableRow, + type TrialLedgerExecutor, +} from '@stock-bot/research'; + +const CURATED_ROOT = '/mnt/data/stockbot/curated'; +const SEED = 20261129; + +function createSeededRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +function makeBusinessDates(startDate: string, count: number): string[] { + const out: string[] = new Array(count); + const current = new Date(`${startDate}T00:00:00.000Z`); + let written = 0; + while (written < count) { + const day = current.getUTCDay(); + if (day !== 0 && day !== 6) { + out[written] = current.toISOString().slice(0, 10); + written += 1; + } + current.setUTCDate(current.getUTCDate() + 1); + } + return out; +} + +function makeUtcMs(date: string, hourUtc: number): number { + const [y, m, d] = date.split('-').map(Number); + return Date.UTC(y!, m! - 1, d!, hourUtc, 0, 0, 0); +} + +interface StoredTrialRow { + readonly trial_id: string; + readonly created_at: Date; + readonly principal_id: string; + readonly campaign_id: string | null; + readonly stage: string; + readonly universe_market: string; + readonly horizon_bucket: string; + readonly hypothesis_id: string | null; + readonly expression_hash: string; + readonly sample_start: string; + readonly sample_end: string; + readonly n_obs: number; + readonly sharpe_unann: number; + readonly skewness: number; + readonly kurtosis: number; + readonly daily_series: readonly number[]; +} + +function createInMemoryTrialExecutor(): { + executor: TrialLedgerExecutor; + rows: StoredTrialRow[]; +} { + const rows: StoredTrialRow[] = []; + let nextTrialId = 1; + + const executor: TrialLedgerExecutor = { + async query>(text: string, params?: readonly unknown[]) { + const trimmed = text.trimStart(); + if (trimmed.startsWith('INSERT INTO trial_ledger')) { + const p = params ?? []; + const trialId = nextTrialId++; + const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId)); + const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); + const stored: StoredTrialRow = { + trial_id: String(trialId), + created_at: createdAt, + principal_id: p[0] as string, + campaign_id: (p[1] as string | null) ?? null, + stage: p[2] as string, + universe_market: p[3] as string, + horizon_bucket: p[4] as string, + hypothesis_id: (p[5] as string | null) ?? null, + expression_hash: p[6] as string, + sample_start: p[7] as string, + sample_end: p[8] as string, + n_obs: p[9] as number, + sharpe_unann: p[10] as number, + skewness: p[11] as number, + kurtosis: p[12] as number, + daily_series: dailySeries, + }; + rows.push(stored); + return { + rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row], + rowCount: 1, + }; + } + + if (trimmed.startsWith('SELECT')) { + if (text.includes('WHERE trial_id = $1::bigint')) { + const targetId = String(params?.[0]); + const matched = rows.filter(r => r.trial_id === targetId); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + if (text.includes('WHERE universe_market = $1')) { + const market = params?.[0] as string; + const bucket = params?.[1] as string; + const matched = rows.filter( + r => r.universe_market === market && r.horizon_bucket === bucket + ); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + } + + return { rows: [], rowCount: 0 }; + }, + }; + + return { executor, rows }; +} + +interface CeoShortsFixture { + readonly listingIds: number[]; + readonly allDates: string[]; + readonly vaultCutoffDate: string; + readonly vaultCutoffTs: number; + readonly barRows: TableRow[]; + readonly shortsRows: TableRow[]; +} + +function buildCeoShortsFixture(poisonPostCutoff: boolean): CeoShortsFixture { + const rand = createSeededRng(SEED); + const listingCount = 28; + const preCutoffSessions = 140; // spans late 2022 through early 2023 (pre-2023 & post-2023) + const postCutoffSessions = 10; + const allDates = makeBusinessDates('2022-09-01', preCutoffSessions + postCutoffSessions); + const vaultCutoffDate = allDates[preCutoffSessions]!; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + + const listingIds = Array.from({ length: listingCount }, (_, i) => 50_001 + i); + const barRows: TableRow[] = []; + const shortsRows: TableRow[] = []; + + // Semi-monthly ceoShorts reports (every 10 trading sessions), published at 17:00 ET (22:00 UTC). + // Plant a negative relationship: higher net_change predicts lower subsequent 5-session return. + const activeNetChange = new Float64Array(listingCount); + const prices = new Float64Array(listingCount); + for (let l = 0; l < listingCount; l += 1) { + prices[l] = 10 + l * 1.5; + } + + for (let t = 0; t < allDates.length; t += 1) { + const date = allDates[t]!; + const closeTs = makeUtcMs(date, 21); // 16:00 ET close + + if (t % 10 === 0) { + const reportKnownAt = makeUtcMs(date, 22); // 17:00 ET (after close -> effective next session) + for (let l = 0; l < listingCount; l += 1) { + const isNullCell = t > 0 && (t + l) % 19 === 0; + const netChange = isNullCell ? null : Math.round((rand() * 2 - 1) * 20_000); + if (netChange !== null) { + activeNetChange[l] = netChange / 20_000; // normalized in [-1, 1] + } + shortsRows.push({ + listing_id: listingIds[l]!, + report_date: date, + known_at: reportKnownAt, + shares_short: 100_000 + l * 5_000 + Math.round(rand() * 10_000), + net_change: netChange, + pct_float: isNullCell ? null : Number((0.02 + rand() * 0.08).toFixed(4)), + source: 'ceoShorts', + }); + } + } + + for (let l = 0; l < listingCount; l += 1) { + // Drift driven negatively by prior known short-interest change + idiosyncratic noise. + const dailyRet = -0.004 * activeNetChange[l]! + (rand() * 2 - 1) * 0.008; + prices[l] = Math.max(0.5, prices[l]! * (1 + dailyRet)); + + const isPostCutoff = date >= vaultCutoffDate; + const closeVal = poisonPostCutoff && isPostCutoff ? 999_999 : Number(prices[l]!.toFixed(6)); + barRows.push({ + listing_id: listingIds[l]!, + ts: closeTs, + open: closeVal, + high: closeVal, + low: closeVal, + close: closeVal, + volume: 50_000, + vwap: closeVal, + known_at: closeTs, + }); + } + } + + return { + listingIds, + allDates, + vaultCutoffDate, + vaultCutoffTs, + barRows, + shortsRows, + }; +} + +function createFakeDuckDbExecutor(fixture: CeoShortsFixture): { + executor: DuckDbExecutor; + runStatements: string[]; + queryCount: () => number; +} { + const runStatements: string[] = []; + let queries = 0; + + const executor: DuckDbExecutor = { + async run(sql: string) { + runStatements.push(sql); + }, + async query(sql: string, params: readonly DuckDbParam[]): Promise { + queries += 1; + + if (sql.includes('bars_1d/year=*/part.parquet')) { + // Bound params: [...listingIds, fromIso, toIso, asOfIso] + const nIds = fixture.listingIds.length; + const idSet = new Set(params.slice(0, nIds) as number[]); + const fromMs = Date.parse(params[nIds] as string); + const toMs = Date.parse(params[nIds + 1] as string); + const asOfMs = Date.parse(params[nIds + 2] as string); + return fixture.barRows.filter(row => { + const lid = row.listing_id as number; + const ts = row.ts as number; + const knownAt = row.known_at as number; + return idSet.has(lid) && ts >= fromMs && ts <= toMs && knownAt <= asOfMs; + }); + } + + if (sql.includes('shorts/part.parquet')) { + // Bound params: [...listingIds, fromDate, toDate, asOfIso] + const nIds = fixture.listingIds.length; + const idSet = new Set(params.slice(0, nIds) as number[]); + const fromDate = params[nIds] as string; + const toDate = params[nIds + 1] as string; + const asOfMs = Date.parse(params[nIds + 2] as string); + return fixture.shortsRows.filter(row => { + const lid = row.listing_id as number; + const reportDate = row.report_date as string; + const knownAt = row.known_at as number; + return idSet.has(lid) && reportDate >= fromDate && reportDate <= toDate && knownAt <= asOfMs; + }); + } + + throw new Error(`Unexpected SQL in fake DuckDbExecutor: ${sql}`); + }, + }; + + return { + executor, + runStatements, + queryCount: () => queries, + }; +} + +describe('ceoShorts end-to-end signal study (headless, no database)', () => { + async function runCeoShortsStudy(poisonPostCutoff: boolean) { + const fixture = buildCeoShortsFixture(poisonPostCutoff); + const duck = createFakeDuckDbExecutor(fixture); + const ledger = createInMemoryTrialExecutor(); + + const store = createDuckDbMarketDataStore({ + executor: duck.executor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: fixture.vaultCutoffTs, + barBatchSize: 256, + }); + + const from = fixture.allDates[0]!; + const to = fixture.allDates[fixture.allDates.length - 1]!; + + const bars = await collectBars( + store.bars({ + listingIds: fixture.listingIds, + timeframe: '1d', + from, + to, + adjustment: 'raw', + }) + ); + const shortsTable = await store.shortsAsOf({ + listingIds: fixture.listingIds, + from, + to, + }); + + const signals = shortsTableToSignalRows(shortsTable, 'net_change'); + const built = buildForwardReturnPanel({ + bars, + signals, + horizonSessions: 5, + vaultCutoffDate: fixture.vaultCutoffDate, + }); + + const studyResult = await analyzeSignal(ledger.executor, { + principalId: 'operator', + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'ceoshorts_net_change_5d', + params: { field: 'net_change', horizonSessions: 5 }, + universe: 'CA_EQ_FIXTURE', + horizon: '5d', + }, + panel: built.panel, + vaultCutoffDate: fixture.vaultCutoffDate, + }); + + return { fixture, duck, ledger, built, studyResult }; + } + + it('flows DuckDbMarketDataStore -> buildForwardReturnPanel -> analyzeSignal -> trial_ledger + DSR', async () => { + const clean = await runCeoShortsStudy(false); + + // DuckDB connection budget SET statements ran exactly once. + expect(clean.duck.runStatements).toHaveLength(3); + expect(clean.duck.runStatements[0]).toContain('SET memory_limit'); + expect(clean.duck.runStatements[1]).toContain('SET threads'); + expect(clean.duck.runStatements[2]).toContain('SET temp_directory'); + expect(clean.duck.queryCount()).toBe(2); // 1 bars query + 1 shortsAsOf query + + // Panel Vault safety: no emitted date or forward session >= vaultCutoffDate. + expect(clean.built.panel.length).toBeGreaterThan(100); + for (const slice of clean.built.panel) { + expect(slice.date < clean.fixture.vaultCutoffDate).toBe(true); + const idx = clean.built.sessionDates.indexOf(slice.date); + expect(idx).toBeGreaterThanOrEqual(0); + expect(idx + 5).toBeLessThan(clean.built.sessionDates.length); + expect(clean.built.sessionDates[idx + 5]! < clean.fixture.vaultCutoffDate).toBe(true); + } + + // Signal study succeeded and inserted exactly one `signal_ic` row for CA_EQ. + expect(clean.studyResult.status).toBe('ok'); + if (clean.studyResult.status !== 'ok') { + return; + } + + expect(clean.ledger.rows).toHaveLength(1); + const stored = clean.ledger.rows[0]!; + expect(stored.stage).toBe('signal_ic'); + expect(stored.universe_market).toBe('CA_EQ'); + expect(stored.horizon_bucket).toBe('swing_1_10d'); + expect(clean.studyResult.trial.sampleEnd < clean.fixture.vaultCutoffDate).toBe(true); + expect(stored.sample_end < clean.fixture.vaultCutoffDate).toBe(true); + + // Finite DSR with effectiveTrials >= 1. + expect(clean.studyResult.deflatedSharpe.dsr).not.toBeNull(); + expect(Number.isFinite(clean.studyResult.deflatedSharpe.dsr!)).toBe(true); + expect(clean.studyResult.deflatedSharpe.effectiveTrials).toBeGreaterThanOrEqual(1); + + // Planted negative short-interest change -> next-5-session return relationship yields negative mean rank-IC. + expect(clean.studyResult.analysis.rankIc.mean).not.toBeNull(); + expect(clean.studyResult.analysis.rankIc.mean!).toBeLessThan(0); + + // Poisoning post-cutoff fixture bars leaves study result and trial_ledger row byte-identical. + const poisoned = await runCeoShortsStudy(true); + expect(poisoned.studyResult).toEqual(clean.studyResult); + expect(poisoned.ledger.rows).toEqual(clean.ledger.rows); + expect(poisoned.built).toEqual(clean.built); + }); +}); diff --git a/libs/research/test/signal-panel.test.ts b/libs/research/test/signal-panel.test.ts new file mode 100644 index 00000000..6f4ca1c5 --- /dev/null +++ b/libs/research/test/signal-panel.test.ts @@ -0,0 +1,766 @@ +import { describe, expect, it } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { + SHORTS_SIGNAL_FIELDS, + SignalPanelError, + buildForwardReturnPanel, + collectBars, + shortsTableToSignalRows, + type BarBatch, + type BarRecord, + type SignalObservation, + type SignalPanelErrorCode, + type Table, +} from '@stock-bot/research'; +import { + SHORTS_SIGNAL_FIELDS as SubpathShortsSignalFields, + SignalPanelError as SubpathSignalPanelError, + buildForwardReturnPanel as subpathBuildForwardReturnPanel, + collectBars as subpathCollectBars, + shortsTableToSignalRows as subpathShortsTableToSignalRows, +} from '@stock-bot/research/signal-panel'; + +function makeUtcMs(date: string, hourUtc = 21, minuteUtc = 0, secondUtc = 0, ms = 0): number { + const [y, m, d] = date.split('-').map(Number); + return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, secondUtc, ms); +} + +function makeBusinessDates(startDate: string, count: number): string[] { + const out: string[] = new Array(count); + const current = new Date(`${startDate}T00:00:00.000Z`); + let written = 0; + while (written < count) { + const day = current.getUTCDay(); + if (day !== 0 && day !== 6) { + out[written] = current.toISOString().slice(0, 10); + written += 1; + } + current.setUTCDate(current.getUTCDate() + 1); + } + return out; +} + +function makeBar(listingId: number, date: string, close: number, hourUtc = 21): BarRecord { + const ts = makeUtcMs(date, hourUtc, 0, 0, 0); + return { + listingId, + ts, + open: close, + high: close, + low: close, + close, + volume: 1_000, + vwap: close, + knownAt: ts, + }; +} + +function createSeededRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +function shuffle(items: readonly T[], seed: number): T[] { + const copy = [...items]; + const rand = createSeededRng(seed); + for (let i = copy.length - 1; i > 0; i -= 1) { + const j = Math.floor(rand() * (i + 1)); + const tmp = copy[i]!; + copy[i] = copy[j]!; + copy[j] = tmp; + } + return copy; +} + +function expectSignalPanelError(fn: () => unknown, code: SignalPanelErrorCode): SignalPanelError { + try { + fn(); + } catch (err) { + expect(err).toBeInstanceOf(SignalPanelError); + const typed = err as SignalPanelError; + expect(typed.code).toBe(code); + return typed; + } + throw new Error(`Expected SignalPanelError(${code}), but function did not throw.`); +} + +async function expectSignalPanelErrorAsync( + fn: () => Promise, + code: SignalPanelErrorCode +): Promise { + try { + await fn(); + } catch (err) { + expect(err).toBeInstanceOf(SignalPanelError); + const typed = err as SignalPanelError; + expect(typed.code).toBe(code); + return typed; + } + throw new Error(`Expected async SignalPanelError(${code}), but promise resolved.`); +} + +describe('@stock-bot/research signal-panel exports and browser safety', () => { + it('exposes identical symbols from root and ./signal-panel subpath', () => { + expect(buildForwardReturnPanel).toBe(subpathBuildForwardReturnPanel); + expect(shortsTableToSignalRows).toBe(subpathShortsTableToSignalRows); + expect(collectBars).toBe(subpathCollectBars); + expect(SignalPanelError).toBe(SubpathSignalPanelError); + expect(SHORTS_SIGNAL_FIELDS).toBe(SubpathShortsSignalFields); + }); + + it('has zero node:* imports, zero bare process access, and no new package dependencies', () => { + const src = readFileSync(new URL('../src/signal-panel.ts', import.meta.url), 'utf8'); + expect(src).not.toMatch(/from\s+['"]node:/); + expect(src).not.toMatch(/require\s*\(\s*['"]node:/); + expect(src).not.toMatch(/\bprocess\./); + + const pkg = JSON.parse( + readFileSync(new URL('../package.json', import.meta.url), 'utf8') + ) as { + exports: Record; + dependencies: Record; + }; + expect(pkg.exports['./signal-panel']).toBe('./src/signal-panel.ts'); + expect(Object.keys(pkg.dependencies).sort()).toEqual([ + '@stock-bot/calculations', + '@stock-bot/stock-config', + '@stock-bot/types', + 'zod', + ]); + }); +}); + +describe('buildForwardReturnPanel', () => { + it('computes exact hand-verified forward returns for horizons 1, 5, and 20', () => { + const dates = makeBusinessDates('2024-01-02', 25); + const bars: BarRecord[] = []; + const signals: SignalObservation[] = []; + + // Listing 20 and Listing 10 intentionally inserted out of order to verify ascending ids. + for (let i = 0; i < dates.length; i += 1) { + bars.push(makeBar(20, dates[i]!, 100 + i * 2)); + bars.push(makeBar(10, dates[i]!, 50 + i)); + } + signals.push( + { listingId: 10, knownAt: makeUtcMs(dates[0]!, 20), value: 1.5 }, + { listingId: 20, knownAt: makeUtcMs(dates[0]!, 20), value: -2.5 } + ); + + for (const horizon of [1, 5, 20] as const) { + const result = buildForwardReturnPanel({ + bars, + signals, + horizonSessions: horizon, + vaultCutoffDate: '2025-01-01', + }); + + const expectedEmittedDates = dates.length - horizon; + expect(result.sessionDates).toEqual(dates); + expect(result.panel).toHaveLength(expectedEmittedDates); + expect(result.diagnostics.vaultExcludedDates).toBe(0); + expect(result.diagnostics.droppedNoSignal).toBe(0); + expect(result.diagnostics.droppedStaleSignal).toBe(0); + expect(result.diagnostics.droppedMissingForwardBar).toBe(horizon * 2); + expect(result.diagnostics.droppedNonPositiveClose).toBe(0); + expect(result.diagnostics.duplicateBars).toBe(0); + + let emittedObs = 0; + for (let t = 0; t < expectedEmittedDates; t += 1) { + const slice = result.panel[t]!; + expect(slice.date).toBe(dates[t]); + expect(slice.ids).toBeInstanceOf(Int32Array); + expect(slice.signal).toBeInstanceOf(Float64Array); + expect(slice.forwardReturn).toBeInstanceOf(Float64Array); + expect(Array.from(slice.ids)).toEqual([10, 20]); + expect(Array.from(slice.signal)).toEqual([1.5, -2.5]); + + const expectedRet10 = (50 + t + horizon) / (50 + t) - 1; + const expectedRet20 = (100 + (t + horizon) * 2) / (100 + t * 2) - 1; + expect(slice.forwardReturn[0]).toBeCloseTo(expectedRet10, 12); + expect(slice.forwardReturn[1]).toBeCloseTo(expectedRet20, 12); + emittedObs += slice.ids.length; + } + + // Conservation identity: emitted + all drops === unique pre-cutoff bars. + const totalDrops = + result.diagnostics.droppedNoSignal + + result.diagnostics.droppedStaleSignal + + result.diagnostics.droppedMissingForwardBar + + result.diagnostics.droppedNonPositiveClose; + expect(emittedObs + totalDrops).toBe(bars.length); + } + }); + + it('enforces strict knownAt <= bar.ts point-in-time rule and deterministic tie-breaking', () => { + const dates = makeBusinessDates('2024-03-04', 5); + const bars: BarRecord[] = dates.map((d, idx) => makeBar(1, d, 100 + idx * 10)); + + const day0CloseTs = makeUtcMs(dates[0]!, 21, 0, 0, 0); + const day1CloseTs = makeUtcMs(dates[1]!, 21, 0, 0, 0); + const signals: SignalObservation[] = [ + // Known 1 ms AFTER day 0 close -> must NOT apply on day 0, MUST apply on day 1. + { listingId: 1, knownAt: day0CloseTs + 1, value: 10 }, + // Known EXACTLY at day 1 close -> MUST apply on day 1, overriding the day0+1ms signal. + { listingId: 1, knownAt: day1CloseTs, value: 20 }, + // Tie at exact same knownAt on day 1 close -> deterministic max value (25) regardless of order. + { listingId: 1, knownAt: day1CloseTs, value: 25 }, + ]; + + const result = buildForwardReturnPanel({ + bars, + signals, + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + }); + + expect(result.diagnostics.droppedNoSignal).toBe(1); // day 0 had no eligible signal + expect(result.panel.map(s => s.date)).toEqual([dates[1], dates[2], dates[3]]); + expect(result.panel[0]!.signal[0]).toBe(25); + expect(result.panel[1]!.signal[0]).toBe(25); + expect(result.panel[2]!.signal[0]).toBe(25); + + // Reverse signal order must produce the exact same tie-break value. + const reversed = buildForwardReturnPanel({ + bars, + signals: [...signals].reverse(), + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + }); + expect(reversed.panel.map(s => s.signal[0])).toEqual([25, 25, 25]); + }); + + it('drops observations whose forward bar at d + h is missing instead of shifting to d + h + 1', () => { + const dates = makeBusinessDates('2024-04-01', 6); + // Listing 1 has all 6 sessions; Listing 2 is missing dates[3]. + const bars: BarRecord[] = []; + for (let i = 0; i < dates.length; i += 1) { + bars.push(makeBar(1, dates[i]!, 100 + i)); + if (i !== 3) { + bars.push(makeBar(2, dates[i]!, 200 + i)); + } + } + const signals: SignalObservation[] = [ + { listingId: 1, knownAt: makeUtcMs(dates[0]!, 10), value: 1 }, + { listingId: 2, knownAt: makeUtcMs(dates[0]!, 10), value: 2 }, + ]; + + const result = buildForwardReturnPanel({ + bars, + signals, + horizonSessions: 2, + vaultCutoffDate: '2025-01-01', + }); + + // On dates[1], target is dates[3]. Listing 2 has no bar on dates[3], so it must be dropped + // rather than using dates[4]. + const sliceDay1 = result.panel.find(s => s.date === dates[1])!; + expect(Array.from(sliceDay1.ids)).toEqual([1]); + // On dates[2], target is dates[4], which Listing 2 DOES have. + const sliceDay2 = result.panel.find(s => s.date === dates[2])!; + expect(Array.from(sliceDay2.ids)).toEqual([1, 2]); + expect(sliceDay2.forwardReturn[1]).toBeCloseTo(204 / 202 - 1, 12); + + // Missing forward bars: Listing 1 misses dates[4], dates[5] (2); + // Listing 2 misses dates[1] (-> dates[3]), dates[4], dates[5] (3). Total = 5. + expect(result.diagnostics.droppedMissingForwardBar).toBe(5); + }); + + it('enforces maxSignalAgeSessions including age 0 and after-close 17:00 ET signals', () => { + const dates = makeBusinessDates('2024-05-06', 6); + const bars: BarRecord[] = dates.map((d, idx) => makeBar(1, d, 100 + idx, 20)); // 16:00 EDT = 20:00 UTC + + // Signal published at 17:00 EDT (21:00 UTC) on dates[0] -> first actionable session is dates[1] (age 0). + const signals: SignalObservation[] = [ + { listingId: 1, knownAt: makeUtcMs(dates[0]!, 21, 0), value: 3.14 }, + ]; + + // maxSignalAgeSessions = 0: only dates[1] is emitted; dates[2], dates[3], dates[4], dates[5] are stale. + const age0 = buildForwardReturnPanel({ + bars, + signals, + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + maxSignalAgeSessions: 0, + }); + expect(age0.panel.map(s => s.date)).toEqual([dates[1]]); + expect(age0.diagnostics.droppedNoSignal).toBe(1); // dates[0] + expect(age0.diagnostics.droppedStaleSignal).toBe(4); // dates[2..5] + + // maxSignalAgeSessions = 2: dates[1] (age 0), dates[2] (age 1), dates[3] (age 2) emitted; + // dates[4] (age 3) and dates[5] (age 4) dropped as stale. + const age2 = buildForwardReturnPanel({ + bars, + signals, + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + maxSignalAgeSessions: 2, + }); + expect(age2.panel.map(s => s.date)).toEqual([dates[1], dates[2], dates[3]]); + expect(age2.diagnostics.droppedNoSignal).toBe(1); + expect(age2.diagnostics.droppedStaleSignal).toBe(2); + }); + + it('drops non-positive and non-finite entry/exit closes into droppedNonPositiveClose without throwing', () => { + const dates = makeBusinessDates('2024-06-03', 6); + const closes = [100, 0, -5, Number.NaN, Number.POSITIVE_INFINITY, 120]; + const bars: BarRecord[] = dates.map((d, i) => makeBar(1, d, closes[i]!)); + // Add a clean listing so we also verify normal rows survive alongside bad closes. + for (let i = 0; i < dates.length; i += 1) { + bars.push(makeBar(2, dates[i]!, 50 + i)); + } + + const signals: SignalObservation[] = [ + { listingId: 1, knownAt: makeUtcMs(dates[0]!, 10), value: 1 }, + { listingId: 2, knownAt: makeUtcMs(dates[0]!, 10), value: 2 }, + ]; + + const result = buildForwardReturnPanel({ + bars, + signals, + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + }); + + // Every pair for listing 1 touches a non-positive/non-finite close (0->1, 1->2, 2->3, 3->4, 4->5). + expect(result.diagnostics.droppedNonPositiveClose).toBe(5); + expect(result.panel).toHaveLength(5); + for (const slice of result.panel) { + expect(Array.from(slice.ids)).toEqual([2]); + } + }); + + it('deduplicates exact pre-cutoff bars and rejects conflicting duplicates', () => { + const dates = makeBusinessDates('2024-07-01', 3); + const b0 = makeBar(1, dates[0]!, 100); + const b1 = makeBar(1, dates[1]!, 110); + const b2 = makeBar(1, dates[2]!, 121); + const bNaN = makeBar(2, dates[0]!, Number.NaN); + + const result = buildForwardReturnPanel({ + bars: [b0, { ...b0 }, b1, b2, bNaN, { ...bNaN }], + signals: [{ listingId: 1, knownAt: makeUtcMs(dates[0]!, 10), value: 1 }], + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + }); + + expect(result.diagnostics.duplicateBars).toBe(2); + expect(result.panel).toHaveLength(2); + expect(result.panel[0]!.forwardReturn[0]).toBeCloseTo(0.1, 12); + + // Conflicting close on same (listingId, date) must throw duplicate_bar. + expectSignalPanelError( + () => + buildForwardReturnPanel({ + bars: [b0, { ...b0, close: 101 }, b1], + signals: [], + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + }), + 'duplicate_bar' + ); + + // Conflicting ts on same (listingId, date) must throw duplicate_bar. + expectSignalPanelError( + () => + buildForwardReturnPanel({ + bars: [b0, { ...b0, ts: b0.ts + 1_000 }, b1], + signals: [], + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + }), + 'duplicate_bar' + ); + }); + + it('enforces strict Vault cutoff across both d and d + h and never reads post-cutoff closes', () => { + const preCutoffCount = 30; + const postCutoffCount = 6; + const allDates = makeBusinessDates('2024-01-02', preCutoffCount + postCutoffCount); + const vaultCutoffDate = allDates[preCutoffCount]!; + + const baseBars: BarRecord[] = []; + for (let i = 0; i < allDates.length; i += 1) { + baseBars.push(makeBar(1, allDates[i]!, 100 + i)); + baseBars.push(makeBar(2, allDates[i]!, 200 + i * 2)); + } + const signals: SignalObservation[] = [ + { listingId: 1, knownAt: makeUtcMs(allDates[0]!, 10), value: 0.5 }, + { listingId: 2, knownAt: makeUtcMs(allDates[0]!, 10), value: -0.5 }, + ]; + + for (const horizon of [1, 5, 20] as const) { + const clean = buildForwardReturnPanel({ + bars: baseBars, + signals, + horizonSessions: horizon, + vaultCutoffDate, + }); + + const expectedEmittable = preCutoffCount - horizon; + expect(clean.sessionDates).toEqual(allDates.slice(0, preCutoffCount)); + expect(clean.sessionDates.every(d => d < vaultCutoffDate)).toBe(true); + expect(clean.panel).toHaveLength(expectedEmittable); + expect(clean.panel[clean.panel.length - 1]!.date).toBe(allDates[preCutoffCount - 1 - horizon]); + expect(clean.diagnostics.vaultExcludedDates).toBe(horizon + postCutoffCount); + + for (const slice of clean.panel) { + const idx = clean.sessionDates.indexOf(slice.date); + expect(idx).toBeGreaterThanOrEqual(0); + expect(slice.date < vaultCutoffDate).toBe(true); + const fwdDate = allDates[idx + horizon]!; + expect(fwdDate < vaultCutoffDate).toBe(true); + } + + // Poison every post-cutoff close with NaN -> output must be byte-identical. + const poisonedBars: BarRecord[] = baseBars.map(b => { + const date = new Date(b.ts).toISOString().slice(0, 10); + return date >= vaultCutoffDate ? { ...b, close: Number.NaN } : b; + }); + const poisoned = buildForwardReturnPanel({ + bars: poisonedBars, + signals, + horizonSessions: horizon, + vaultCutoffDate, + }); + expect(poisoned).toEqual(clean); + + // Getter trap on every post-cutoff bar's `close` -> must never be accessed. + let closeReadsPostCutoff = 0; + const trappedBars: BarRecord[] = baseBars.map(b => { + const date = new Date(b.ts).toISOString().slice(0, 10); + if (date < vaultCutoffDate) { + return b; + } + const trapped = { + listingId: b.listingId, + ts: b.ts, + open: b.open, + high: b.high, + low: b.low, + volume: b.volume, + vwap: b.vwap, + knownAt: b.knownAt, + } as Record; + Object.defineProperty(trapped, 'close', { + enumerable: true, + get() { + closeReadsPostCutoff += 1; + throw new Error('Post-cutoff close must never be read!'); + }, + }); + return trapped as unknown as BarRecord; + }); + + const trappedResult = buildForwardReturnPanel({ + bars: trappedBars, + signals, + horizonSessions: horizon, + vaultCutoffDate, + }); + expect(closeReadsPostCutoff).toBe(0); + expect(trappedResult).toEqual(clean); + } + }); + + it('produces byte-identical output for shuffled bars and signals and never mutates frozen inputs', () => { + const dates = makeBusinessDates('2024-08-01', 15); + const bars: BarRecord[] = []; + const signals: SignalObservation[] = []; + + for (const lid of [101, 202, 303, 404]) { + for (let i = 0; i < dates.length; i += 1) { + bars.push(makeBar(lid, dates[i]!, 50 + lid * 0.1 + i * 0.5)); + } + signals.push( + { listingId: lid, knownAt: makeUtcMs(dates[0]!, 18), value: lid * 0.01 }, + { listingId: lid, knownAt: makeUtcMs(dates[4]!, 21), value: lid * -0.02 }, + { listingId: lid, knownAt: makeUtcMs(dates[4]!, 21), value: lid * 0.03 } // intentional tie + ); + } + + const frozenInput = Object.freeze({ + bars: Object.freeze(bars.map(b => Object.freeze({ ...b }))), + signals: Object.freeze(signals.map(s => Object.freeze({ ...s }))), + horizonSessions: 3, + vaultCutoffDate: dates[12]!, + maxSignalAgeSessions: 6, + }); + + const baseline = buildForwardReturnPanel(frozenInput); + + for (const seed of [1, 2, 3, 42]) { + const shuffledResult = buildForwardReturnPanel({ + bars: shuffle(bars, seed), + signals: shuffle(signals, seed + 100), + horizonSessions: 3, + vaultCutoffDate: dates[12]!, + maxSignalAgeSessions: 6, + }); + expect(shuffledResult).toEqual(baseline); + } + }); + + it('handles empty bars and post-cutoff-only bars cleanly', () => { + const empty = buildForwardReturnPanel({ + bars: [], + signals: [{ listingId: 1, knownAt: makeUtcMs('2024-01-02', 10), value: 1 }], + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + }); + expect(empty.panel).toEqual([]); + expect(empty.sessionDates).toEqual([]); + expect(empty.diagnostics).toEqual({ + vaultExcludedDates: 0, + droppedNoSignal: 0, + droppedStaleSignal: 0, + droppedMissingForwardBar: 0, + droppedNonPositiveClose: 0, + duplicateBars: 0, + }); + + const postOnly = buildForwardReturnPanel({ + bars: [makeBar(1, '2025-01-02', 100), makeBar(1, '2025-01-03', 101)], + signals: [], + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + }); + expect(postOnly.panel).toEqual([]); + expect(postOnly.sessionDates).toEqual([]); + expect(postOnly.diagnostics.vaultExcludedDates).toBe(2); + }); + + it('throws typed SignalPanelError for every invalid input, option, date, bar, and signal', () => { + expectSignalPanelError( + () => buildForwardReturnPanel(null as unknown as Parameters[0]), + 'invalid_input' + ); + expectSignalPanelError( + () => + buildForwardReturnPanel({ + bars: 'not-an-array' as unknown as BarRecord[], + signals: [], + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + }), + 'invalid_input' + ); + expectSignalPanelError( + () => + buildForwardReturnPanel({ + bars: [], + signals: 'not-an-array' as unknown as SignalObservation[], + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + }), + 'invalid_input' + ); + + for (const badHorizon of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) { + expectSignalPanelError( + () => + buildForwardReturnPanel({ + bars: [], + signals: [], + horizonSessions: badHorizon, + vaultCutoffDate: '2025-01-01', + }), + 'invalid_horizon' + ); + } + + for (const badAge of [-1, 0.5, Number.NaN, Number.POSITIVE_INFINITY]) { + expectSignalPanelError( + () => + buildForwardReturnPanel({ + bars: [], + signals: [], + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + maxSignalAgeSessions: badAge, + }), + 'invalid_option' + ); + } + + for (const badDate of ['', '2025-02-29', '2025-13-01', '2025-01-01T00:00:00Z']) { + expectSignalPanelError( + () => + buildForwardReturnPanel({ + bars: [], + signals: [], + horizonSessions: 1, + vaultCutoffDate: badDate, + }), + 'invalid_date' + ); + } + + expectSignalPanelError( + () => + buildForwardReturnPanel({ + bars: [null as unknown as BarRecord], + signals: [], + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + }), + 'invalid_bar' + ); + expectSignalPanelError( + () => + buildForwardReturnPanel({ + bars: [{ ...makeBar(1, '2024-01-02', 100), listingId: 1.5 }], + signals: [], + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + }), + 'invalid_bar' + ); + expectSignalPanelError( + () => + buildForwardReturnPanel({ + bars: [{ ...makeBar(1, '2024-01-02', 100), close: '100' as unknown as number }], + signals: [], + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + }), + 'invalid_bar' + ); + + expectSignalPanelError( + () => + buildForwardReturnPanel({ + bars: [], + signals: [null as unknown as SignalObservation], + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + }), + 'invalid_signal' + ); + expectSignalPanelError( + () => + buildForwardReturnPanel({ + bars: [], + signals: [{ listingId: 1, knownAt: makeUtcMs('2024-01-02', 10), value: Number.NaN }], + horizonSessions: 1, + vaultCutoffDate: '2025-01-01', + }), + 'invalid_signal' + ); + }); +}); + +describe('shortsTableToSignalRows and collectBars', () => { + it('maps shortsAsOf table fields, skips nulls, normalizes -0, and rejects malformed inputs', () => { + const knownAt1 = makeUtcMs('2024-02-01', 22, 0); + const knownAt2 = makeUtcMs('2024-02-15', 22, 0); + const table: Table = { + columns: ['listing_id', 'report_date', 'known_at', 'shares_short', 'net_change', 'pct_float', 'source'], + rows: [ + { + listing_id: 10, + report_date: '2024-01-31', + known_at: knownAt1, + shares_short: 50_000, + net_change: -0, + pct_float: 0.042, + source: 'ceoShorts', + }, + { + listing_id: 20, + report_date: '2024-02-15', + known_at: knownAt2, + shares_short: 12_000, + net_change: null, + pct_float: null, + source: 'ceoShorts', + }, + ], + }; + + expect(shortsTableToSignalRows(table, 'shares_short')).toEqual([ + { listingId: 10, knownAt: knownAt1, value: 50_000 }, + { listingId: 20, knownAt: knownAt2, value: 12_000 }, + ]); + + const netChangeRows = shortsTableToSignalRows(table, 'net_change'); + expect(netChangeRows).toEqual([{ listingId: 10, knownAt: knownAt1, value: 0 }]); + expect(Object.is(netChangeRows[0]!.value, 0)).toBe(true); + + expect(shortsTableToSignalRows(table, 'pct_float')).toEqual([ + { listingId: 10, knownAt: knownAt1, value: 0.042 }, + ]); + + expectSignalPanelError( + () => shortsTableToSignalRows(table, 'bad_field' as unknown as 'net_change'), + 'invalid_input' + ); + expectSignalPanelError( + () => + shortsTableToSignalRows( + { columns: ['listing_id', 'known_at'], rows: [] }, + 'net_change' + ), + 'invalid_input' + ); + expectSignalPanelError( + () => + shortsTableToSignalRows( + { + columns: ['listing_id', 'known_at', 'net_change'], + rows: [{ listing_id: 1, known_at: knownAt1, net_change: Number.POSITIVE_INFINITY }], + }, + 'net_change' + ), + 'invalid_signal' + ); + expectSignalPanelError( + () => + shortsTableToSignalRows( + { + columns: ['listing_id', 'known_at', 'net_change'], + rows: [{ listing_id: 1, known_at: knownAt1 }], + }, + 'net_change' + ), + 'invalid_signal' + ); + }); + + it('collects multi-batch async iterables without mutating batches and rejects invalid inputs', async () => { + const b1 = makeBar(1, '2024-01-02', 100); + const b2 = makeBar(1, '2024-01-03', 101); + const b3 = makeBar(2, '2024-01-02', 50); + + const batch1: BarBatch = Object.freeze({ rows: Object.freeze([b1, b2]) }); + const batch2: BarBatch = Object.freeze({ rows: Object.freeze([b3]) }); + + async function* gen(): AsyncIterable { + yield batch1; + yield { rows: [] }; + yield batch2; + } + + const collected = await collectBars(gen()); + expect(collected).toEqual([b1, b2, b3]); + + async function* emptyGen(): AsyncIterable { + // empty + } + expect(await collectBars(emptyGen())).toEqual([]); + + await expectSignalPanelErrorAsync( + () => collectBars(null as unknown as AsyncIterable), + 'invalid_input' + ); + + async function* badBatchGen(): AsyncIterable { + yield { rows: 'not-array' } as unknown as BarBatch; + } + await expectSignalPanelErrorAsync(() => collectBars(badBatchGen()), 'invalid_bar'); + }); +});