stock-bot/apps/stock/data-pipeline/src/security-master/delisting-chains.ts

865 lines
29 KiB
TypeScript

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<string> = 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<string>;
}
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;
}
/**
* Delisting classification for a single listing as of `options.asOfDate`.
*
* Note: `delistReason: 'active'` indicates delisting status (not delisted as of `asOfDate`),
* not point-in-time universe eligibility. Historical callers must filter listings by
* `listedFrom <= asOfDate` before using outcomes for universe membership.
*/
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'
| 'malformed_listing_entry';
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;
skippedMalformedEntries: 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<string> {
if (!(otcMics instanceof Set)) {
throw new TypeError('input.otcMics must be a ReadonlySet<string>');
}
const normalized = new Set<string>();
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() : '',
};
}
interface OtcPrimaryInterval {
readonly startIdx: number;
readonly endIdx: number;
readonly otcIdx: number;
}
function lowerBoundPrimaryByListedToDay(
primaries: readonly EndedPrimaryRow[],
targetDay: number
): number {
let lo = 0;
let hi = primaries.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
const midRow = primaries[mid];
if (midRow !== undefined && midRow.listedToDay < targetDay) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
function upperBoundPrimaryByListedToDay(
primaries: readonly EndedPrimaryRow[],
targetDay: number
): number {
let lo = 0;
let hi = primaries.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
const midRow = primaries[mid];
if (midRow !== undefined && midRow.listedToDay <= 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.
*
* Note: `delistReason: 'active'` is strictly a delisting status ("not delisted as of
* `options.asOfDate`"). Historical callers must filter listings by `listedFrom <= asOfDate`
* before using outcomes for point-in-time universe membership.
*/
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 conflicts: DelistingChainConflictRecord[] = [];
const normalizedKeys = new Array<ListingNaturalKey | undefined>(totalInputListings);
const keyIds = new Array<string | undefined>(totalInputListings);
const keyCounts = new Map<string, number>();
let skippedMalformedEntries = 0;
for (let i = 0; i < totalInputListings; i++) {
let malformedKind: string | null = null;
const row = i in input.listings ? input.listings[i] : undefined;
if (!(i in input.listings)) {
malformedKind = 'sparse slot';
} else if (row === undefined) {
malformedKind = 'undefined';
} else if (row === null) {
malformedKind = 'null';
} else if (Array.isArray(row)) {
malformedKind = 'array';
} else if (typeof row !== 'object') {
malformedKind = typeof row;
}
if (malformedKind !== null || row === undefined) {
skippedMalformedEntries += 1;
conflicts.push({
conflictKind: 'malformed_listing_entry',
detail: {
primaryIsin: '',
currency: '',
fromListingKeys: [],
toListingKeys: [],
candidateListingKeys: [],
listedFrom: null,
listedTo: null,
reason: `Malformed listing entry at input.listings[${i}]: expected a listing object, received ${malformedKind ?? 'undefined'}`,
},
});
continue;
}
const key = normalizeKeyFromListing(row);
const keyId = makeListingNaturalKeyId(key);
normalizedKeys[i] = key;
keyIds[i] = keyId;
keyCounts.set(keyId, (keyCounts.get(keyId) ?? 0) + 1);
}
const validRows: NormalizedListingRow[] = [];
const groups = new Map<string, InstrumentCurrencyGroup>();
const reportedDuplicateKeyIds = new Set<string>();
const droppedOtcKeysByGroup = new Map<string, Map<string, ListingNaturalKey>>();
const recordDroppedOtcIfApplicable = (
key: ListingNaturalKey,
keyId: string,
listedFromDay: number | null
): void => {
if (
!normalizedOtcMics.has(key.mic) ||
key.primaryIsin.length === 0 ||
key.currency.length === 0 ||
(listedFromDay !== null && listedFromDay > asOfDay)
) {
return;
}
const groupKey = makeGroupKey(key.primaryIsin, key.currency);
let droppedForGroup = droppedOtcKeysByGroup.get(groupKey);
if (droppedForGroup === undefined) {
droppedForGroup = new Map<string, ListingNaturalKey>();
droppedOtcKeysByGroup.set(groupKey, droppedForGroup);
}
if (!droppedForGroup.has(keyId)) {
droppedForGroup.set(keyId, key);
}
};
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;
recordDroppedOtcIfApplicable(key, keyId, parseExactIsoDateToUtcDay(row.listedFrom));
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;
recordDroppedOtcIfApplicable(key, keyId, listedFromDay);
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<number>();
for (const group of groups.values()) {
if (group.endedPrimaries.length === 0) {
continue;
}
const droppedOtcMap = droppedOtcKeysByGroup.get(
makeGroupKey(group.primaryIsin, group.currency)
);
const droppedOtcCount = droppedOtcMap?.size ?? 0;
if (group.missingFromOtcs.length > 0 || droppedOtcCount > 0) {
const sortedPrimaryKeys = group.endedPrimaries
.map(p => p.key)
.sort(compareListingNaturalKey);
const blockingOtcKeyMap = new Map<string, ListingNaturalKey>();
for (const o of group.missingFromOtcs) {
blockingOtcKeyMap.set(makeListingNaturalKeyId(o.key), o.key);
}
if (droppedOtcMap !== undefined) {
for (const [kId, k] of droppedOtcMap) {
if (!blockingOtcKeyMap.has(kId)) {
blockingOtcKeyMap.set(kId, k);
}
}
}
const sortedBlockingOtcKeys = [...blockingOtcKeyMap.values()].sort(compareListingNaturalKey);
const allKeys = [...sortedPrimaryKeys, ...sortedBlockingOtcKeys].sort(
compareListingNaturalKey
);
const singleMissingOtc =
group.missingFromOtcs.length === 1 ? group.missingFromOtcs[0] : undefined;
let reason: string;
if (droppedOtcCount === 0) {
reason =
group.missingFromOtcs.length === 1
? 'OTC listing has null listedFrom; cannot establish transfer window or effectiveDate'
: `${group.missingFromOtcs.length} OTC listings have null listedFrom; cannot establish transfer window or effectiveDate`;
} else if (group.missingFromOtcs.length === 0) {
reason =
droppedOtcCount === 1
? 'OTC listing was dropped due to duplicate key or invalid dates; cannot establish transfer window or effectiveDate'
: `${droppedOtcCount} OTC listings were dropped due to duplicate key or invalid dates; cannot establish transfer window or effectiveDate`;
} else {
reason = `${group.missingFromOtcs.length} undated OTC listing(s) and ${droppedOtcCount} dropped OTC listing(s) in group; cannot establish transfer window or effectiveDate`;
}
conflicts.push({
conflictKind: 'missing_otc_listed_from',
detail: {
primaryIsin: group.primaryIsin,
currency: group.currency,
fromListingKeys: sortedPrimaryKeys.map(cloneListingKey),
toListingKeys: sortedBlockingOtcKeys.map(cloneListingKey),
candidateListingKeys: allKeys.map(cloneListingKey),
listedFrom: null,
listedTo: singleMissingOtc !== undefined ? singleMissingOtc.listedTo : null,
reason,
},
});
// Rule 5 ("never guess"): an undated or dropped OTC row in the same (primaryIsin, currency)
// group could be the true continuation, so suppress all continuity linking for this group
// until OTC listing metadata is resolved.
continue;
}
if (group.eligibleOtcs.length === 0) {
continue;
}
const primaries = group.endedPrimaries;
const otcs = group.eligibleOtcs;
primaries.sort(
(a, b) => a.listedToDay - b.listedToDay || compareListingNaturalKey(a.key, b.key)
);
// For each eligible OTC listing, its matching ended primaries form a contiguous index
// range [startIdx, endIdx] in `primaries` sorted by `listedToDay`:
// otc.listedFromDay - maxTransferGapDays <= primary.listedToDay
// primary.listedToDay <= min(otc.listedFromDay + overlapToleranceDays, otc.listedToDay ?? +inf)
// Merging overlapping intervals finds all bipartite connected components in O((P + O) log (P + O))
// time and O(P + O) memory without enumerating O(P * O) candidate edges.
const intervals: OtcPrimaryInterval[] = [];
for (let oIdx = 0; oIdx < otcs.length; oIdx++) {
const otc = otcs[oIdx];
if (otc === undefined) {
continue;
}
const lowDay = otc.listedFromDay - maxTransferGapDays;
const maxWindowDay = otc.listedFromDay + overlapToleranceDays;
// Reject OTC stubs that had already ended before the primary listing ended.
const highDay =
otc.listedToDay === null || otc.listedToDay > maxWindowDay
? maxWindowDay
: otc.listedToDay;
if (lowDay > highDay) {
continue;
}
const startIdx = lowerBoundPrimaryByListedToDay(primaries, lowDay);
const endExclusive = upperBoundPrimaryByListedToDay(primaries, highDay);
if (startIdx < endExclusive) {
intervals.push({ startIdx, endIdx: endExclusive - 1, otcIdx: oIdx });
}
}
if (intervals.length === 0) {
continue;
}
intervals.sort(
(a, b) => a.startIdx - b.startIdx || a.endIdx - b.endIdx || a.otcIdx - b.otcIdx
);
const firstInterval = intervals[0];
if (firstInterval === undefined) {
continue;
}
let compStart = firstInterval.startIdx;
let compEnd = firstInterval.endIdx;
let compOtcs: number[] = [firstInterval.otcIdx];
const flushComponent = (startIdx: number, endIdx: number, otcIndices: readonly number[]): void => {
const primaryCount = endIdx - startIdx + 1;
const otcCount = otcIndices.length;
if (primaryCount === 1 && otcCount === 1) {
const primary = primaries[startIdx];
const oIdx = otcIndices[0];
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,
});
}
return;
}
const fromKeys: ListingNaturalKey[] = [];
for (let pIdx = startIdx; pIdx <= endIdx; pIdx++) {
const p = primaries[pIdx];
if (p !== undefined) {
fromKeys.push(p.key);
}
}
fromKeys.sort(compareListingNaturalKey);
const toKeys: ListingNaturalKey[] = [];
for (let k = 0; k < otcIndices.length; k++) {
const oIdx = otcIndices[k];
const o = oIdx !== undefined ? otcs[oIdx] : undefined;
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 (${primaryCount} primary, ${otcCount} OTC)`,
},
});
};
for (let i = 1; i < intervals.length; i++) {
const interval = intervals[i];
if (interval === undefined) {
continue;
}
if (interval.startIdx <= compEnd) {
if (interval.endIdx > compEnd) {
compEnd = interval.endIdx;
}
compOtcs.push(interval.otcIdx);
} else {
flushComponent(compStart, compEnd, compOtcs);
compStart = interval.startIdx;
compEnd = interval.endIdx;
compOtcs = [interval.otcIdx];
}
}
flushComponent(compStart, compEnd, compOtcs);
}
// 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) {
// 'active' is a delisting status (not delisted as of options.asOfDate), not a
// universe-membership flag; historical callers must filter by listedFrom <= asOfDate.
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,
skippedMalformedEntries,
skippedInvalidDates,
skippedDuplicateKeys,
continuitiesCreated: continuities.length,
conflictsDetected: conflicts.length,
byOutcome,
},
};
}