stock-bot/apps/stock/data-pipeline/src/security-master/sample-closes.ts

519 lines
15 KiB
TypeScript

import {
BAR_SPAN_COLLECTIONS,
normalizeBarDate,
type BarSpanSource,
} from '../normalization/bar-spans';
import { compareAscii } from './exchange-pass1';
import type { FxRateByDateRecord, SampleCloseRecord } from './price-cross-check';
import type {
ReadOnlySourceSymbolCursor,
ReadOnlySourceSymbolReader,
SourceSymbolFindOptions,
} from './source-symbol-readers';
export type SampleCloseSource = BarSpanSource;
export const MAX_SAMPLE_DATES = 64;
export const DEFAULT_SAMPLE_CLOSE_ID_CHUNK_SIZE = 10_000;
export const FX_USD_CAD_SOURCE_ID = 'CAD.FOREX';
export const EOD_SAMPLE_CLOSES_PROJECTION: Readonly<Record<string, 0 | 1>> = Object.freeze({
_id: 0,
[BAR_SPAN_COLLECTIONS.eod.idField]: 1,
[BAR_SPAN_COLLECTIONS.eod.dateField]: 1,
close: 1,
});
export const QM_SAMPLE_CLOSES_PROJECTION: Readonly<Record<string, 0 | 1>> = Object.freeze({
_id: 0,
[BAR_SPAN_COLLECTIONS.qm.idField]: 1,
[BAR_SPAN_COLLECTIONS.qm.dateField]: 1,
unadjustedclose: 1,
});
export interface SampleCloseSourceIdsBySource {
readonly eod: readonly string[];
readonly qm: readonly string[];
}
export interface ReadSampleClosesOptions {
readonly sampleDates: readonly string[];
readonly sourceIdsBySource: SampleCloseSourceIdsBySource;
readonly includeFx?: boolean;
readonly batchSize?: number;
readonly idChunkSize?: number;
}
export interface SampleCloseSkipCounts {
missingId: number;
unrequestedId: number;
invalidDate: number;
unrequestedDate: number;
invalidClose: number;
}
export type SampleCloseSkipReason = keyof SampleCloseSkipCounts;
export interface SampleCloseSourceReadStats {
collection: string;
findsRun: number;
docsRead: number;
emitted: number;
skippedTotal: number;
skipped: SampleCloseSkipCounts;
}
export interface ReadSampleClosesStats {
eod: SampleCloseSourceReadStats;
qm: SampleCloseSourceReadStats;
fx: SampleCloseSourceReadStats;
}
export interface ReadSampleClosesResult {
sampleDates: string[];
closes: SampleCloseRecord[];
fxRates: FxRateByDateRecord[];
stats: ReadSampleClosesStats;
}
const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
function isSampleCloseSource(value: unknown): value is SampleCloseSource {
return value === 'eod' || value === 'qm';
}
function isPlainRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function isAsyncIterable<T>(value: unknown): value is AsyncIterable<T> {
return (
value !== null &&
(typeof value === 'object' || typeof value === 'function') &&
typeof (value as Record<symbol, unknown>)[Symbol.asyncIterator] === 'function'
);
}
function validatePositiveSafeInt(value: unknown, name: string): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
throw new RangeError(`${name} must be a positive safe integer, received ${String(value)}`);
}
return value;
}
function assertReadOnlyReader(reader: ReadOnlySourceSymbolReader): void {
if (
reader === null ||
reader === undefined ||
typeof reader !== 'object' ||
typeof reader.isReadOnly !== 'function' ||
typeof reader.find !== 'function' ||
reader.isReadOnly() !== true
) {
throw new Error(
'Sample close reader requires a read-only MongoDB reader (isReadOnly() must be true)'
);
}
}
/**
* Validates, deduplicates, and ASCII-sorts exact Gregorian `YYYY-MM-DD` sample dates.
* Rejects empty lists, malformed/padded/rollover dates, and lists exceeding `MAX_SAMPLE_DATES`.
*/
function normalizeSampleDates(sampleDates: readonly string[]): string[] {
if (!Array.isArray(sampleDates)) {
throw new RangeError('sampleDates must be a non-empty array of YYYY-MM-DD strings');
}
if (sampleDates.length === 0) {
throw new RangeError('sampleDates must not be empty');
}
const unique = new Set<string>();
for (let i = 0; i < sampleDates.length; i++) {
const raw = sampleDates[i];
if (
typeof raw !== 'string' ||
!EXACT_YMD_PATTERN.test(raw) ||
normalizeBarDate(raw) !== raw
) {
throw new RangeError(
`sampleDates[${i}] must be a valid exact YYYY-MM-DD date, received ${JSON.stringify(raw)}`
);
}
unique.add(raw);
}
if (unique.size > MAX_SAMPLE_DATES) {
throw new RangeError(
`sampleDates exceeds maximum allowed count of ${MAX_SAMPLE_DATES} (received ${unique.size})`
);
}
return Array.from(unique).sort(compareAscii);
}
/**
* Validates, deduplicates, and ASCII-sorts requested source IDs without trimming non-blank strings
* (T-49). Whitespace-only entries are dropped; `CAD.FOREX` is excluded when `excludeFx` is true.
*/
function normalizeRequestedIds(
rawIds: readonly string[],
fieldName: string,
options?: { readonly excludeFx?: boolean }
): string[] {
if (!Array.isArray(rawIds)) {
throw new TypeError(`${fieldName} must be an array of strings`);
}
const excludeFx = options?.excludeFx === true;
const unique = new Set<string>();
for (let i = 0; i < rawIds.length; i++) {
const raw = rawIds[i];
if (typeof raw !== 'string') {
throw new TypeError(`${fieldName}[${i}] must be a string, received ${typeof raw}`);
}
if (raw.trim().length === 0) {
continue;
}
if (excludeFx && raw === FX_USD_CAD_SOURCE_ID) {
continue;
}
unique.add(raw);
}
return Array.from(unique).sort(compareAscii);
}
function createEmptySkipCounts(): SampleCloseSkipCounts {
return {
missingId: 0,
unrequestedId: 0,
invalidDate: 0,
unrequestedDate: 0,
invalidClose: 0,
};
}
function createSourceStats(collection: string): SampleCloseSourceReadStats {
return {
collection,
findsRun: 0,
docsRead: 0,
emitted: 0,
skippedTotal: 0,
skipped: createEmptySkipCounts(),
};
}
function recordSkip(stats: SampleCloseSourceReadStats, reason: SampleCloseSkipReason): void {
stats.skipped[reason] += 1;
stats.skippedTotal += 1;
}
function wrapCollectionReadError(collectionName: string, error: unknown): Error {
const detail = error instanceof Error ? error.message : String(error);
const message = detail.includes(collectionName)
? detail
: `Failed reading collection "${collectionName}": ${detail}`;
return new Error(message, { cause: error });
}
async function streamSampleCloseFind(
reader: ReadOnlySourceSymbolReader,
collectionName: string,
filter: Record<string, unknown>,
findOptions: SourceSymbolFindOptions,
onDoc: (doc: unknown) => void
): Promise<void> {
assertReadOnlyReader(reader);
let closableHandle: Pick<ReadOnlySourceSymbolCursor<Record<string, unknown>>, 'close'> | null =
null;
let primaryError: unknown = undefined;
let hasPrimaryError = false;
let isInvalidCursorError = false;
try {
const rawCursor = await reader.find<Record<string, unknown>>(
collectionName,
filter,
findOptions
);
if (
rawCursor !== null &&
(typeof rawCursor === 'object' || typeof rawCursor === 'function')
) {
closableHandle = rawCursor as Pick<
ReadOnlySourceSymbolCursor<Record<string, unknown>>,
'close'
>;
}
if (Array.isArray(rawCursor) || !isAsyncIterable<Record<string, unknown>>(rawCursor)) {
isInvalidCursorError = true;
throw new TypeError(
`Reader for collection "${collectionName}" must return an incremental AsyncIterable cursor (got buffered or non-async result)`
);
}
for await (const doc of rawCursor) {
onDoc(doc);
}
} catch (error) {
primaryError = error;
hasPrimaryError = true;
} finally {
if (closableHandle !== null && typeof closableHandle.close === 'function') {
try {
await closableHandle.close();
} catch (closeError) {
if (!hasPrimaryError) {
primaryError = closeError;
hasPrimaryError = true;
}
}
}
}
if (hasPrimaryError) {
if (isInvalidCursorError) {
throw primaryError;
}
throw wrapCollectionReadError(collectionName, primaryError);
}
}
function compareSampleCloses(a: SampleCloseRecord, b: SampleCloseRecord): number {
return (
compareAscii(a.source, b.source) ||
compareAscii(a.sourceId, b.sourceId) ||
compareAscii(a.date, b.date) ||
a.close - b.close
);
}
function compareFxRates(a: FxRateByDateRecord, b: FxRateByDateRecord): number {
return compareAscii(a.date, b.date) || a.usdCad - b.usdCad;
}
/**
* Builds a plain date-first MongoDB `find` filter for Pass 4 sample-close queries:
* `{ date: { $in: [...] } }`, optionally AND-ed with `{ eodSearchCode | qmSearchCode: { $in: [...] } }`.
*
* `eodPrices` (`price-storage.ts`) enforces `YYYY-MM-DD` strings for `date`, while
* `qmPrices` (`prices.action.ts`) copies the provider's `date` field verbatim (assumed
* `YYYY-MM-DD`, with BSON `Date` stored separately in `dateTime`), so `$in` emits sorted
* `YYYY-MM-DD` strings.
*/
export function buildSampleCloseFilter(
source: SampleCloseSource,
sampleDates: readonly string[],
sourceIds?: readonly string[]
): Record<string, unknown> {
if (!isSampleCloseSource(source)) {
throw new RangeError(`Unsupported sample close source: "${String(source)}"`);
}
const normalizedDates = normalizeSampleDates(sampleDates);
const spec = BAR_SPAN_COLLECTIONS[source];
const filter: Record<string, unknown> = {
[spec.dateField]: { $in: normalizedDates },
};
if (sourceIds !== undefined) {
const normalizedIds = normalizeRequestedIds(sourceIds, 'sourceIds');
filter[spec.idField] = { $in: normalizedIds };
}
return filter;
}
/**
* Streams read-only Pass 4 sample closes from `eodPrices` (raw `close`), `qmPrices`
* (raw `unadjustedclose`), and USD/CAD FX rates from `eodPrices` (`CAD.FOREX`) using
* date-first `{ date: { $in: sampleDates } }` filters over `ReadOnlySourceSymbolReader`.
*/
export async function readSampleCloses(
reader: ReadOnlySourceSymbolReader,
options: ReadSampleClosesOptions
): Promise<ReadSampleClosesResult> {
assertReadOnlyReader(reader);
if (options === null || typeof options !== 'object') {
throw new TypeError('options must be an object');
}
if (options.sourceIdsBySource === null || typeof options.sourceIdsBySource !== 'object') {
throw new TypeError('options.sourceIdsBySource must be an object');
}
const sampleDates = normalizeSampleDates(options.sampleDates);
const sampleDateSet = new Set<string>(sampleDates);
const eodIds = normalizeRequestedIds(options.sourceIdsBySource.eod, 'sourceIdsBySource.eod', {
excludeFx: true,
});
const qmIds = normalizeRequestedIds(options.sourceIdsBySource.qm, 'sourceIdsBySource.qm');
const includeFx = options.includeFx ?? true;
if (typeof includeFx !== 'boolean') {
throw new TypeError('options.includeFx must be a boolean');
}
const batchSize =
options.batchSize !== undefined
? validatePositiveSafeInt(options.batchSize, 'options.batchSize')
: undefined;
const idChunkSize =
options.idChunkSize !== undefined
? validatePositiveSafeInt(options.idChunkSize, 'options.idChunkSize')
: DEFAULT_SAMPLE_CLOSE_ID_CHUNK_SIZE;
const eodFindOptions: SourceSymbolFindOptions =
batchSize !== undefined
? { projection: { ...EOD_SAMPLE_CLOSES_PROJECTION }, batchSize }
: { projection: { ...EOD_SAMPLE_CLOSES_PROJECTION } };
const qmFindOptions: SourceSymbolFindOptions =
batchSize !== undefined
? { projection: { ...QM_SAMPLE_CLOSES_PROJECTION }, batchSize }
: { projection: { ...QM_SAMPLE_CLOSES_PROJECTION } };
const stats: ReadSampleClosesStats = {
eod: createSourceStats(BAR_SPAN_COLLECTIONS.eod.collection),
qm: createSourceStats(BAR_SPAN_COLLECTIONS.qm.collection),
fx: createSourceStats(BAR_SPAN_COLLECTIONS.eod.collection),
};
const closes: SampleCloseRecord[] = [];
const fxRates: FxRateByDateRecord[] = [];
const readEquitySource = async (
source: SampleCloseSource,
ids: readonly string[],
findOptions: SourceSymbolFindOptions
): Promise<void> => {
if (ids.length === 0) {
return;
}
const spec = BAR_SPAN_COLLECTIONS[source];
const closeField = source === 'eod' ? 'close' : 'unadjustedclose';
const sourceStats = stats[source];
for (let offset = 0; offset < ids.length; offset += idChunkSize) {
const chunkIds = ids.slice(offset, offset + idChunkSize);
const chunkIdSet = new Set<string>(chunkIds);
const filter = buildSampleCloseFilter(source, sampleDates, chunkIds);
sourceStats.findsRun += 1;
await streamSampleCloseFind(reader, spec.collection, filter, findOptions, doc => {
sourceStats.docsRead += 1;
if (!isPlainRecord(doc)) {
recordSkip(sourceStats, 'missingId');
return;
}
const rawId = doc[spec.idField];
if (typeof rawId !== 'string' || rawId.trim().length === 0) {
recordSkip(sourceStats, 'missingId');
return;
}
if (!chunkIdSet.has(rawId)) {
recordSkip(sourceStats, 'unrequestedId');
return;
}
const rawDate = doc[spec.dateField];
const normalizedDate =
typeof rawDate === 'string' && sampleDateSet.has(rawDate)
? rawDate
: normalizeBarDate(rawDate);
if (normalizedDate === null) {
recordSkip(sourceStats, 'invalidDate');
return;
}
if (!sampleDateSet.has(normalizedDate)) {
recordSkip(sourceStats, 'unrequestedDate');
return;
}
const rawClose = doc[closeField];
if (typeof rawClose !== 'number' || !Number.isFinite(rawClose) || rawClose <= 0) {
recordSkip(sourceStats, 'invalidClose');
return;
}
closes.push({
source,
sourceId: rawId,
date: normalizedDate,
close: rawClose,
});
sourceStats.emitted += 1;
});
}
};
await readEquitySource('eod', eodIds, eodFindOptions);
await readEquitySource('qm', qmIds, qmFindOptions);
if (includeFx) {
const eodSpec = BAR_SPAN_COLLECTIONS.eod;
const fxFilter = buildSampleCloseFilter('eod', sampleDates, [FX_USD_CAD_SOURCE_ID]);
stats.fx.findsRun += 1;
await streamSampleCloseFind(reader, eodSpec.collection, fxFilter, eodFindOptions, doc => {
stats.fx.docsRead += 1;
if (!isPlainRecord(doc)) {
recordSkip(stats.fx, 'missingId');
return;
}
const rawId = doc[eodSpec.idField];
if (typeof rawId !== 'string' || rawId.trim().length === 0) {
recordSkip(stats.fx, 'missingId');
return;
}
if (rawId !== FX_USD_CAD_SOURCE_ID) {
recordSkip(stats.fx, 'unrequestedId');
return;
}
const rawDate = doc[eodSpec.dateField];
const normalizedDate =
typeof rawDate === 'string' && sampleDateSet.has(rawDate)
? rawDate
: normalizeBarDate(rawDate);
if (normalizedDate === null) {
recordSkip(stats.fx, 'invalidDate');
return;
}
if (!sampleDateSet.has(normalizedDate)) {
recordSkip(stats.fx, 'unrequestedDate');
return;
}
const rawClose = doc.close;
if (typeof rawClose !== 'number' || !Number.isFinite(rawClose) || rawClose <= 0) {
recordSkip(stats.fx, 'invalidClose');
return;
}
fxRates.push({
date: normalizedDate,
usdCad: rawClose,
});
stats.fx.emitted += 1;
});
}
closes.sort(compareSampleCloses);
fxRates.sort(compareFxRates);
return {
sampleDates,
closes,
fxRates,
stats,
};
}