T-60: M1.1g — Pass 6: pure in-memory OTC delisting chain linker (same-ISIN primary venue → OTC continuation, SIVB → SIVBQ) + delist reason / Shumway terminal return
This commit is contained in:
parent
a886050e9b
commit
cef3adad5e
3 changed files with 1823 additions and 0 deletions
739
apps/stock/data-pipeline/src/security-master/delisting-chains.ts
Normal file
739
apps/stock/data-pipeline/src/security-master/delisting-chains.ts
Normal file
|
|
@ -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<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;
|
||||
}
|
||||
|
||||
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<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() : '',
|
||||
};
|
||||
}
|
||||
|
||||
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<ListingNaturalKey>(totalInputListings);
|
||||
const keyIds = new Array<string>(totalInputListings);
|
||||
const keyCounts = new Map<string, number>();
|
||||
|
||||
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<string, InstrumentCurrencyGroup>();
|
||||
const reportedDuplicateKeyIds = new Set<string>();
|
||||
|
||||
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<number>();
|
||||
|
||||
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,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -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,
|
||||
|
|
|
|||
1060
test/unit/security-master-delisting-chains.test.ts
Normal file
1060
test/unit/security-master-delisting-chains.test.ts
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue