305 lines
11 KiB
TypeScript
305 lines
11 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
|
import {
|
|
cusipToIsin,
|
|
isValidCusip,
|
|
isValidIsin,
|
|
resolveIsin,
|
|
type NorthAmericaCountry,
|
|
} from '../../apps/stock/data-pipeline/src/normalization/identifiers';
|
|
import {
|
|
parseTicker,
|
|
type TickerSource,
|
|
} from '../../apps/stock/data-pipeline/src/normalization/ticker';
|
|
|
|
/*
|
|
* QA property tests for Pass 2 normalization. The check-digit oracles below are written
|
|
* independently of the implementation (string expansion + textbook Luhn / ANSI X9.6), so
|
|
* agreement over a seeded random corpus verifies the allocation-light charCodeAt loops.
|
|
*/
|
|
|
|
const ALNUM = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
|
const LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
|
const CUSIP_CHARS = ALNUM + '*@#';
|
|
|
|
/** Mulberry32: tiny deterministic PRNG so every run sees the same corpus. */
|
|
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 pick(rng: () => number, alphabet: string): string {
|
|
return alphabet.charAt(Math.floor(rng() * alphabet.length));
|
|
}
|
|
|
|
function randomString(rng: () => number, alphabet: string, length: number): string {
|
|
let out = '';
|
|
for (let i = 0; i < length; i++) {
|
|
out += pick(rng, alphabet);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** Reference ISO 6166: expand letters to two digits, then standard Luhn over the digit string. */
|
|
function referenceIsinCheckDigit(base11: string): number {
|
|
let digits = '';
|
|
for (const ch of base11) {
|
|
digits += ALNUM.indexOf(ch).toString();
|
|
}
|
|
let sum = 0;
|
|
// Rightmost digit of the payload is doubled because the check digit will sit to its right.
|
|
for (let i = digits.length - 1, pos = 0; i >= 0; i--, pos++) {
|
|
let d = Number(digits[i]);
|
|
if (pos % 2 === 0) {
|
|
d *= 2;
|
|
if (d > 9) {
|
|
d -= 9;
|
|
}
|
|
}
|
|
sum += d;
|
|
}
|
|
return (10 - (sum % 10)) % 10;
|
|
}
|
|
|
|
/** Reference ANSI X9.6 CUSIP check digit (textbook pseudocode, 1-based even positions doubled). */
|
|
function referenceCusipCheckDigit(base8: string): number {
|
|
let sum = 0;
|
|
for (let i = 0; i < 8; i++) {
|
|
let v = CUSIP_CHARS.indexOf(base8.charAt(i));
|
|
if ((i + 1) % 2 === 0) {
|
|
v *= 2;
|
|
}
|
|
sum += Math.floor(v / 10) + (v % 10);
|
|
}
|
|
return (10 - (sum % 10)) % 10;
|
|
}
|
|
|
|
describe('identifier check digits agree with independent reference oracles', () => {
|
|
test('reference oracles reproduce published security identifiers', () => {
|
|
expect(referenceIsinCheckDigit('US037833100')).toBe(5); // Apple
|
|
expect(referenceIsinCheckDigit('CA780087102')).toBe(1); // RBC
|
|
expect(referenceIsinCheckDigit('AU0000XVGZA')).toBe(3);
|
|
expect(referenceCusipCheckDigit('03783310')).toBe(0); // Apple
|
|
expect(referenceCusipCheckDigit('82509L10')).toBe(7); // Shopify
|
|
// Confirms the approved spec correction: the design-doc example vectors are not checksum-valid.
|
|
expect(referenceCusipCheckDigit('81313910')).toBe(2);
|
|
expect(referenceIsinCheckDigit('CA813139106')).toBe(9);
|
|
});
|
|
|
|
test('isValidIsin accepts exactly the reference check digit for 5,000 seeded random bases', () => {
|
|
const rng = makeRng(0x15111);
|
|
for (let n = 0; n < 5_000; n++) {
|
|
const base11 = randomString(rng, LETTERS, 2) + randomString(rng, ALNUM, 9);
|
|
const expected = referenceIsinCheckDigit(base11);
|
|
for (let d = 0; d <= 9; d++) {
|
|
expect(isValidIsin(base11 + String(d))).toBe(d === expected);
|
|
}
|
|
}
|
|
});
|
|
|
|
test('isValidCusip accepts exactly the reference check digit for 5,000 seeded random bases', () => {
|
|
const rng = makeRng(0xc051);
|
|
for (let n = 0; n < 5_000; n++) {
|
|
const base8 = randomString(rng, CUSIP_CHARS, 8);
|
|
const expected = referenceCusipCheckDigit(base8);
|
|
for (let d = 0; d <= 9; d++) {
|
|
expect(isValidCusip(base8 + String(d))).toBe(d === expected);
|
|
}
|
|
}
|
|
});
|
|
|
|
test('cusipToIsin always emits a checksum-valid ISIN that embeds the CUSIP and country', () => {
|
|
const rng = makeRng(0xca05);
|
|
const countries: readonly NorthAmericaCountry[] = ['US', 'CA'];
|
|
for (let n = 0; n < 2_000; n++) {
|
|
const base8 = randomString(rng, ALNUM, 8);
|
|
const cusip = base8 + String(referenceCusipCheckDigit(base8));
|
|
const country = countries[n & 1]!;
|
|
const isin = cusipToIsin(cusip, country);
|
|
expect(isin).toBe(country + cusip + String(referenceIsinCheckDigit(country + cusip)));
|
|
expect(isValidIsin(isin)).toBe(true);
|
|
}
|
|
});
|
|
|
|
test('every single-character substitution of a valid ISIN body is detected or recovered', () => {
|
|
// Luhn detects all single-digit substitutions; resolveIsin must never pass one through as 'isin'.
|
|
const valid = 'US0378331005';
|
|
for (let i = 2; i < 11; i++) {
|
|
for (const ch of '0123456789') {
|
|
if (ch === valid.charAt(i)) {
|
|
continue;
|
|
}
|
|
const mutated = valid.slice(0, i) + ch + valid.slice(i + 1);
|
|
expect(isValidIsin(mutated)).toBe(false);
|
|
const result = resolveIsin({ isin: mutated });
|
|
expect(
|
|
result.isin === null || ('source' in result && result.source === 'cusip_derived')
|
|
).toBe(true);
|
|
}
|
|
}
|
|
});
|
|
|
|
test('every single-digit substitution of a valid CUSIP is rejected', () => {
|
|
const valid = '037833100';
|
|
for (let i = 0; i < 9; i++) {
|
|
for (const ch of '0123456789') {
|
|
if (ch === valid.charAt(i)) {
|
|
continue;
|
|
}
|
|
expect(isValidCusip(valid.slice(0, i) + ch + valid.slice(i + 1))).toBe(false);
|
|
}
|
|
}
|
|
});
|
|
});
|
|
|
|
describe('resolveIsin edge cases beyond the plan list', () => {
|
|
test('a valid ISIN wins even when a conflicting country or CUSIP is supplied', () => {
|
|
expect(resolveIsin({ isin: 'US0378331005', country: 'CA' })).toEqual({
|
|
isin: 'US0378331005',
|
|
source: 'isin',
|
|
});
|
|
expect(resolveIsin({ isin: 'AU0000XVGZA3', cusip: '037833100', country: 'US' })).toEqual({
|
|
isin: 'AU0000XVGZA3',
|
|
source: 'isin',
|
|
});
|
|
});
|
|
|
|
test('an invalid explicit CUSIP falls back to the valid CUSIP embedded in the ISIN', () => {
|
|
expect(resolveIsin({ isin: 'CA7800871029', cusip: '037833101' })).toEqual({
|
|
isin: 'CA7800871021',
|
|
source: 'cusip_derived',
|
|
});
|
|
});
|
|
|
|
test('a corrupted non-US/CA ISIN is rejected rather than recovered', () => {
|
|
expect(resolveIsin({ isin: 'AU0000XVGZA4' })).toEqual({
|
|
isin: null,
|
|
reason: 'invalid_isin_and_no_valid_cusip',
|
|
});
|
|
});
|
|
|
|
test('lowercase country codes are normalized before the conflict check', () => {
|
|
expect(resolveIsin({ isin: 'ca7800871029', country: 'ca' })).toEqual({
|
|
isin: 'CA7800871021',
|
|
source: 'cusip_derived',
|
|
});
|
|
expect(resolveIsin({ isin: 'ca7800871029', cusip: '780087102', country: 'us' })).toEqual({
|
|
isin: null,
|
|
reason: 'invalid_isin_and_no_valid_cusip',
|
|
});
|
|
});
|
|
|
|
test('non-string field values are treated as missing without throwing', () => {
|
|
const malformed = { isin: 123, cusip: {}, country: [] } as unknown as Parameters<
|
|
typeof resolveIsin
|
|
>[0];
|
|
expect(resolveIsin(malformed)).toEqual({ isin: null, reason: 'missing_identifiers' });
|
|
expect(resolveIsin('US0378331005' as unknown as Parameters<typeof resolveIsin>[0])).toEqual({
|
|
isin: null,
|
|
reason: 'missing_identifiers',
|
|
});
|
|
});
|
|
|
|
test('seeded random garbage never throws and always returns a well-formed result', () => {
|
|
const rng = makeRng(0x6a7b);
|
|
const alphabet = ALNUM + 'abcxyz *@#-.!\t';
|
|
for (let n = 0; n < 5_000; n++) {
|
|
const input = {
|
|
isin: rng() < 0.1 ? null : randomString(rng, alphabet, Math.floor(rng() * 15)),
|
|
cusip: rng() < 0.5 ? null : randomString(rng, alphabet, Math.floor(rng() * 11)),
|
|
country: rng() < 0.5 ? null : randomString(rng, 'UCSAGB', 2),
|
|
};
|
|
const result = resolveIsin(input);
|
|
if (result.isin === null) {
|
|
expect('reason' in result).toBe(true);
|
|
} else {
|
|
expect(isValidIsin(result.isin)).toBe(true);
|
|
expect(result.isin).toBe(result.isin.trim().toUpperCase());
|
|
}
|
|
}
|
|
});
|
|
});
|
|
|
|
describe('parseTicker invariants', () => {
|
|
const SOURCES: readonly TickerSource[] = ['eod', 'qm', 'ib', 'ceo'];
|
|
const SEPARATORS = ['.', '-', ' ', '/', '. ', '- ', '\t'];
|
|
|
|
test('slash-separated share classes canonicalize like dot and dash forms', () => {
|
|
for (const source of SOURCES) {
|
|
expect(parseTicker('BRK/B', source)).toEqual({ tickerRoot: 'BRK', classSuffix: 'B' });
|
|
expect(parseTicker('BRK.B', source)).toEqual(parseTicker('BRK/B', source));
|
|
}
|
|
});
|
|
|
|
test('ceo strips only one trailing venue suffix and keeps -V dash class suffixes', () => {
|
|
expect(parseTicker('ABC.TO.V', 'ceo')).toEqual({ tickerRoot: 'ABC', classSuffix: 'TO' });
|
|
expect(parseTicker('ABC-V', 'ceo')).toEqual({ tickerRoot: 'ABC', classSuffix: 'V' });
|
|
expect(parseTicker('V.TO', 'ceo')).toEqual({ tickerRoot: 'V', classSuffix: '' });
|
|
expect(parseTicker('TO', 'ceo')).toEqual({ tickerRoot: 'TO', classSuffix: '' });
|
|
expect(parseTicker('V', 'ceo')).toEqual({ tickerRoot: 'V', classSuffix: '' });
|
|
});
|
|
|
|
test('seeded random separator variants of the same parts all parse to one canonical pair', () => {
|
|
const rng = makeRng(0x71c4);
|
|
for (let n = 0; n < 2_000; n++) {
|
|
const root = randomString(rng, LETTERS, 1 + Math.floor(rng() * 5));
|
|
const partCount = Math.floor(rng() * 3);
|
|
const parts: string[] = [];
|
|
for (let p = 0; p < partCount; p++) {
|
|
parts.push(randomString(rng, ALNUM, 1 + Math.floor(rng() * 3)));
|
|
}
|
|
const expected = { tickerRoot: root, classSuffix: parts.join('.') };
|
|
let raw = root;
|
|
for (const part of parts) {
|
|
raw += SEPARATORS[Math.floor(rng() * SEPARATORS.length)]! + part;
|
|
}
|
|
const source = SOURCES[n & 3]!;
|
|
// eod/qm/ib must never treat TO/V parts as venues; ceo would, so only compare when unaffected.
|
|
const last = parts[parts.length - 1];
|
|
const ceoWouldStrip = source === 'ceo' && (last === 'TO' || last === 'V');
|
|
if (!ceoWouldStrip) {
|
|
expect(parseTicker(raw.toLowerCase(), source)).toEqual(expected);
|
|
}
|
|
}
|
|
});
|
|
|
|
test('parsing is idempotent on its own canonical output', () => {
|
|
const inputs = ['RY-PR-A', 'AACT U', 'SCU.UN', 'BRK/B', 'AAPL', 'RY- PR- A'];
|
|
for (const source of SOURCES) {
|
|
for (const raw of inputs) {
|
|
const first = parseTicker(raw, source);
|
|
expect(first).not.toBeNull();
|
|
if (first === null) {
|
|
continue;
|
|
}
|
|
const canonical =
|
|
first.classSuffix === '' ? first.tickerRoot : `${first.tickerRoot}.${first.classSuffix}`;
|
|
expect(parseTicker(canonical, source === 'ceo' ? 'eod' : source)).toEqual(first);
|
|
}
|
|
}
|
|
});
|
|
|
|
test('seeded random garbage never throws and never yields empty parts or stray separators', () => {
|
|
const rng = makeRng(0x9a7b);
|
|
const alphabet = 'ABCxyz019 .-/\t';
|
|
for (let n = 0; n < 5_000; n++) {
|
|
const raw = randomString(rng, alphabet, Math.floor(rng() * 12));
|
|
const result = parseTicker(raw, SOURCES[n & 3]!);
|
|
if (result === null) {
|
|
continue;
|
|
}
|
|
expect(result.tickerRoot.length).toBeGreaterThan(0);
|
|
expect(/[ .\-/\t]/.test(result.tickerRoot)).toBe(false);
|
|
expect(result.tickerRoot).toBe(result.tickerRoot.toUpperCase());
|
|
if (result.classSuffix !== '') {
|
|
// Canonical suffix: dot-joined non-empty parts with no other separator characters.
|
|
expect(/^[^ .\-/\t]+(\.[^ .\-/\t]+)*$/.test(result.classSuffix)).toBe(true);
|
|
}
|
|
}
|
|
});
|
|
});
|