diff --git a/apps/stock/data-pipeline/src/security-master/delisting-chains.ts b/apps/stock/data-pipeline/src/security-master/delisting-chains.ts new file mode 100644 index 00000000..2a15b300 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/delisting-chains.ts @@ -0,0 +1,739 @@ +import { compareAscii } from './exchange-pass1'; +import type { ListingNaturalKey, StageBListingCandidate } from './listing-stage-b'; + +export const DEFAULT_ACTIVE_GRACE_DAYS = 10; +export const DEFAULT_MAX_TRANSFER_GAP_DAYS = 30; +export const DEFAULT_OVERLAP_TOLERANCE_DAYS = 5; + +export const DEFAULT_OTC_MICS: ReadonlySet = new Set(['OTCM']); + +export const DELIST_REASONS = [ + 'active', + 'moved_to_otc', + 'bankruptcy_cancelled', + 'unknown_involuntary', +] as const; + +export type Pass6DelistReason = (typeof DELIST_REASONS)[number]; + +export const CONTINUITY_KIND_OTC_DELIST_TRANSFER = 'otc_delist_transfer' as const; + +export type DelistingContinuityKind = typeof CONTINUITY_KIND_OTC_DELIST_TRANSFER; + +export const SHUMWAY_PRIMARY_TERMINAL_RETURN = -0.3; +export const BANKRUPTCY_CANCELLED_TERMINAL_RETURN = -1.0; + +export interface DelistingChainInput { + readonly listings: readonly StageBListingCandidate[]; + readonly otcMics: ReadonlySet; +} + +export interface LinkDelistingChainsOptions { + readonly asOfDate: string; + readonly activeGraceDays?: number; + readonly maxTransferGapDays?: number; + readonly overlapToleranceDays?: number; +} + +export interface DelistingContinuityCandidate { + fromListingKey: ListingNaturalKey; + toListingKey: ListingNaturalKey; + effectiveDate: string; + kind: DelistingContinuityKind; +} + +export interface ListingDelistOutcome { + listingKey: ListingNaturalKey; + delistReason: Pass6DelistReason; + terminalReturn: number | null; +} + +export type DelistingChainConflictKind = + | 'ambiguous_otc_continuation' + | 'invalid_listing_dates' + | 'duplicate_listing_key' + | 'missing_otc_listed_from'; + +export interface DelistingChainConflictDetail { + primaryIsin: string; + currency: string; + fromListingKeys: ListingNaturalKey[]; + toListingKeys: ListingNaturalKey[]; + candidateListingKeys: ListingNaturalKey[]; + listedFrom: string | null; + listedTo: string | null; + reason: string; +} + +export interface DelistingChainConflictRecord { + conflictKind: DelistingChainConflictKind; + detail: DelistingChainConflictDetail; +} + +export interface DelistingChainOutcomeStats { + active: number; + moved_to_otc: number; + bankruptcy_cancelled: number; + unknown_involuntary: number; +} + +export interface DelistingChainStats { + totalInputListings: number; + processedListings: number; + skippedInvalidDates: number; + skippedDuplicateKeys: number; + continuitiesCreated: number; + conflictsDetected: number; + byOutcome: DelistingChainOutcomeStats; +} + +export interface DelistingChainResult { + continuities: DelistingContinuityCandidate[]; + listingOutcomes: ListingDelistOutcome[]; + conflicts: DelistingChainConflictRecord[]; + stats: DelistingChainStats; +} + +interface NormalizedListingRow { + readonly index: number; + readonly key: ListingNaturalKey; + readonly listedFrom: string | null; + readonly listedTo: string | null; + readonly listedFromDay: number | null; + readonly listedToDay: number | null; + readonly isOtc: boolean; +} + +interface EndedPrimaryRow extends NormalizedListingRow { + readonly listedTo: string; + readonly listedToDay: number; +} + +interface EligibleOtcRow extends NormalizedListingRow { + readonly listedFrom: string; + readonly listedFromDay: number; +} + +interface InstrumentCurrencyGroup { + readonly primaryIsin: string; + readonly currency: string; + readonly endedPrimaries: EndedPrimaryRow[]; + readonly eligibleOtcs: EligibleOtcRow[]; + readonly missingFromOtcs: NormalizedListingRow[]; +} + +const ISO_MIC_PATTERN = /^[A-Z0-9]{4}$/; +const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; +const OTC_BANKRUPTCY_Q_TICKER_PATTERN = /^[A-Z]{4}Q$/; + +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +/** + * Pure UTC calendar date parser returning integer days since 1970-01-01 using + * Howard Hinnant's `days_from_civil` algorithm with zero `Date` allocations. + * Rejects timestamps, padded strings, and invalid calendar dates (e.g. 2023-02-29). + */ +function parseExactIsoDateToUtcDay(value: unknown): number | null { + if (typeof value !== 'string' || !EXACT_YMD_PATTERN.test(value)) { + return null; + } + const year = + (value.charCodeAt(0) - 48) * 1000 + + (value.charCodeAt(1) - 48) * 100 + + (value.charCodeAt(2) - 48) * 10 + + (value.charCodeAt(3) - 48); + const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48); + const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48); + + if (month < 1 || month > 12) { + return null; + } + const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0); + if (day < 1 || day > maxDay) { + return null; + } + + const adjustedYear = month <= 2 ? year - 1 : year; + const era = Math.floor(adjustedYear / 400); + const yearOfEra = adjustedYear - era * 400; + const dayOfYear = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1; + const dayOfEra = + yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear; + return era * 146097 + dayOfEra - 719468; +} + +function cloneListingKey(key: ListingNaturalKey): ListingNaturalKey { + return { + primaryIsin: key.primaryIsin, + mic: key.mic, + tickerRoot: key.tickerRoot, + classSuffix: key.classSuffix, + currency: key.currency, + }; +} + +function makeListingNaturalKeyId(key: ListingNaturalKey): string { + return `${key.primaryIsin}\u0000${key.mic}\u0000${key.tickerRoot}\u0000${key.classSuffix}\u0000${key.currency}`; +} + +function makeGroupKey(primaryIsin: string, currency: string): string { + return `${primaryIsin}\u0000${currency}`; +} + +function compareListingNaturalKey(a: ListingNaturalKey, b: ListingNaturalKey): number { + return ( + compareAscii(a.primaryIsin, b.primaryIsin) || + compareAscii(a.mic, b.mic) || + compareAscii(a.tickerRoot, b.tickerRoot) || + compareAscii(a.classSuffix, b.classSuffix) || + compareAscii(a.currency, b.currency) + ); +} + +function compareListingKeyArrays( + a: readonly ListingNaturalKey[], + b: readonly ListingNaturalKey[] +): number { + const len = a.length < b.length ? a.length : b.length; + for (let i = 0; i < len; i++) { + const ak = a[i]; + const bk = b[i]; + if (ak !== undefined && bk !== undefined) { + const cmp = compareListingNaturalKey(ak, bk); + if (cmp !== 0) { + return cmp; + } + } + } + return a.length - b.length; +} + +function compareContinuities( + a: DelistingContinuityCandidate, + b: DelistingContinuityCandidate +): number { + return ( + compareListingNaturalKey(a.fromListingKey, b.fromListingKey) || + compareAscii(a.effectiveDate, b.effectiveDate) || + compareListingNaturalKey(a.toListingKey, b.toListingKey) || + compareAscii(a.kind, b.kind) + ); +} + +function compareOutcomes(a: ListingDelistOutcome, b: ListingDelistOutcome): number { + return ( + compareListingNaturalKey(a.listingKey, b.listingKey) || + compareAscii(a.delistReason, b.delistReason) + ); +} + +function compareConflicts( + a: DelistingChainConflictRecord, + b: DelistingChainConflictRecord +): number { + return ( + compareAscii(a.conflictKind, b.conflictKind) || + compareAscii(a.detail.primaryIsin, b.detail.primaryIsin) || + compareAscii(a.detail.currency, b.detail.currency) || + compareListingKeyArrays(a.detail.fromListingKeys, b.detail.fromListingKeys) || + compareListingKeyArrays(a.detail.toListingKeys, b.detail.toListingKeys) || + compareListingKeyArrays(a.detail.candidateListingKeys, b.detail.candidateListingKeys) || + compareAscii(a.detail.listedFrom ?? '', b.detail.listedFrom ?? '') || + compareAscii(a.detail.listedTo ?? '', b.detail.listedTo ?? '') || + compareAscii(a.detail.reason, b.detail.reason) + ); +} + +function validateNonNegativeSafeIntegerOption(value: unknown, optionName: string): number { + if (typeof value !== 'number') { + throw new TypeError(`options.${optionName} must be a number, received ${typeof value}`); + } + if (!Number.isSafeInteger(value) || value < 0) { + throw new RangeError( + `options.${optionName} must be a non-negative safe integer, received ${String(value)}` + ); + } + return value; +} + +function normalizeAndValidateOtcMics(otcMics: unknown): Set { + if (!(otcMics instanceof Set)) { + throw new TypeError('input.otcMics must be a ReadonlySet'); + } + const normalized = new Set(); + for (const rawMic of otcMics) { + if (typeof rawMic !== 'string') { + throw new TypeError(`input.otcMics entries must be strings, received ${typeof rawMic}`); + } + const mic = rawMic.trim().toUpperCase(); + if (!ISO_MIC_PATTERN.test(mic)) { + throw new RangeError( + `input.otcMics entry "${rawMic}" is not a valid 4-character ISO 10383 MIC` + ); + } + normalized.add(mic); + } + return normalized; +} + +function normalizeKeyFromListing(listing: StageBListingCandidate): ListingNaturalKey { + return { + primaryIsin: typeof listing.primaryIsin === 'string' ? listing.primaryIsin.trim().toUpperCase() : '', + mic: typeof listing.mic === 'string' ? listing.mic.trim().toUpperCase() : '', + tickerRoot: typeof listing.tickerRoot === 'string' ? listing.tickerRoot.trim() : '', + classSuffix: typeof listing.classSuffix === 'string' ? listing.classSuffix.trim() : '', + currency: typeof listing.currency === 'string' ? listing.currency.trim().toUpperCase() : '', + }; +} + +function lowerBoundByListedFromDay(otcs: readonly EligibleOtcRow[], targetDay: number): number { + let lo = 0; + let hi = otcs.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + const midRow = otcs[mid]; + if (midRow !== undefined && midRow.listedFromDay < targetDay) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; +} + +/** + * Pass 6 pure in-memory OTC delisting chain linker. + * + * Links ended primary-venue listings to same-ISIN, same-currency OTC continuations + * (e.g. `SIVB` on `XNAS` -> `SIVBQ` on `OTCM`), classifies each listing's `delistReason` + * and Shumway/bankruptcy `terminalReturn`, and quarantines ambiguous candidates as typed + * conflicts without guessing. + */ +export function linkDelistingChains( + input: DelistingChainInput, + options: LinkDelistingChainsOptions +): DelistingChainResult { + if (input === null || input === undefined || typeof input !== 'object') { + throw new TypeError('Delisting chain input must be an object'); + } + if (!Array.isArray(input.listings)) { + throw new TypeError('input.listings must be an array'); + } + const normalizedOtcMics = normalizeAndValidateOtcMics(input.otcMics); + + if (options === null || options === undefined || typeof options !== 'object') { + throw new TypeError('options must be an object'); + } + if (typeof options.asOfDate !== 'string') { + throw new TypeError('options.asOfDate must be a YYYY-MM-DD string'); + } + const asOfDay = parseExactIsoDateToUtcDay(options.asOfDate); + if (asOfDay === null) { + throw new RangeError( + `options.asOfDate must be a valid YYYY-MM-DD calendar date, received "${options.asOfDate}"` + ); + } + + const activeGraceDays = validateNonNegativeSafeIntegerOption( + options.activeGraceDays ?? DEFAULT_ACTIVE_GRACE_DAYS, + 'activeGraceDays' + ); + const maxTransferGapDays = validateNonNegativeSafeIntegerOption( + options.maxTransferGapDays ?? DEFAULT_MAX_TRANSFER_GAP_DAYS, + 'maxTransferGapDays' + ); + const overlapToleranceDays = validateNonNegativeSafeIntegerOption( + options.overlapToleranceDays ?? DEFAULT_OVERLAP_TOLERANCE_DAYS, + 'overlapToleranceDays' + ); + + const activeCutoffDay = asOfDay - activeGraceDays; + const totalInputListings = input.listings.length; + + // Pass 1a: validate container slots and count natural-key occurrences so duplicates are quarantined. + const normalizedKeys = new Array(totalInputListings); + const keyIds = new Array(totalInputListings); + const keyCounts = new Map(); + + for (let i = 0; i < totalInputListings; i++) { + if (!(i in input.listings)) { + throw new TypeError(`Invalid sparse slot at input.listings[${i}]: expected a listing object`); + } + const row = input.listings[i]; + if (row === undefined || row === null || typeof row !== 'object') { + throw new TypeError(`Invalid listing entry at input.listings[${i}]: expected an object`); + } + const key = normalizeKeyFromListing(row); + const keyId = makeListingNaturalKeyId(key); + normalizedKeys[i] = key; + keyIds[i] = keyId; + keyCounts.set(keyId, (keyCounts.get(keyId) ?? 0) + 1); + } + + const conflicts: DelistingChainConflictRecord[] = []; + const validRows: NormalizedListingRow[] = []; + const groups = new Map(); + const reportedDuplicateKeyIds = new Set(); + + let skippedDuplicateKeys = 0; + let skippedInvalidDates = 0; + + // Pass 1b: filter duplicates and invalid date spans, and group valid unique rows by (primaryIsin, currency). + for (let i = 0; i < totalInputListings; i++) { + const row = input.listings[i]; + const key = normalizedKeys[i]; + const keyId = keyIds[i]; + if (row === undefined || key === undefined || keyId === undefined) { + continue; + } + + const occurrences = keyCounts.get(keyId) ?? 0; + if (occurrences > 1) { + skippedDuplicateKeys += 1; + if (!reportedDuplicateKeyIds.has(keyId)) { + reportedDuplicateKeyIds.add(keyId); + conflicts.push({ + conflictKind: 'duplicate_listing_key', + detail: { + primaryIsin: key.primaryIsin, + currency: key.currency, + fromListingKeys: [], + toListingKeys: [], + candidateListingKeys: [cloneListingKey(key)], + listedFrom: null, + listedTo: null, + reason: `Duplicate listing natural key appeared ${occurrences} times`, + }, + }); + } + continue; + } + + const rawListedFrom = row.listedFrom; + const rawListedTo = row.listedTo; + + let listedFromDay: number | null = null; + let listedToDay: number | null = null; + let dateErrorReason: string | null = null; + + if (rawListedFrom !== null) { + listedFromDay = parseExactIsoDateToUtcDay(rawListedFrom); + if (listedFromDay === null) { + dateErrorReason = `Invalid listedFrom date "${String(rawListedFrom)}"`; + } + } + + if (dateErrorReason === null && rawListedTo !== null) { + listedToDay = parseExactIsoDateToUtcDay(rawListedTo); + if (listedToDay === null) { + dateErrorReason = `Invalid listedTo date "${String(rawListedTo)}"`; + } + } + + if ( + dateErrorReason === null && + listedFromDay !== null && + listedToDay !== null && + listedFromDay > listedToDay + ) { + dateErrorReason = `Inverted date range: listedFrom (${String(rawListedFrom)}) is after listedTo (${String(rawListedTo)})`; + } + + if (dateErrorReason !== null) { + skippedInvalidDates += 1; + conflicts.push({ + conflictKind: 'invalid_listing_dates', + detail: { + primaryIsin: key.primaryIsin, + currency: key.currency, + fromListingKeys: [], + toListingKeys: [], + candidateListingKeys: [cloneListingKey(key)], + listedFrom: typeof rawListedFrom === 'string' ? rawListedFrom : null, + listedTo: typeof rawListedTo === 'string' ? rawListedTo : null, + reason: dateErrorReason, + }, + }); + continue; + } + + const isOtc = normalizedOtcMics.has(key.mic); + const normalizedRow: NormalizedListingRow = { + index: validRows.length, + key, + listedFrom: rawListedFrom, + listedTo: rawListedTo, + listedFromDay, + listedToDay, + isOtc, + }; + validRows.push(normalizedRow); + + const isEnded = listedToDay !== null && listedToDay < activeCutoffDay; + const isEndedPrimary = !isOtc && isEnded; + const isEligibleOtc = isOtc && listedFromDay !== null && listedFromDay <= asOfDay; + const isMissingFromOtc = isOtc && listedFromDay === null; + + if (isEndedPrimary || isEligibleOtc || isMissingFromOtc) { + const groupKey = makeGroupKey(key.primaryIsin, key.currency); + let group = groups.get(groupKey); + if (group === undefined) { + group = { + primaryIsin: key.primaryIsin, + currency: key.currency, + endedPrimaries: [], + eligibleOtcs: [], + missingFromOtcs: [], + }; + groups.set(groupKey, group); + } + + if (isEndedPrimary && rawListedTo !== null && listedToDay !== null) { + group.endedPrimaries.push(normalizedRow as EndedPrimaryRow); + } else if (isEligibleOtc && rawListedFrom !== null && listedFromDay !== null) { + group.eligibleOtcs.push(normalizedRow as EligibleOtcRow); + } else if (isMissingFromOtc) { + group.missingFromOtcs.push(normalizedRow); + } + } + } + + // Pass 2: match ended primary listings to eligible OTC continuations within each (primaryIsin, currency) group. + const continuities: DelistingContinuityCandidate[] = []; + const linkedPrimaryIndices = new Set(); + + for (const group of groups.values()) { + if (group.endedPrimaries.length === 0) { + continue; + } + + if (group.missingFromOtcs.length > 0) { + const sortedPrimaryKeys = group.endedPrimaries + .map(p => p.key) + .sort(compareListingNaturalKey); + for (const otc of group.missingFromOtcs) { + const allKeys = [...sortedPrimaryKeys, otc.key].sort(compareListingNaturalKey); + conflicts.push({ + conflictKind: 'missing_otc_listed_from', + detail: { + primaryIsin: group.primaryIsin, + currency: group.currency, + fromListingKeys: sortedPrimaryKeys.map(cloneListingKey), + toListingKeys: [cloneListingKey(otc.key)], + candidateListingKeys: allKeys.map(cloneListingKey), + listedFrom: null, + listedTo: otc.listedTo, + reason: 'OTC listing has null listedFrom; cannot establish transfer window or effectiveDate', + }, + }); + } + } + + if (group.eligibleOtcs.length === 0) { + continue; + } + + const primaries = group.endedPrimaries; + const otcs = group.eligibleOtcs; + otcs.sort( + (a, b) => a.listedFromDay - b.listedFromDay || compareListingNaturalKey(a.key, b.key) + ); + + const primaryAdj: number[][] = Array.from({ length: primaries.length }, () => []); + const otcAdj: number[][] = Array.from({ length: otcs.length }, () => []); + + for (let pIdx = 0; pIdx < primaries.length; pIdx++) { + const primary = primaries[pIdx]; + if (primary === undefined) { + continue; + } + const minDay = primary.listedToDay - overlapToleranceDays; + const maxDay = primary.listedToDay + maxTransferGapDays; + let oIdx = lowerBoundByListedFromDay(otcs, minDay); + while (oIdx < otcs.length) { + const otc = otcs[oIdx]; + if (otc === undefined || otc.listedFromDay > maxDay) { + break; + } + // Reject OTC stubs that had already ended before the primary listing ended. + if (otc.listedToDay === null || otc.listedToDay >= primary.listedToDay) { + primaryAdj[pIdx]?.push(oIdx); + otcAdj[oIdx]?.push(pIdx); + } + oIdx += 1; + } + } + + // Partition bipartite candidate edges into connected components. + const visitedPrimary = new Uint8Array(primaries.length); + const visitedOtc = new Uint8Array(otcs.length); + + for (let startP = 0; startP < primaries.length; startP++) { + const startNeighbors = primaryAdj[startP]; + if (visitedPrimary[startP] === 1 || startNeighbors === undefined || startNeighbors.length === 0) { + continue; + } + + const compPrimaries: number[] = []; + const compOtcs: number[] = []; + const primaryQueue: number[] = [startP]; + const otcQueue: number[] = []; + visitedPrimary[startP] = 1; + + while (primaryQueue.length > 0 || otcQueue.length > 0) { + while (primaryQueue.length > 0) { + const pIdx = primaryQueue.pop(); + if (pIdx === undefined) { + continue; + } + compPrimaries.push(pIdx); + const neighbors = primaryAdj[pIdx]; + if (neighbors !== undefined) { + for (let k = 0; k < neighbors.length; k++) { + const oIdx = neighbors[k]; + if (oIdx !== undefined && visitedOtc[oIdx] === 0) { + visitedOtc[oIdx] = 1; + otcQueue.push(oIdx); + } + } + } + } + while (otcQueue.length > 0) { + const oIdx = otcQueue.pop(); + if (oIdx === undefined) { + continue; + } + compOtcs.push(oIdx); + const neighbors = otcAdj[oIdx]; + if (neighbors !== undefined) { + for (let k = 0; k < neighbors.length; k++) { + const pIdx = neighbors[k]; + if (pIdx !== undefined && visitedPrimary[pIdx] === 0) { + visitedPrimary[pIdx] = 1; + primaryQueue.push(pIdx); + } + } + } + } + } + + if (compPrimaries.length === 1 && compOtcs.length === 1) { + const pIdx = compPrimaries[0]; + const oIdx = compOtcs[0]; + const primary = pIdx !== undefined ? primaries[pIdx] : undefined; + const otc = oIdx !== undefined ? otcs[oIdx] : undefined; + if (primary !== undefined && otc !== undefined) { + linkedPrimaryIndices.add(primary.index); + // effectiveDate uses the OTC listing's first observed date (listedFrom) so + // downstream backtests and curation never back-date OTC availability before + // OTC trading/quoting actually began. + continuities.push({ + fromListingKey: cloneListingKey(primary.key), + toListingKey: cloneListingKey(otc.key), + effectiveDate: otc.listedFrom, + kind: CONTINUITY_KIND_OTC_DELIST_TRANSFER, + }); + } + } else { + const fromKeys: ListingNaturalKey[] = []; + for (const idx of compPrimaries) { + const p = primaries[idx]; + if (p !== undefined) { + fromKeys.push(p.key); + } + } + fromKeys.sort(compareListingNaturalKey); + + const toKeys: ListingNaturalKey[] = []; + for (const idx of compOtcs) { + const o = otcs[idx]; + if (o !== undefined) { + toKeys.push(o.key); + } + } + toKeys.sort(compareListingNaturalKey); + + const allKeys = [...fromKeys, ...toKeys].sort(compareListingNaturalKey); + + conflicts.push({ + conflictKind: 'ambiguous_otc_continuation', + detail: { + primaryIsin: group.primaryIsin, + currency: group.currency, + fromListingKeys: fromKeys.map(cloneListingKey), + toListingKeys: toKeys.map(cloneListingKey), + candidateListingKeys: allKeys.map(cloneListingKey), + listedFrom: null, + listedTo: null, + reason: `Ambiguous OTC delisting continuation component (${compPrimaries.length} primary, ${compOtcs.length} OTC)`, + }, + }); + } + } + } + + // Pass 3: classify every valid unique listing into its delistReason and terminalReturn. + const byOutcome: DelistingChainOutcomeStats = { + active: 0, + moved_to_otc: 0, + bankruptcy_cancelled: 0, + unknown_involuntary: 0, + }; + const listingOutcomes: ListingDelistOutcome[] = []; + + for (let i = 0; i < validRows.length; i++) { + const row = validRows[i]; + if (row === undefined) { + continue; + } + let delistReason: Pass6DelistReason; + let terminalReturn: number | null; + + if (linkedPrimaryIndices.has(row.index)) { + delistReason = 'moved_to_otc'; + terminalReturn = null; + } else if (row.listedToDay === null || row.listedToDay >= activeCutoffDay) { + delistReason = 'active'; + terminalReturn = null; + } else if (!row.isOtc) { + delistReason = 'unknown_involuntary'; + terminalReturn = SHUMWAY_PRIMARY_TERMINAL_RETURN; + } else if (OTC_BANKRUPTCY_Q_TICKER_PATTERN.test(row.key.tickerRoot.toUpperCase())) { + delistReason = 'bankruptcy_cancelled'; + terminalReturn = BANKRUPTCY_CANCELLED_TERMINAL_RETURN; + } else { + delistReason = 'unknown_involuntary'; + terminalReturn = SHUMWAY_PRIMARY_TERMINAL_RETURN; + } + + byOutcome[delistReason] += 1; + listingOutcomes.push({ + listingKey: cloneListingKey(row.key), + delistReason, + terminalReturn, + }); + } + + continuities.sort(compareContinuities); + listingOutcomes.sort(compareOutcomes); + conflicts.sort(compareConflicts); + + return { + continuities, + listingOutcomes, + conflicts, + stats: { + totalInputListings, + processedListings: validRows.length, + skippedInvalidDates, + skippedDuplicateKeys, + continuitiesCreated: continuities.length, + conflictsDetected: conflicts.length, + byOutcome, + }, + }; +} diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 116056b2..5d369504 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -1,3 +1,27 @@ +export { + BANKRUPTCY_CANCELLED_TERMINAL_RETURN, + CONTINUITY_KIND_OTC_DELIST_TRANSFER, + DEFAULT_ACTIVE_GRACE_DAYS, + DEFAULT_MAX_TRANSFER_GAP_DAYS, + DEFAULT_OTC_MICS, + DEFAULT_OVERLAP_TOLERANCE_DAYS, + DELIST_REASONS, + linkDelistingChains, + SHUMWAY_PRIMARY_TERMINAL_RETURN, + type DelistingChainConflictDetail, + type DelistingChainConflictKind, + type DelistingChainConflictRecord, + type DelistingChainInput, + type DelistingChainOutcomeStats, + type DelistingChainResult, + type DelistingChainStats, + type DelistingContinuityCandidate, + type DelistingContinuityKind, + type LinkDelistingChainsOptions, + type ListingDelistOutcome, + type Pass6DelistReason, +} from './delisting-chains'; + export { classifySourceExchanges, compareAscii, diff --git a/test/unit/security-master-delisting-chains.test.ts b/test/unit/security-master-delisting-chains.test.ts new file mode 100644 index 00000000..4c7f0a05 --- /dev/null +++ b/test/unit/security-master-delisting-chains.test.ts @@ -0,0 +1,1060 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, test } from 'bun:test'; +import { + BANKRUPTCY_CANCELLED_TERMINAL_RETURN, + CONTINUITY_KIND_OTC_DELIST_TRANSFER, + DEFAULT_ACTIVE_GRACE_DAYS, + DEFAULT_MAX_TRANSFER_GAP_DAYS, + DEFAULT_OTC_MICS, + DEFAULT_OVERLAP_TOLERANCE_DAYS, + DELIST_REASONS, + linkDelistingChains, + SHUMWAY_PRIMARY_TERMINAL_RETURN, + type DelistingChainResult, + type ListingNaturalKey, + type StageBListingCandidate, +} from '../../apps/stock/data-pipeline/src/security-master'; + +const delistingChainsSourcePath = fileURLToPath( + new URL( + '../../apps/stock/data-pipeline/src/security-master/delisting-chains.ts', + import.meta.url + ) +); + +const ALLOWED_DELIST_REASONS = new Set(DELIST_REASONS); + +function makeListing( + overrides: Partial & + Pick +): StageBListingCandidate { + return { + primaryIsin: overrides.primaryIsin, + mic: overrides.mic, + tickerRoot: overrides.tickerRoot, + classSuffix: overrides.classSuffix ?? '', + currency: overrides.currency ?? 'USD', + ibConid: overrides.ibConid ?? null, + ibPrimaryExchange: overrides.ibPrimaryExchange ?? null, + listedFrom: overrides.listedFrom === undefined ? '2015-01-02' : overrides.listedFrom, + listedTo: overrides.listedTo === undefined ? null : overrides.listedTo, + }; +} + +function makeRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function shuffleWithSeed(items: readonly T[], seed: number): T[] { + const copy = [...items]; + const rng = makeRng(seed); + for (let i = copy.length - 1; i > 0; i--) { + const j = Math.floor(rng() * (i + 1)); + const tmp = copy[i]; + const swap = copy[j]; + if (tmp !== undefined && swap !== undefined) { + copy[i] = swap; + copy[j] = tmp; + } + } + return copy; +} + +function makeContinuityPk(key: ListingNaturalKey, effectiveDate: string): string { + return `${key.primaryIsin}\u0000${key.mic}\u0000${key.tickerRoot}\u0000${key.classSuffix}\u0000${key.currency}\u0000${effectiveDate}`; +} + +function assertReconciliationAndContracts( + result: DelistingChainResult, + expectedInputCount: number +): void { + expect(result.stats.totalInputListings).toBe(expectedInputCount); + expect(result.stats.processedListings).toBe(result.listingOutcomes.length); + expect( + result.stats.processedListings + + result.stats.skippedInvalidDates + + result.stats.skippedDuplicateKeys + ).toBe(result.stats.totalInputListings); + expect(result.stats.continuitiesCreated).toBe(result.continuities.length); + expect(result.stats.conflictsDetected).toBe(result.conflicts.length); + + const counted = { + active: 0, + moved_to_otc: 0, + bankruptcy_cancelled: 0, + unknown_involuntary: 0, + }; + for (const outcome of result.listingOutcomes) { + expect(ALLOWED_DELIST_REASONS.has(outcome.delistReason)).toBe(true); + expect(outcome.delistReason as string).not.toBe('merger_cash'); + counted[outcome.delistReason] += 1; + if (outcome.delistReason === 'active' || outcome.delistReason === 'moved_to_otc') { + expect(outcome.terminalReturn).toBeNull(); + } else if (outcome.delistReason === 'bankruptcy_cancelled') { + expect(outcome.terminalReturn).toBe(BANKRUPTCY_CANCELLED_TERMINAL_RETURN); + } else { + expect(outcome.terminalReturn).toBe(SHUMWAY_PRIMARY_TERMINAL_RETURN); + } + } + expect(result.stats.byOutcome).toEqual(counted); + expect( + counted.active + + counted.moved_to_otc + + counted.bankruptcy_cancelled + + counted.unknown_involuntary + ).toBe(result.stats.processedListings); + + // Enforce corporate_action_continuity PK uniqueness on (fromListingKey, effectiveDate) and kind enum. + const seenContinuityPks = new Set(); + for (const c of result.continuities) { + expect(c.kind).toBe(CONTINUITY_KIND_OTC_DELIST_TRANSFER); + const pk = makeContinuityPk(c.fromListingKey, c.effectiveDate); + expect(seenContinuityPks.has(pk)).toBe(false); + seenContinuityPks.add(pk); + } +} + +describe('security master Pass 6 OTC delisting chain linker', () => { + test('is exported from security-master barrel and performs zero I/O imports', () => { + expect(typeof linkDelistingChains).toBe('function'); + expect(DEFAULT_ACTIVE_GRACE_DAYS).toBe(10); + expect(DEFAULT_MAX_TRANSFER_GAP_DAYS).toBe(30); + expect(DEFAULT_OVERLAP_TOLERANCE_DAYS).toBe(5); + expect(DEFAULT_OTC_MICS.has('OTCM')).toBe(true); + expect(DELIST_REASONS).toEqual([ + 'active', + 'moved_to_otc', + 'bankruptcy_cancelled', + 'unknown_involuntary', + ]); + expect(CONTINUITY_KIND_OTC_DELIST_TRANSFER).toBe('otc_delist_transfer'); + expect(SHUMWAY_PRIMARY_TERMINAL_RETURN).toBe(-0.3); + expect(BANKRUPTCY_CANCELLED_TERMINAL_RETURN).toBe(-1.0); + + const sourceText = readFileSync(delistingChainsSourcePath, 'utf8'); + const forbiddenImports = [ + '@stock-bot/mongodb', + '@stock-bot/postgres', + 'node:fs', + 'node:http', + 'node:https', + 'node:net', + 'bun:sqlite', + "'fs'", + '"fs"', + "'http'", + '"http"', + "'https'", + '"https"', + "'net'", + '"net"', + 'Date.now', + ]; + for (const forbidden of forbiddenImports) { + expect(sourceText).not.toContain(forbidden); + } + }); + + test('links SIVB (XNAS) -> SIVBQ (OTCM) happy path and respects point-in-time asOfDate sweep', () => { + const listings: StageBListingCandidate[] = [ + makeListing({ + primaryIsin: 'US78486Q1013', + mic: 'XNAS', + tickerRoot: 'SIVB', + currency: 'USD', + listedFrom: '1987-10-26', + listedTo: '2023-03-10', + }), + makeListing({ + primaryIsin: 'US78486Q1013', + mic: 'OTCM', + tickerRoot: 'SIVBQ', + currency: 'USD', + listedFrom: '2023-03-28', + listedTo: '2024-11-07', + }), + ]; + + // Full post-cancellation view (2025-11-27). + const finalResult = linkDelistingChains( + { listings, otcMics: DEFAULT_OTC_MICS }, + { asOfDate: '2025-11-27' } + ); + expect(finalResult.conflicts).toEqual([]); + expect(finalResult.continuities).toEqual([ + { + fromListingKey: { + primaryIsin: 'US78486Q1013', + mic: 'XNAS', + tickerRoot: 'SIVB', + classSuffix: '', + currency: 'USD', + }, + toListingKey: { + primaryIsin: 'US78486Q1013', + mic: 'OTCM', + tickerRoot: 'SIVBQ', + classSuffix: '', + currency: 'USD', + }, + effectiveDate: '2023-03-28', + kind: 'otc_delist_transfer', + }, + ]); + expect(finalResult.listingOutcomes).toEqual([ + { + listingKey: { + primaryIsin: 'US78486Q1013', + mic: 'OTCM', + tickerRoot: 'SIVBQ', + classSuffix: '', + currency: 'USD', + }, + delistReason: 'bankruptcy_cancelled', + terminalReturn: -1.0, + }, + { + listingKey: { + primaryIsin: 'US78486Q1013', + mic: 'XNAS', + tickerRoot: 'SIVB', + classSuffix: '', + currency: 'USD', + }, + delistReason: 'moved_to_otc', + terminalReturn: null, + }, + ]); + assertReconciliationAndContracts(finalResult, 2); + + // As-of 2023-03-15: SIVB is still within 10-day grace window, and SIVBQ has not started yet -> no look-ahead link. + const sweepHalted = linkDelistingChains( + { listings, otcMics: DEFAULT_OTC_MICS }, + { asOfDate: '2023-03-15' } + ); + expect(sweepHalted.continuities).toEqual([]); + expect(sweepHalted.conflicts).toEqual([]); + expect(sweepHalted.listingOutcomes.find(o => o.listingKey.tickerRoot === 'SIVB')).toMatchObject( + { delistReason: 'active', terminalReturn: null } + ); + assertReconciliationAndContracts(sweepHalted, 2); + + // As-of 2023-03-28: SIVB is ended (18d > 10d grace), SIVBQ starts today -> linked, SIVBQ still active. + const sweepOtcOpen = linkDelistingChains( + { listings, otcMics: DEFAULT_OTC_MICS }, + { asOfDate: '2023-03-28' } + ); + expect(sweepOtcOpen.continuities).toHaveLength(1); + expect(sweepOtcOpen.continuities[0]?.effectiveDate).toBe('2023-03-28'); + expect( + sweepOtcOpen.listingOutcomes.find(o => o.listingKey.tickerRoot === 'SIVB') + ).toMatchObject({ delistReason: 'moved_to_otc', terminalReturn: null }); + expect( + sweepOtcOpen.listingOutcomes.find(o => o.listingKey.tickerRoot === 'SIVBQ') + ).toMatchObject({ delistReason: 'active', terminalReturn: null }); + assertReconciliationAndContracts(sweepOtcOpen, 2); + + // As-of 2024-12-01: SIVBQ ended 2024-11-07 (> 10d before 2024-12-01) -> bankruptcy_cancelled / -1.0. + const sweepCancelled = linkDelistingChains( + { listings, otcMics: DEFAULT_OTC_MICS }, + { asOfDate: '2024-12-01' } + ); + expect(sweepCancelled.continuities).toHaveLength(1); + expect( + sweepCancelled.listingOutcomes.find(o => o.listingKey.tickerRoot === 'SIVBQ') + ).toMatchObject({ delistReason: 'bankruptcy_cancelled', terminalReturn: -1.0 }); + assertReconciliationAndContracts(sweepCancelled, 2); + }); + + test('enforces Rule 2 active grace-window boundaries for primary and OTC listings', () => { + const listings: StageBListingCandidate[] = [ + // Open-ended listing (listedTo: null) -> active. + makeListing({ + primaryIsin: 'US0000000001', + mic: 'XNAS', + tickerRoot: 'OPEN', + listedTo: null, + }), + // Ended exactly at asOfDate - activeGraceDays (2025-11-27 - 10 = 2025-11-17) -> active (inclusive). + makeListing({ + primaryIsin: 'US0000000002', + mic: 'XNAS', + tickerRoot: 'EDGE', + listedTo: '2025-11-17', + }), + // Ended 1 day before cutoff (2025-11-16) -> ended primary -> unknown_involuntary / -0.3. + makeListing({ + primaryIsin: 'US0000000003', + mic: 'XNAS', + tickerRoot: 'DEAD', + listedTo: '2025-11-16', + }), + // Active OTC -Q ticker (still trading inside grace window) -> active / null, NOT bankruptcy_cancelled. + makeListing({ + primaryIsin: 'US0000000004', + mic: 'OTCM', + tickerRoot: 'LIVEQ', + listedTo: '2025-11-20', + }), + ]; + + const result = linkDelistingChains( + { listings, otcMics: DEFAULT_OTC_MICS }, + { asOfDate: '2025-11-27', activeGraceDays: 10 } + ); + + const byTicker = new Map(result.listingOutcomes.map(o => [o.listingKey.tickerRoot, o])); + expect(byTicker.get('OPEN')).toMatchObject({ delistReason: 'active', terminalReturn: null }); + expect(byTicker.get('EDGE')).toMatchObject({ delistReason: 'active', terminalReturn: null }); + expect(byTicker.get('DEAD')).toMatchObject({ + delistReason: 'unknown_involuntary', + terminalReturn: -0.3, + }); + expect(byTicker.get('LIVEQ')).toMatchObject({ delistReason: 'active', terminalReturn: null }); + assertReconciliationAndContracts(result, 4); + }); + + test('enforces Rule 4 exact 5-letter ASCII -Q bankruptcy marker only on ended OTC listings', () => { + const listings: StageBListingCandidate[] = [ + makeListing({ + primaryIsin: 'US1000000001', + mic: 'OTCM', + tickerRoot: 'SIVBQ', + listedTo: '2024-01-10', + }), + makeListing({ + primaryIsin: 'US1000000002', + mic: 'OTCM', + tickerRoot: 'HTZGQ', + listedTo: '2021-06-30', + }), + makeListing({ + primaryIsin: 'US1000000003', + mic: 'OTCM', + tickerRoot: 'ABCD', + listedTo: '2024-01-10', + }), + makeListing({ + primaryIsin: 'US1000000004', + mic: 'OTCM', + tickerRoot: 'ABCQ', + listedTo: '2024-01-10', + }), + makeListing({ + primaryIsin: 'US1000000005', + mic: 'OTCM', + tickerRoot: 'ABCDEQ', + listedTo: '2024-01-10', + }), + makeListing({ + primaryIsin: 'US1000000006', + mic: 'OTCM', + tickerRoot: '1234Q', + listedTo: '2024-01-10', + }), + // Primary-venue 5-letter ending in Q must NOT be classified as bankruptcy_cancelled. + makeListing({ + primaryIsin: 'US1000000007', + mic: 'XNAS', + tickerRoot: 'SIVBQ', + listedTo: '2024-01-10', + }), + ]; + + const result = linkDelistingChains( + { listings, otcMics: DEFAULT_OTC_MICS }, + { asOfDate: '2025-11-27' } + ); + + const byIsin = new Map(result.listingOutcomes.map(o => [o.listingKey.primaryIsin, o])); + expect(byIsin.get('US1000000001')).toMatchObject({ + delistReason: 'bankruptcy_cancelled', + terminalReturn: -1.0, + }); + expect(byIsin.get('US1000000002')).toMatchObject({ + delistReason: 'bankruptcy_cancelled', + terminalReturn: -1.0, + }); + for (const isin of [ + 'US1000000003', + 'US1000000004', + 'US1000000005', + 'US1000000006', + 'US1000000007', + ]) { + expect(byIsin.get(isin)).toMatchObject({ + delistReason: 'unknown_involuntary', + terminalReturn: -0.3, + }); + } + assertReconciliationAndContracts(result, 7); + }); + + test('enforces transfer gap, overlap tolerance, OTC stub rejection, and ISIN/currency/venue isolation', () => { + const listings: StageBListingCandidate[] = [ + // Gap === maxTransferGapDays (30d: 2023-03-01 -> 2023-03-31) -> links. + makeListing({ + primaryIsin: 'US2000000001', + mic: 'XNAS', + tickerRoot: 'GAP30', + listedTo: '2023-03-01', + }), + makeListing({ + primaryIsin: 'US2000000001', + mic: 'OTCM', + tickerRoot: 'GAP30Q', + listedFrom: '2023-03-31', + listedTo: '2024-01-01', + }), + // Gap === maxTransferGapDays + 1 (31d: 2023-03-01 -> 2023-04-01) -> no link. + makeListing({ + primaryIsin: 'US2000000002', + mic: 'XNAS', + tickerRoot: 'GAP31', + listedTo: '2023-03-01', + }), + makeListing({ + primaryIsin: 'US2000000002', + mic: 'OTCM', + tickerRoot: 'GAP31Q', + listedFrom: '2023-04-01', + listedTo: '2024-01-01', + }), + // Overlap === overlapToleranceDays (5d before: 2023-03-05 vs 2023-03-10, otc.listedTo >= primary.listedTo) -> links. + makeListing({ + primaryIsin: 'US2000000003', + mic: 'XNYS', + tickerRoot: 'OVLP5', + listedTo: '2023-03-10', + }), + makeListing({ + primaryIsin: 'US2000000003', + mic: 'OTCM', + tickerRoot: 'OVLPQ', + listedFrom: '2023-03-05', + listedTo: '2023-09-01', + }), + // Overlap === overlapToleranceDays + 1 (6d before: 2023-03-04 vs 2023-03-10) -> no link. + makeListing({ + primaryIsin: 'US2000000004', + mic: 'XNYS', + tickerRoot: 'OVLP6', + listedTo: '2023-03-10', + }), + makeListing({ + primaryIsin: 'US2000000004', + mic: 'OTCM', + tickerRoot: 'OVL6Q', + listedFrom: '2023-03-04', + listedTo: '2023-09-01', + }), + // OTC stub that ended BEFORE primary ended (2023-03-08 < 2023-03-10) -> no link. + makeListing({ + primaryIsin: 'US2000000005', + mic: 'XNYS', + tickerRoot: 'STUB', + listedTo: '2023-03-10', + }), + makeListing({ + primaryIsin: 'US2000000005', + mic: 'OTCM', + tickerRoot: 'STUBQ', + listedFrom: '2023-03-06', + listedTo: '2023-03-08', + }), + // Different ISINs -> never link. + makeListing({ + primaryIsin: 'US2000000006', + mic: 'XNAS', + tickerRoot: 'DIFF1', + listedTo: '2023-03-10', + }), + makeListing({ + primaryIsin: 'US2000000007', + mic: 'OTCM', + tickerRoot: 'DIFFQ', + listedFrom: '2023-03-15', + listedTo: '2024-01-01', + }), + // Same ISIN, different currency (CAD primary vs USD OTC interlisted) -> never link. + makeListing({ + primaryIsin: 'CA2000000008', + mic: 'XTSE', + tickerRoot: 'INTER', + currency: 'CAD', + listedTo: '2023-03-10', + }), + makeListing({ + primaryIsin: 'CA2000000008', + mic: 'OTCM', + tickerRoot: 'INTRF', + currency: 'USD', + listedFrom: '2023-03-15', + listedTo: '2024-01-01', + }), + // OTC -> OTC on same ISIN+currency -> never link. + makeListing({ + primaryIsin: 'US2000000009', + mic: 'OTCM', + tickerRoot: 'OTCA', + listedFrom: '2020-01-01', + listedTo: '2023-03-10', + }), + makeListing({ + primaryIsin: 'US2000000009', + mic: 'OTCM', + tickerRoot: 'OTCAQ', + listedFrom: '2023-03-15', + listedTo: '2024-01-01', + }), + // Primary -> Primary on same ISIN+currency -> never link. + makeListing({ + primaryIsin: 'US2000000010', + mic: 'XNAS', + tickerRoot: 'UPL1', + listedFrom: '2020-01-01', + listedTo: '2023-03-10', + }), + makeListing({ + primaryIsin: 'US2000000010', + mic: 'XNYS', + tickerRoot: 'UPL2', + listedFrom: '2023-03-15', + listedTo: '2024-01-01', + }), + ]; + + const result = linkDelistingChains( + { listings, otcMics: DEFAULT_OTC_MICS }, + { asOfDate: '2025-11-27', maxTransferGapDays: 30, overlapToleranceDays: 5 } + ); + + expect(result.conflicts).toEqual([]); + expect(result.continuities.map(c => c.fromListingKey.primaryIsin)).toEqual([ + 'US2000000001', + 'US2000000003', + ]); + assertReconciliationAndContracts(result, listings.length); + }); + + test('quarantines ambiguous 1-to-2, 2-to-1, and 2x2 components while linking disjoint cycles cleanly', () => { + const listings: StageBListingCandidate[] = [ + // 1-to-2: one primary with two OTC candidates in window -> conflict, 0 continuities. + makeListing({ + primaryIsin: 'US3000000001', + mic: 'XNAS', + tickerRoot: 'ONEP', + listedTo: '2023-03-10', + }), + makeListing({ + primaryIsin: 'US3000000001', + mic: 'OTCM', + tickerRoot: 'ONEPQ', + listedFrom: '2023-03-15', + listedTo: '2024-01-01', + }), + makeListing({ + primaryIsin: 'US3000000001', + mic: 'OTCM', + tickerRoot: 'ONEPA', + listedFrom: '2023-03-20', + listedTo: '2024-01-01', + }), + + // 2-to-1: two primary listings competing for one OTC listing -> conflict, 0 continuities. + makeListing({ + primaryIsin: 'US3000000002', + mic: 'XNAS', + tickerRoot: 'TWOP1', + listedTo: '2023-03-10', + }), + makeListing({ + primaryIsin: 'US3000000002', + mic: 'XNYS', + tickerRoot: 'TWOP2', + listedTo: '2023-03-12', + }), + makeListing({ + primaryIsin: 'US3000000002', + mic: 'OTCM', + tickerRoot: 'TWOPQ', + listedFrom: '2023-03-20', + listedTo: '2024-01-01', + }), + + // Mixed 2x2 connected component -> 1 conflict, 0 continuities. + makeListing({ + primaryIsin: 'US3000000003', + mic: 'XNAS', + tickerRoot: 'MXP1', + listedTo: '2023-03-10', + }), + makeListing({ + primaryIsin: 'US3000000003', + mic: 'XNYS', + tickerRoot: 'MXP2', + listedTo: '2023-03-15', + }), + makeListing({ + primaryIsin: 'US3000000003', + mic: 'OTCM', + tickerRoot: 'MXPQ1', + listedFrom: '2023-03-18', + listedTo: '2024-01-01', + }), + makeListing({ + primaryIsin: 'US3000000003', + mic: 'OTCM', + tickerRoot: 'MXPQ2', + listedFrom: '2023-03-25', + listedTo: '2024-01-01', + }), + + // Two disjoint non-overlapping delist -> OTC cycles on the same (primaryIsin, currency) -> both link cleanly! + makeListing({ + primaryIsin: 'US3000000004', + mic: 'XNAS', + tickerRoot: 'CYC1', + listedFrom: '2015-01-02', + listedTo: '2018-06-01', + }), + makeListing({ + primaryIsin: 'US3000000004', + mic: 'OTCM', + tickerRoot: 'CYC1Q', + listedFrom: '2018-06-10', + listedTo: '2019-12-31', + }), + makeListing({ + primaryIsin: 'US3000000004', + mic: 'XNYS', + tickerRoot: 'CYC2', + listedFrom: '2020-01-02', + listedTo: '2023-06-01', + }), + makeListing({ + primaryIsin: 'US3000000004', + mic: 'OTCM', + tickerRoot: 'CYC2Q', + listedFrom: '2023-06-12', + listedTo: '2024-06-01', + }), + ]; + + const result = linkDelistingChains( + { listings, otcMics: DEFAULT_OTC_MICS }, + { asOfDate: '2025-11-27' } + ); + + expect(result.conflicts).toHaveLength(3); + for (const conflict of result.conflicts) { + expect(conflict.conflictKind).toBe('ambiguous_otc_continuation'); + } + expect(result.conflicts.map(c => c.detail.primaryIsin)).toEqual([ + 'US3000000001', + 'US3000000002', + 'US3000000003', + ]); + expect(result.conflicts[0]?.detail.candidateListingKeys).toHaveLength(3); + expect(result.conflicts[1]?.detail.candidateListingKeys).toHaveLength(3); + expect(result.conflicts[2]?.detail.candidateListingKeys).toHaveLength(4); + + // Primaries in ambiguous components fall back to unknown_involuntary / -0.3. + const byTicker = new Map(result.listingOutcomes.map(o => [o.listingKey.tickerRoot, o])); + for (const ticker of ['ONEP', 'TWOP1', 'TWOP2', 'MXP1', 'MXP2']) { + expect(byTicker.get(ticker)).toMatchObject({ + delistReason: 'unknown_involuntary', + terminalReturn: -0.3, + }); + } + + // Disjoint cycles both link cleanly. + expect(result.continuities).toHaveLength(2); + expect( + result.continuities.map(c => [ + c.fromListingKey.tickerRoot, + c.toListingKey.tickerRoot, + c.effectiveDate, + ]) + ).toEqual([ + ['CYC1', 'CYC1Q', '2018-06-10'], + ['CYC2', 'CYC2Q', '2023-06-12'], + ]); + expect(byTicker.get('CYC1')).toMatchObject({ + delistReason: 'moved_to_otc', + terminalReturn: null, + }); + expect(byTicker.get('CYC2')).toMatchObject({ + delistReason: 'moved_to_otc', + terminalReturn: null, + }); + assertReconciliationAndContracts(result, listings.length); + }); + + test('records typed conflicts on invalid dates, null OTC listedFrom, and duplicate keys without throwing', () => { + const listings: StageBListingCandidate[] = [ + // Rollover leap date 2023-02-29 + makeListing({ + primaryIsin: 'US4000000001', + mic: 'XNAS', + tickerRoot: 'BAD1', + listedFrom: '2023-02-29', + listedTo: '2024-01-01', + }), + // Timestamp string instead of YYYY-MM-DD + makeListing({ + primaryIsin: 'US4000000002', + mic: 'XNAS', + tickerRoot: 'BAD2', + listedFrom: '2020-01-01', + listedTo: '2023-03-10T00:00:00Z', + }), + // Padded date string + makeListing({ + primaryIsin: 'US4000000003', + mic: 'XNAS', + tickerRoot: 'BAD3', + listedFrom: ' 2023-03-10 ', + listedTo: '2024-01-01', + }), + // Inverted range (listedFrom > listedTo) + makeListing({ + primaryIsin: 'US4000000004', + mic: 'XNAS', + tickerRoot: 'BAD4', + listedFrom: '2024-05-01', + listedTo: '2024-04-01', + }), + // OTC with null listedFrom alongside ended primary -> missing_otc_listed_from conflict, OTC still classified. + makeListing({ + primaryIsin: 'US4000000005', + mic: 'XNAS', + tickerRoot: 'MISS', + listedFrom: '2020-01-01', + listedTo: '2023-03-10', + }), + makeListing({ + primaryIsin: 'US4000000005', + mic: 'OTCM', + tickerRoot: 'MISSQ', + listedFrom: null, + listedTo: '2024-01-01', + }), + // Duplicate natural keys -> quarantined as duplicate_listing_key. + makeListing({ + primaryIsin: 'US4000000006', + mic: 'XNAS', + tickerRoot: 'DUPX', + listedFrom: '2020-01-01', + listedTo: '2024-01-01', + }), + makeListing({ + primaryIsin: 'US4000000006', + mic: 'XNAS', + tickerRoot: 'DUPX', + listedFrom: '2021-01-01', + listedTo: '2024-06-01', + }), + ]; + + const result = linkDelistingChains( + { listings, otcMics: DEFAULT_OTC_MICS }, + { asOfDate: '2025-11-27' } + ); + + expect(result.stats.skippedInvalidDates).toBe(4); + expect(result.stats.skippedDuplicateKeys).toBe(2); + expect(result.stats.processedListings).toBe(2); + expect(result.continuities).toEqual([]); + + const conflictKinds = result.conflicts.map(c => c.conflictKind); + expect(conflictKinds.filter(k => k === 'invalid_listing_dates')).toHaveLength(4); + expect(conflictKinds.filter(k => k === 'duplicate_listing_key')).toHaveLength(1); + expect(conflictKinds.filter(k => k === 'missing_otc_listed_from')).toHaveLength(1); + + const byTicker = new Map(result.listingOutcomes.map(o => [o.listingKey.tickerRoot, o])); + expect(byTicker.get('MISS')).toMatchObject({ + delistReason: 'unknown_involuntary', + terminalReturn: -0.3, + }); + expect(byTicker.get('MISSQ')).toMatchObject({ + delistReason: 'bankruptcy_cancelled', + terminalReturn: -1.0, + }); + assertReconciliationAndContracts(result, listings.length); + }); + + test('throws TypeError or RangeError on invalid options or container arguments', () => { + const emptyInput = { listings: [], otcMics: DEFAULT_OTC_MICS }; + const validOpts = { asOfDate: '2025-11-27' }; + + expect(() => linkDelistingChains(null as unknown as typeof emptyInput, validOpts)).toThrow( + TypeError + ); + expect(() => + linkDelistingChains( + { listings: 'not-an-array' as unknown as StageBListingCandidate[], otcMics: DEFAULT_OTC_MICS }, + validOpts + ) + ).toThrow(TypeError); + expect(() => + linkDelistingChains( + { listings: [], otcMics: ['OTCM'] as unknown as ReadonlySet }, + validOpts + ) + ).toThrow(TypeError); + expect(() => + linkDelistingChains({ listings: [], otcMics: new Set(['INVALID_MIC']) }, validOpts) + ).toThrow(RangeError); + expect(() => + linkDelistingChains(emptyInput, null as unknown as typeof validOpts) + ).toThrow(TypeError); + expect(() => + linkDelistingChains(emptyInput, {} as unknown as typeof validOpts) + ).toThrow(TypeError); + expect(() => linkDelistingChains(emptyInput, { asOfDate: '2023-02-29' })).toThrow(RangeError); + expect(() => linkDelistingChains(emptyInput, { asOfDate: '2025-11-27T00:00:00Z' })).toThrow( + RangeError + ); + expect(() => + linkDelistingChains(emptyInput, { asOfDate: '2025-11-27', activeGraceDays: -1 }) + ).toThrow(RangeError); + expect(() => + linkDelistingChains(emptyInput, { asOfDate: '2025-11-27', maxTransferGapDays: 1.5 }) + ).toThrow(RangeError); + expect(() => + linkDelistingChains(emptyInput, { asOfDate: '2025-11-27', overlapToleranceDays: -2 }) + ).toThrow(RangeError); + expect(() => + linkDelistingChains(emptyInput, { + asOfDate: '2025-11-27', + activeGraceDays: '10' as unknown as number, + }) + ).toThrow(TypeError); + }); + + test('is deterministic across input shuffles, never mutates inputs, and never shares ListingNaturalKey references', () => { + const listings: StageBListingCandidate[] = [ + makeListing({ + primaryIsin: 'US78486Q1013', + mic: 'XNAS', + tickerRoot: 'SIVB', + listedFrom: '1987-10-26', + listedTo: '2023-03-10', + }), + makeListing({ + primaryIsin: 'US78486Q1013', + mic: 'OTCM', + tickerRoot: 'SIVBQ', + listedFrom: '2023-03-28', + listedTo: '2024-11-07', + }), + makeListing({ + primaryIsin: 'US5000000001', + mic: 'XNAS', + tickerRoot: 'AMBG', + listedTo: '2023-05-01', + }), + makeListing({ + primaryIsin: 'US5000000001', + mic: 'OTCM', + tickerRoot: 'AMBGQ', + listedFrom: '2023-05-05', + listedTo: '2024-01-01', + }), + makeListing({ + primaryIsin: 'US5000000001', + mic: 'OTCM', + tickerRoot: 'AMBGA', + listedFrom: '2023-05-10', + listedTo: '2024-01-01', + }), + makeListing({ + primaryIsin: 'US5000000002', + mic: 'XNYS', + tickerRoot: 'ACTV', + listedTo: null, + }), + makeListing({ + primaryIsin: 'US5000000003', + mic: 'XNAS', + tickerRoot: 'BADD', + listedFrom: '2024-05-01', + listedTo: '2024-01-01', + }), + ]; + + const snapshotBefore = structuredClone(listings); + for (const item of listings) { + Object.freeze(item); + } + Object.freeze(listings); + const otcMics = new Set(['OTCM']); + + const baseline = linkDelistingChains({ listings, otcMics }, { asOfDate: '2025-11-27' }); + const baselineJson = JSON.stringify(baseline); + + // Input immutability check. + expect(listings).toEqual(snapshotBefore); + expect([...otcMics]).toEqual(['OTCM']); + + // Reference isolation check (T-58): every returned ListingNaturalKey object must be unique and distinct from input rows. + const inputRefs = new Set(listings); + const seenKeyRefs = new Set(); + const registerKey = (key: ListingNaturalKey): void => { + expect(inputRefs.has(key)).toBe(false); + expect(seenKeyRefs.has(key)).toBe(false); + seenKeyRefs.add(key); + }; + + for (const c of baseline.continuities) { + registerKey(c.fromListingKey); + registerKey(c.toListingKey); + } + for (const o of baseline.listingOutcomes) { + registerKey(o.listingKey); + } + for (const conflict of baseline.conflicts) { + for (const k of conflict.detail.fromListingKeys) { + registerKey(k); + } + for (const k of conflict.detail.toListingKeys) { + registerKey(k); + } + for (const k of conflict.detail.candidateListingKeys) { + registerKey(k); + } + } + expect(seenKeyRefs.size).toBeGreaterThan(0); + + // Shuffle determinism across multiple seeds. + for (const seed of [1, 42, 1337, 99999]) { + const shuffled = shuffleWithSeed(listings, seed); + const res = linkDelistingChains({ listings: shuffled, otcMics }, { asOfDate: '2025-11-27' }); + expect(JSON.stringify(res)).toBe(baselineJson); + assertReconciliationAndContracts(res, listings.length); + } + }); + + test('scale smoke: 50,000 synthetic listings complete under 1000 ms with exact stats reconciliation', () => { + const TOTAL = 50_000; + const listings: StageBListingCandidate[] = []; + + // 10,000 linked primary -> OTC pairs (20,000 listings; half ended -Q, half active OTC) + for (let i = 0; i < 10_000; i++) { + const isin = `US${String(1000000000 + i)}`; + const isBankruptOtc = (i & 1) === 0; + const root4 = + String.fromCharCode(65 + ((i >> 12) % 26)) + + String.fromCharCode(65 + ((i >> 8) % 26)) + + String.fromCharCode(65 + ((i >> 4) % 26)) + + String.fromCharCode(65 + (i % 26)); + listings.push( + makeListing({ + primaryIsin: isin, + mic: 'XNAS', + tickerRoot: `P${i}`, + listedFrom: '2015-01-02', + listedTo: '2023-03-10', + }), + makeListing({ + primaryIsin: isin, + mic: 'OTCM', + tickerRoot: isBankruptOtc ? `${root4}Q` : `O${i}`, + listedFrom: '2023-03-20', + listedTo: isBankruptOtc ? '2024-06-01' : null, + }) + ); + } + + // 1,000 ambiguous 1-to-2 groups (3,000 listings) + for (let i = 0; i < 1_000; i++) { + const isin = `US${String(2000000000 + i)}`; + listings.push( + makeListing({ + primaryIsin: isin, + mic: 'XNYS', + tickerRoot: `AP${i}`, + listedFrom: '2015-01-02', + listedTo: '2023-04-01', + }), + makeListing({ + primaryIsin: isin, + mic: 'OTCM', + tickerRoot: `AO1${i}`, + listedFrom: '2023-04-05', + listedTo: '2024-01-01', + }), + makeListing({ + primaryIsin: isin, + mic: 'OTCM', + tickerRoot: `AO2${i}`, + listedFrom: '2023-04-10', + listedTo: '2024-01-01', + }) + ); + } + + // 17,000 active primary listings + for (let i = 0; i < 17_000; i++) { + listings.push( + makeListing({ + primaryIsin: `US${String(3000000000 + i)}`, + mic: 'XNAS', + tickerRoot: `ACT${i}`, + listedFrom: '2018-01-02', + listedTo: null, + }) + ); + } + + // 10,000 unlinked ended primary listings + for (let i = 0; i < 10_000; i++) { + listings.push( + makeListing({ + primaryIsin: `US${String(4000000000 + i)}`, + mic: 'XNYS', + tickerRoot: `END${i}`, + listedFrom: '2015-01-02', + listedTo: '2022-12-30', + }) + ); + } + + expect(listings).toHaveLength(TOTAL); + + const startMs = performance.now(); + const result = linkDelistingChains( + { listings, otcMics: DEFAULT_OTC_MICS }, + { asOfDate: '2025-11-27' } + ); + const elapsedMs = performance.now() - startMs; + + process.stdout.write( + `[benchmark] linkDelistingChains(${TOTAL} listings): ${elapsedMs.toFixed(1)} ms (${result.continuities.length} continuities, ${result.conflicts.length} conflicts)\n` + ); + + expect(elapsedMs).toBeLessThan(1000); + expect(result.continuities).toHaveLength(10_000); + expect(result.conflicts).toHaveLength(1_000); + expect(result.stats.byOutcome.moved_to_otc).toBe(10_000); + expect(result.stats.byOutcome.bankruptcy_cancelled).toBe(5_000); + expect(result.stats.byOutcome.active).toBe(22_000); + expect(result.stats.byOutcome.unknown_involuntary).toBe(13_000); + expect( + result.stats.byOutcome.active + + result.stats.byOutcome.moved_to_otc + + result.stats.byOutcome.bankruptcy_cancelled + + result.stats.byOutcome.unknown_involuntary + ).toBe(TOTAL); + assertReconciliationAndContracts(result, TOTAL); + }); +});