T-38: M1.1b — Pass 2 normalization: ISIN/CUSIP validators, ticker root/suffix parser, IB fields in provider-symbol.ts

This commit is contained in:
Studio 2026-11-27 14:37:27 -05:00
parent abf51ad2df
commit 5483f7f127
6 changed files with 731 additions and 2 deletions

View file

@ -0,0 +1,234 @@
export type NorthAmericaCountry = 'US' | 'CA';
export interface ResolveIsinInput {
isin?: string | null;
cusip?: string | null;
country?: string | null;
}
export type ResolveIsinRejectionReason =
| 'missing_identifiers'
| 'invalid_isin_and_no_valid_cusip'
| 'invalid_cusip'
| 'unsupported_country_for_cusip';
export type ResolveIsinResult =
| { isin: string; source: 'isin' | 'cusip_derived' }
| { isin: null; reason: ResolveIsinRejectionReason };
const CODE_0 = 48;
const CODE_9 = 57;
const CODE_A = 65;
const CODE_Z = 90;
const CODE_STAR = 42;
const CODE_AT = 64;
const CODE_HASH = 35;
function normalizeCode(value: string | null | undefined): string | null {
if (typeof value !== 'string') {
return null;
}
const normalized = value.trim().toUpperCase();
return normalized.length === 0 ? null : normalized;
}
function isAsciiDigit(code: number): boolean {
return code >= CODE_0 && code <= CODE_9;
}
function isAsciiUpper(code: number): boolean {
return code >= CODE_A && code <= CODE_Z;
}
function isAsciiAlnum(code: number): boolean {
return isAsciiDigit(code) || isAsciiUpper(code);
}
function isNorthAmericaCountry(value: string | null): value is NorthAmericaCountry {
return value === 'US' || value === 'CA';
}
function luhnStep(digit: number, doubleDigit: boolean): number {
if (!doubleDigit) {
return digit;
}
const doubled = digit * 2;
return doubled > 9 ? doubled - 9 : doubled;
}
/**
* Computes the ISO 6166 Luhn sum scanning right-to-left from `endIndex` down to 0.
* Letters A=10..Z=35 expand to two decimal digits (units first, then tens when scanning right-to-left).
*/
function computeIsinLuhnSum(code: string, endIndex: number, startDouble: boolean): number {
let sum = 0;
let doubleNext = startDouble;
for (let i = endIndex; i >= 0; i--) {
const ch = code.charCodeAt(i);
if (ch >= CODE_0 && ch <= CODE_9) {
sum += luhnStep(ch - CODE_0, doubleNext);
doubleNext = !doubleNext;
} else {
const val = ch - 55; // 'A' (65) -> 10 .. 'Z' (90) -> 35
const units = val % 10;
const tens = (val - units) / 10;
sum += luhnStep(units, doubleNext);
doubleNext = !doubleNext;
sum += luhnStep(tens, doubleNext);
doubleNext = !doubleNext;
}
}
return sum;
}
function computeIsinCheckDigit(base11: string): number {
const sum = computeIsinLuhnSum(base11, 10, true);
return (10 - (sum % 10)) % 10;
}
/** Validates an ISO 6166 ISIN (12 chars, `[A-Z]{2}[A-Z0-9]{9}[0-9]`, Luhn check digit). */
export function isValidIsin(isin: string | null | undefined): boolean {
const normalized = normalizeCode(isin);
if (normalized === null || normalized.length !== 12) {
return false;
}
if (!isAsciiUpper(normalized.charCodeAt(0)) || !isAsciiUpper(normalized.charCodeAt(1))) {
return false;
}
for (let i = 2; i < 11; i++) {
if (!isAsciiAlnum(normalized.charCodeAt(i))) {
return false;
}
}
if (!isAsciiDigit(normalized.charCodeAt(11))) {
return false;
}
return computeIsinLuhnSum(normalized, 11, false) % 10 === 0;
}
/** Validates an ANSI X9.6 CUSIP (9 chars, mod-10 check digit including `*`, `@`, `#` = 36..38). */
export function isValidCusip(cusip: string | null | undefined): boolean {
const normalized = normalizeCode(cusip);
if (normalized === null || normalized.length !== 9) {
return false;
}
const checkCode = normalized.charCodeAt(8);
if (!isAsciiDigit(checkCode)) {
return false;
}
let sum = 0;
for (let i = 0; i < 8; i++) {
const ch = normalized.charCodeAt(i);
let val: number;
if (ch >= CODE_0 && ch <= CODE_9) {
val = ch - CODE_0;
} else if (ch >= CODE_A && ch <= CODE_Z) {
val = ch - 55;
} else if (ch === CODE_STAR) {
val = 36;
} else if (ch === CODE_AT) {
val = 37;
} else if (ch === CODE_HASH) {
val = 38;
} else {
return false;
}
if ((i & 1) === 1) {
val *= 2;
}
sum += Math.floor(val / 10) + (val % 10);
}
const expected = (10 - (sum % 10)) % 10;
return checkCode - CODE_0 === expected;
}
/**
* Derives an ISO 6166 ISIN from a valid 9-character US or CA CUSIP.
* Returns `null` if the CUSIP is invalid, contains ISO-6166-disallowed characters (`*`, `@`, `#`),
* or if the country is not `'US'` or `'CA'`.
*/
export function cusipToIsin(
cusip: string | null | undefined,
country: NorthAmericaCountry
): string | null {
const normalizedCountry = normalizeCode(country);
if (!isNorthAmericaCountry(normalizedCountry)) {
return null;
}
const normalizedCusip = normalizeCode(cusip);
if (normalizedCusip === null || !isValidCusip(normalizedCusip)) {
return null;
}
// ISO 6166 forbids `*`, `@`, `#` in the 9-character NSIN portion.
for (let i = 0; i < 9; i++) {
if (!isAsciiAlnum(normalizedCusip.charCodeAt(i))) {
return null;
}
}
const base11 = normalizedCountry + normalizedCusip;
return base11 + String(computeIsinCheckDigit(base11));
}
/**
* Resolves an ISIN without throwing on malformed input:
* 1. Returns the ISIN directly when ISO 6166 Luhn-valid.
* 2. Otherwise derives an ISIN from an explicit valid CUSIP (using `country` or a US/CA ISIN prefix).
* 3. Otherwise attempts recovery from the 9-char CUSIP embedded in a 12-char US/CA ISIN.
*/
export function resolveIsin(input: ResolveIsinInput | null | undefined): ResolveIsinResult {
if (input === null || input === undefined || typeof input !== 'object') {
return { isin: null, reason: 'missing_identifiers' };
}
const isin = normalizeCode(input.isin);
const cusip = normalizeCode(input.cusip);
const country = normalizeCode(input.country);
if (isin === null && cusip === null) {
return { isin: null, reason: 'missing_identifiers' };
}
if (isin !== null && isValidIsin(isin)) {
return { isin, source: 'isin' };
}
if (cusip !== null) {
if (isValidCusip(cusip)) {
if (country !== null) {
if (!isNorthAmericaCountry(country)) {
return { isin: null, reason: 'unsupported_country_for_cusip' };
}
const derived = cusipToIsin(cusip, country);
if (derived !== null) {
return { isin: derived, source: 'cusip_derived' };
}
} else {
const isinPrefix = isin !== null && isin.length >= 2 ? isin.slice(0, 2) : null;
if (!isNorthAmericaCountry(isinPrefix)) {
return { isin: null, reason: 'unsupported_country_for_cusip' };
}
const derived = cusipToIsin(cusip, isinPrefix);
if (derived !== null) {
return { isin: derived, source: 'cusip_derived' };
}
}
} else if (isin === null) {
return { isin: null, reason: 'invalid_cusip' };
}
}
if (isin !== null && isin.length === 12) {
const isinPrefix = isin.slice(0, 2);
if (isNorthAmericaCountry(isinPrefix) && (country === null || country === isinPrefix)) {
const derived = cusipToIsin(isin.slice(2, 11), isinPrefix);
if (derived !== null) {
return { isin: derived, source: 'cusip_derived' };
}
}
}
if (isin !== null) {
return { isin: null, reason: 'invalid_isin_and_no_valid_cusip' };
}
return { isin: null, reason: 'invalid_cusip' };
}

View file

@ -7,10 +7,14 @@ export interface ProviderSymbolDocument {
exchange?: string | null;
exchange_id?: string | null;
Exchange?: string | null;
/** IB execution venue identifier; preserved verbatim rather than mapped to a listing MIC. */
exchangeId?: string | null;
companyName?: string | null;
name?: string | null;
company_name?: string | null;
Name?: string | null;
/** IB security description fallback. */
description?: string | null;
countryCode?: string | null;
country_code?: string | null;
Country?: string | null;
@ -34,7 +38,11 @@ export interface ProviderSymbol {
export function normalizeProviderSymbol(document: ProviderSymbolDocument): ProviderSymbol | null {
const symbol = document.symbol || document.code || document.Code;
const exchangeCode =
document.exchangeCode || document.exchange || document.exchange_id || document.Exchange;
document.exchangeCode ||
document.exchange ||
document.exchange_id ||
document.Exchange ||
document.exchangeId;
if (!symbol || !exchangeCode) {
return null;
}
@ -43,7 +51,12 @@ export function normalizeProviderSymbol(document: ProviderSymbolDocument): Provi
exchangeCode,
providerSymbol: document.qmSearchCode || document.eodSearchCode || symbol,
companyName:
document.companyName || document.name || document.company_name || document.Name || null,
document.companyName ||
document.name ||
document.company_name ||
document.Name ||
document.description ||
null,
country: document.countryCode || document.country_code || document.Country || null,
currency: document.currency || document.Currency || null,
};

View file

@ -0,0 +1,113 @@
export type TickerSource = 'eod' | 'qm' | 'ib' | 'ceo';
export interface ParsedTicker {
tickerRoot: string;
classSuffix: string;
}
const CODE_TAB = 9;
const CODE_SPACE = 32;
const CODE_DASH = 45;
const CODE_DOT = 46;
const CODE_SLASH = 47;
function isWhitespace(code: number): boolean {
return code === CODE_SPACE || code === CODE_TAB;
}
function isSeparator(code: number): boolean {
return (
code === CODE_DOT ||
code === CODE_DASH ||
code === CODE_SPACE ||
code === CODE_TAB ||
code === CODE_SLASH
);
}
function findNextSeparator(str: string, start: number): number {
for (let i = start; i < str.length; i++) {
if (isSeparator(str.charCodeAt(i))) {
return i;
}
}
return -1;
}
/**
* Parses a raw provider ticker into a canonical uppercase `(tickerRoot, classSuffix)` pair.
* Strips embedded `.TO` / `.V` venue suffixes only when `source === 'ceo'`.
* Plain tickers return `classSuffix: ''`; empty or malformed inputs return `null`.
*/
export function parseTicker(
raw: string | null | undefined,
source: TickerSource
): ParsedTicker | null {
if (typeof raw !== 'string') {
return null;
}
let s = raw.trim().toUpperCase();
if (s.length === 0) {
return null;
}
if (source === 'ceo') {
if (s.length > 3 && s.endsWith('.TO')) {
s = s.slice(0, -3).trimEnd();
} else if (s.length > 2 && s.endsWith('.V')) {
s = s.slice(0, -2).trimEnd();
}
if (s.length === 0) {
return null;
}
}
const firstSep = findNextSeparator(s, 0);
if (firstSep === -1) {
return { tickerRoot: s, classSuffix: '' };
}
if (firstSep === 0) {
return null;
}
const tickerRoot = s.slice(0, firstSep);
let pos = firstSep + 1;
if (isWhitespace(s.charCodeAt(firstSep))) {
while (pos < s.length && isWhitespace(s.charCodeAt(pos))) {
pos++;
}
}
if (pos >= s.length || isSeparator(s.charCodeAt(pos))) {
return null;
}
const secondSep = findNextSeparator(s, pos);
if (secondSep === -1) {
return { tickerRoot, classSuffix: s.slice(pos) };
}
let classSuffix = s.slice(pos, secondSep);
pos = secondSep;
while (pos < s.length) {
const sepCode = s.charCodeAt(pos);
pos++;
if (isWhitespace(sepCode)) {
while (pos < s.length && isWhitespace(s.charCodeAt(pos))) {
pos++;
}
}
if (pos >= s.length || isSeparator(s.charCodeAt(pos))) {
return null;
}
const nextSep = findNextSeparator(s, pos);
if (nextSep === -1) {
classSuffix += '.' + s.slice(pos);
break;
}
classSuffix += '.' + s.slice(pos, nextSep);
pos = nextSep;
}
return { tickerRoot, classSuffix };
}

View file

@ -78,6 +78,23 @@ const variants: {
currency: null,
},
},
{
name: 'IB exchangeId and description fallbacks',
input: {
symbol: 'SHOP',
exchangeId: 'AEQLIT',
description: 'SHOPIFY INC - CLASS A',
currency: 'CAD',
},
expected: {
symbol: 'SHOP',
exchangeCode: 'AEQLIT',
providerSymbol: 'SHOP',
companyName: 'SHOPIFY INC - CLASS A',
country: null,
currency: 'CAD',
},
},
];
test.each(variants)(
@ -97,12 +114,14 @@ test('mixed and empty field variants preserve historical precedence', () => {
exchange: 'SECOND_EXCHANGE',
exchange_id: 'THIRD_EXCHANGE',
Exchange: 'FOURTH_EXCHANGE',
exchangeId: 'FIFTH_IB_EXCHANGE',
qmSearchCode: 'FIRST_SEARCH',
eodSearchCode: 'SECOND_SEARCH',
companyName: 'FIRST_NAME',
name: 'SECOND_NAME',
company_name: 'THIRD_NAME',
Name: 'FOURTH_NAME',
description: 'FIFTH_IB_DESCRIPTION',
countryCode: 'CA',
country_code: 'US',
Country: 'GB',
@ -126,12 +145,14 @@ test('mixed and empty field variants preserve historical precedence', () => {
exchange: '',
exchange_id: '',
Exchange: 'TO',
exchangeId: 'AEQLIT',
qmSearchCode: '',
eodSearchCode: 'RY.TO',
companyName: '',
name: '',
company_name: '',
Name: 'Royal Bank',
description: 'ROYAL BANK OF CANADA',
countryCode: '',
country_code: '',
Country: 'CA',
@ -139,6 +160,22 @@ test('mixed and empty field variants preserve historical precedence', () => {
Currency: 'CAD',
})
).toEqual(variants[1]!.expected);
expect(
normalizeProviderSymbol({
symbol: 'SHOP',
exchangeCode: null,
exchange: '',
exchange_id: null,
Exchange: '',
exchangeId: 'AEQLIT',
companyName: '',
name: null,
company_name: '',
Name: null,
description: 'SHOPIFY INC - CLASS A',
currency: 'CAD',
})
).toEqual(variants[4]!.expected);
});
test('incomplete symbol identities remain skipped instead of manufacturing a mapping', () => {

View file

@ -0,0 +1,194 @@
import { describe, expect, test } from 'bun:test';
import {
cusipToIsin,
isValidCusip,
isValidIsin,
resolveIsin,
type NorthAmericaCountry,
} from '../../apps/stock/data-pipeline/src/normalization/identifiers';
describe('isValidIsin', () => {
test('accepts valid US, CA, and international ISINs including trimmed lowercase', () => {
expect(isValidIsin('US0378331005')).toBe(true); // Apple
expect(isValidIsin('CA7800871021')).toBe(true); // RBC
expect(isValidIsin('CA82509L1076')).toBe(true); // Shopify
expect(isValidIsin('CA8131371061')).toBe(true); // Second Cup (SCU.UN)
expect(isValidIsin('AU0000XVGZA3')).toBe(true); // Non-US/CA
expect(isValidIsin(' us0378331005 ')).toBe(true);
});
test('rejects corrupted, synthetic, wrong-length, and malformed inputs without throwing', () => {
// Under true ISO 6166, the check digit for CA813139106 is 9 (so ...64 and ...62 are both invalid).
expect(isValidIsin('CA8131391064')).toBe(false);
expect(isValidIsin('CA8131391062')).toBe(false);
expect(isValidIsin('CATSETEST001')).toBe(false);
expect(isValidIsin('CA00149WBAD4')).toBe(false);
// Wrong lengths
expect(isValidIsin('US037833100')).toBe(false);
expect(isValidIsin('US03783310050')).toBe(false);
// Structural / character-class violations
expect(isValidIsin('120378331005')).toBe(false);
expect(isValidIsin('US037833100X')).toBe(false);
expect(isValidIsin(' bad-isin! ')).toBe(false);
expect(isValidIsin(' catsetest001 ')).toBe(false);
// Empty and nullish
expect(isValidIsin('')).toBe(false);
expect(isValidIsin(' ')).toBe(false);
expect(isValidIsin(null)).toBe(false);
expect(isValidIsin(undefined)).toBe(false);
});
});
describe('isValidCusip', () => {
test('accepts valid numeric, alphanumeric, and special-char ANSI X9.6 CUSIPs', () => {
expect(isValidCusip('037833100')).toBe(true); // Apple
expect(isValidCusip('780087102')).toBe(true); // RBC
expect(isValidCusip('82509L107')).toBe(true); // Shopify
expect(isValidCusip('813137106')).toBe(true); // Second Cup
expect(isValidCusip('12345*@#7')).toBe(true); // ANSI X9.6 special chars *, @, # = 36..38
expect(isValidCusip(' 82509l107 ')).toBe(true);
});
test('rejects invalid check digits, wrong lengths, and malformed inputs without throwing', () => {
// Under true ANSI X9.6, valid check digit for 81313910 is 2, not 6.
expect(isValidCusip('813139106')).toBe(false);
expect(isValidCusip('037833101')).toBe(false);
expect(isValidCusip('82509L108')).toBe(false);
// Wrong lengths
expect(isValidCusip('03783310')).toBe(false);
expect(isValidCusip('0378331000')).toBe(false);
// Non-digit check char and illegal punctuation
expect(isValidCusip('03783310A')).toBe(false);
expect(isValidCusip('0378331!0')).toBe(false);
// Empty and nullish
expect(isValidCusip('')).toBe(false);
expect(isValidCusip(' ')).toBe(false);
expect(isValidCusip(null)).toBe(false);
expect(isValidCusip(undefined)).toBe(false);
});
});
describe('cusipToIsin', () => {
test('derives valid US and CA ISINs from valid CUSIPs', () => {
expect(cusipToIsin('037833100', 'US')).toBe('US0378331005');
expect(cusipToIsin('780087102', 'CA')).toBe('CA7800871021');
expect(cusipToIsin('82509L107', 'CA')).toBe('CA82509L1076');
expect(cusipToIsin('813137106', 'CA')).toBe('CA8131371061');
expect(cusipToIsin(' 82509l107 ', 'CA')).toBe('CA82509L1076');
});
test('returns null for invalid CUSIPs, special-char CUSIPs, and unsupported countries', () => {
expect(cusipToIsin('813139106', 'CA')).toBeNull();
expect(cusipToIsin('037833101', 'US')).toBeNull();
expect(cusipToIsin('', 'US')).toBeNull();
expect(cusipToIsin(null, 'CA')).toBeNull();
// Valid ANSI X9.6 CUSIP, but *, @, # are forbidden in ISO 6166 ISINs.
expect(cusipToIsin('12345*@#7', 'US')).toBeNull();
expect(cusipToIsin('037833100', 'GB' as unknown as NorthAmericaCountry)).toBeNull();
});
});
describe('resolveIsin', () => {
test('returns valid ISIN directly with source isin', () => {
expect(resolveIsin({ isin: 'US0378331005' })).toEqual({
isin: 'US0378331005',
source: 'isin',
});
expect(resolveIsin({ isin: ' ca7800871021 ' })).toEqual({
isin: 'CA7800871021',
source: 'isin',
});
});
test('recovers checksum-corrupted US/CA ISINs from valid embedded CUSIPs', () => {
expect(resolveIsin({ isin: 'CA7800871029' })).toEqual({
isin: 'CA7800871021',
source: 'cusip_derived',
});
expect(resolveIsin({ isin: 'CA82509L1070' })).toEqual({
isin: 'CA82509L1076',
source: 'cusip_derived',
});
expect(resolveIsin({ isin: 'CA8131371062' })).toEqual({
isin: 'CA8131371061',
source: 'cusip_derived',
});
expect(resolveIsin({ isin: 'US0378331009' })).toEqual({
isin: 'US0378331005',
source: 'cusip_derived',
});
});
test('derives ISIN from explicit valid CUSIP and country when ISIN is missing or corrupted', () => {
expect(resolveIsin({ cusip: '037833100', country: 'US' })).toEqual({
isin: 'US0378331005',
source: 'cusip_derived',
});
expect(resolveIsin({ isin: 'CA8131391062', cusip: '813137106', country: 'CA' })).toEqual({
isin: 'CA8131371061',
source: 'cusip_derived',
});
expect(resolveIsin({ isin: 'CA8131391062', cusip: '813137106' })).toEqual({
isin: 'CA8131371061',
source: 'cusip_derived',
});
});
test('rejects unrecoverable, contradictory-country, unsupported-country, and empty inputs without throwing', () => {
expect(resolveIsin({ isin: 'CATSETEST001' })).toEqual({
isin: null,
reason: 'invalid_isin_and_no_valid_cusip',
});
expect(resolveIsin({ isin: 'CA00149WBAD4' })).toEqual({
isin: null,
reason: 'invalid_isin_and_no_valid_cusip',
});
expect(resolveIsin({ isin: 'CA8131391062' })).toEqual({
isin: null,
reason: 'invalid_isin_and_no_valid_cusip',
});
// Explicit country contradicts embedded ISIN country prefix
expect(resolveIsin({ isin: 'CA7800871029', country: 'US' })).toEqual({
isin: null,
reason: 'invalid_isin_and_no_valid_cusip',
});
expect(resolveIsin({ cusip: '037833100', country: 'GB' })).toEqual({
isin: null,
reason: 'unsupported_country_for_cusip',
});
expect(resolveIsin({ cusip: '037833100' })).toEqual({
isin: null,
reason: 'unsupported_country_for_cusip',
});
expect(resolveIsin({ cusip: '813139106', country: 'CA' })).toEqual({
isin: null,
reason: 'invalid_cusip',
});
expect(resolveIsin({ cusip: '12345*@#7', country: 'US' })).toEqual({
isin: null,
reason: 'invalid_cusip',
});
expect(resolveIsin({})).toEqual({
isin: null,
reason: 'missing_identifiers',
});
expect(resolveIsin({ isin: ' ', cusip: '' })).toEqual({
isin: null,
reason: 'missing_identifiers',
});
expect(resolveIsin(null)).toEqual({
isin: null,
reason: 'missing_identifiers',
});
expect(resolveIsin(undefined)).toEqual({
isin: null,
reason: 'missing_identifiers',
});
});
});

View file

@ -0,0 +1,138 @@
import { describe, expect, test } from 'bun:test';
import {
resolveIsin,
type ResolveIsinInput,
} from '../../apps/stock/data-pipeline/src/normalization/identifiers';
import {
parseTicker,
type TickerSource,
} from '../../apps/stock/data-pipeline/src/normalization/ticker';
const ALL_SOURCES: readonly TickerSource[] = ['eod', 'qm', 'ib', 'ceo'];
const NON_CEO_SOURCES: readonly TickerSource[] = ['eod', 'qm', 'ib'];
describe('parseTicker', () => {
test('canonicalizes separator variants across all sources', () => {
for (const source of ALL_SOURCES) {
expect(parseTicker('AAA-P', source)).toEqual({ tickerRoot: 'AAA', classSuffix: 'P' });
expect(parseTicker('AAA.P', source)).toEqual({ tickerRoot: 'AAA', classSuffix: 'P' });
expect(parseTicker('AACT U', source)).toEqual({ tickerRoot: 'AACT', classSuffix: 'U' });
expect(parseTicker('AACT U', source)).toEqual({ tickerRoot: 'AACT', classSuffix: 'U' });
expect(parseTicker('AACT.U', source)).toEqual({ tickerRoot: 'AACT', classSuffix: 'U' });
expect(parseTicker('SCU.UN', source)).toEqual({ tickerRoot: 'SCU', classSuffix: 'UN' });
expect(parseTicker('RY.PR.A', source)).toEqual({ tickerRoot: 'RY', classSuffix: 'PR.A' });
expect(parseTicker('RY-PR-A', source)).toEqual({ tickerRoot: 'RY', classSuffix: 'PR.A' });
expect(parseTicker('RY PR A', source)).toEqual({ tickerRoot: 'RY', classSuffix: 'PR.A' });
}
});
test('parses plain tickers with empty classSuffix and uppercases trimmed input', () => {
expect(parseTicker('AAPL', 'eod')).toEqual({ tickerRoot: 'AAPL', classSuffix: '' });
expect(parseTicker(' shop ', 'qm')).toEqual({ tickerRoot: 'SHOP', classSuffix: '' });
expect(parseTicker('RY', 'ib')).toEqual({ tickerRoot: 'RY', classSuffix: '' });
});
test('strips embedded .TO and .V venue suffixes only for ceo source', () => {
expect(parseTicker('SHOP.TO', 'ceo')).toEqual({ tickerRoot: 'SHOP', classSuffix: '' });
expect(parseTicker('ABC.V', 'ceo')).toEqual({ tickerRoot: 'ABC', classSuffix: '' });
expect(parseTicker('SCU.UN.TO', 'ceo')).toEqual({ tickerRoot: 'SCU', classSuffix: 'UN' });
expect(parseTicker('XYZ.WT.V', 'ceo')).toEqual({ tickerRoot: 'XYZ', classSuffix: 'WT' });
expect(parseTicker('ry.pr.a.to', 'ceo')).toEqual({ tickerRoot: 'RY', classSuffix: 'PR.A' });
});
test('does not strip .TO or .V as venue suffixes for non-ceo sources', () => {
for (const source of NON_CEO_SOURCES) {
expect(parseTicker('ABC.V', source)).toEqual({ tickerRoot: 'ABC', classSuffix: 'V' });
expect(parseTicker('SHOP.TO', source)).toEqual({ tickerRoot: 'SHOP', classSuffix: 'TO' });
}
});
test('returns null for empty, whitespace, and malformed inputs without throwing', () => {
const invalidInputs: (string | null | undefined)[] = [
'',
' ',
'.',
'.AAPL',
'-A',
'AAPL.',
'AAPL-',
'A..B',
'A--B',
'RY.PR.',
'RY-PR--A',
null,
undefined,
];
for (const source of ALL_SOURCES) {
for (const raw of invalidInputs) {
expect(parseTicker(raw, source)).toBeNull();
}
}
expect(parseTicker('.TO', 'ceo')).toBeNull();
expect(parseTicker('.V', 'ceo')).toBeNull();
expect(parseTicker(' .TO', 'ceo')).toBeNull();
expect(parseTicker('..TO', 'ceo')).toBeNull();
});
test('completes 100,000 resolveIsin + parseTicker calls in under 500 ms', () => {
const isinCorpus: readonly ResolveIsinInput[] = [
{ isin: 'US0378331005' },
{ isin: 'CA7800871029' },
{ isin: 'CA82509L1070' },
{ isin: 'CATSETEST001' },
{ cusip: '037833100', country: 'US' },
{ isin: 'CA8131391062', cusip: '813137106', country: 'CA' },
{ isin: 'CA00149WBAD4' },
{ isin: ' us0378331005 ' },
];
const tickerCorpus: readonly { raw: string; source: TickerSource }[] = [
{ raw: 'AAPL', source: 'eod' },
{ raw: 'AAA-P', source: 'qm' },
{ raw: 'AACT U', source: 'ib' },
{ raw: 'SCU.UN.TO', source: 'ceo' },
{ raw: 'SHOP.TO', source: 'ceo' },
{ raw: 'ABC.V', source: 'eod' },
{ raw: 'RY-PR-A', source: 'qm' },
{ raw: ' shop ', source: 'ib' },
];
const corpusLen = isinCorpus.length;
let sink = 0;
// Warm up JIT
for (let i = 0; i < 1_000; i++) {
const idx = i & 7;
const isinResult = resolveIsin(isinCorpus[idx]);
const tickerEntry = tickerCorpus[idx]!;
const tickerResult = parseTicker(tickerEntry.raw, tickerEntry.source);
if (isinResult.isin !== null) {
sink++;
}
if (tickerResult !== null) {
sink += tickerResult.tickerRoot.length;
}
}
const iterations = 100_000;
const startMs = performance.now();
for (let i = 0; i < iterations; i++) {
const idx = i % corpusLen;
const isinResult = resolveIsin(isinCorpus[idx]);
const tickerEntry = tickerCorpus[idx]!;
const tickerResult = parseTicker(tickerEntry.raw, tickerEntry.source);
if (isinResult.isin !== null) {
sink++;
}
if (tickerResult !== null) {
sink += tickerResult.tickerRoot.length;
}
}
const elapsedMs = performance.now() - startMs;
process.stdout.write(
`[bench] 100,000 resolveIsin + parseTicker calls: ${elapsedMs.toFixed(2)} ms (sink=${sink})\n`
);
expect(sink).toBeGreaterThan(0);
expect(elapsedMs).toBeLessThan(500);
});
});