small commit
This commit is contained in:
parent
f8ca9b529b
commit
8f00871661
4 changed files with 874 additions and 0 deletions
528
apps/stock/data-pipeline/scripts/phase1-inventory.ts
Normal file
528
apps/stock/data-pipeline/scripts/phase1-inventory.ts
Normal file
|
|
@ -0,0 +1,528 @@
|
|||
import { homedir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { parseArgs, parseEnv } from 'node:util';
|
||||
import { MongoClient, type Db, type Document } from 'mongodb';
|
||||
import { Client } from 'pg';
|
||||
|
||||
const sources = ['qm', 'eod', 'ib', 'ceo'] as const;
|
||||
type Source = typeof sources[number];
|
||||
type Entity = 'stock' | 'exchange' | 'country' | 'other' | 'unclassified';
|
||||
const entities: Record<string, Entity> = {
|
||||
qmSymbols: 'stock', eodSymbols: 'stock', ibSymbols: 'stock', ceoSymbols: 'stock',
|
||||
qmExchanges: 'exchange', eodExchanges: 'exchange', ibExchanges: 'exchange', ceoExchanges: 'exchange',
|
||||
teCountries: 'country', teIndicators: 'country', teData: 'country', teMarketData: 'country',
|
||||
qmDividends: 'other', qmEarnings: 'other', qmFilings: 'other', qmFinancials: 'other',
|
||||
'qmFinancials-old': 'other', qmIntraday: 'other', qmPrices: 'other', qmSplits: 'other',
|
||||
eodFinancialsOLD: 'other', eodFundamentalsOLD: 'other', eodIntraday1H: 'other',
|
||||
eodIntraday1M: 'other', eodIntraday5M: 'other', eodPrices: 'other', eodSymbolChange: 'other',
|
||||
ceoPosts: 'other', ceoShorts: 'other', teUrls: 'other', ttFutures: 'other',
|
||||
};
|
||||
const fields = ['ticker', 'exchange', 'isin', 'figi', 'cusip', 'name', 'country', 'currency', 'mic', 'conid', 'priority'] as const;
|
||||
type Field = typeof fields[number];
|
||||
type Aliases = Partial<Record<Field, string[]>>;
|
||||
const qmId = (field: string) => [
|
||||
field, 'profile.' + field, 'profile.info.' + field, 'profile.details.' + field,
|
||||
'symbolInfo.' + field, 'symbolInfo.' + field.toUpperCase(),
|
||||
];
|
||||
const aliases: Record<string, Aliases> = {
|
||||
qmSymbols: { ticker: ['symbol'], exchange: ['exchange'], name: ['name'], country: ['countryCode'],
|
||||
isin: qmId('isin'), cusip: qmId('cusip'), figi: qmId('figi'), currency: qmId('currency') },
|
||||
eodSymbols: { ticker: ['Code'], exchange: ['eodExchange', 'Exchange'], isin: ['Isin', 'ISIN'],
|
||||
name: ['Name'], country: ['Country'], currency: ['Currency'], cusip: ['Cusip'], figi: ['FIGI', 'Figi'] },
|
||||
ibSymbols: { ticker: ['localSymbol', 'symbol'], exchange: ['exchangeId', 'exchange_id'], isin: ['isin'],
|
||||
cusip: ['cusip'], figi: ['figi'], conid: ['conid'], name: ['description'], country: ['country'], currency: ['currency'] },
|
||||
ceoSymbols: { ticker: ['symbol'], exchange: ['exchange'], name: ['name'], country: ['countryCode'],
|
||||
currency: ['currency'], isin: ['isin'], cusip: ['cusip'], figi: ['figi'] },
|
||||
qmExchanges: { exchange: ['exchange'], country: ['countryCode'], name: ['exchangeName', 'name'],
|
||||
currency: ['currency'], mic: ['operatingMIC', 'mic'], priority: ['priority'] },
|
||||
eodExchanges: { exchange: ['Code'], mic: ['OperatingMIC'], country: ['CountryISO2', 'Country'],
|
||||
currency: ['Currency'], name: ['Name'] },
|
||||
ibExchanges: { exchange: ['exchange_id', 'id'], country: ['country_code', 'country'], name: ['name'],
|
||||
currency: ['currency'], mic: ['operatingMIC', 'mic'] },
|
||||
ceoExchanges: { exchange: ['exchange'], country: ['countryCode'], name: ['exchangeName', 'name'],
|
||||
currency: ['currency'], mic: ['operatingMIC', 'mic'] },
|
||||
};
|
||||
const requiredFields = fields.slice(0, 8);
|
||||
const cmp = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;
|
||||
const upper = (value: string) => value.toUpperCase();
|
||||
const sourceOf = (name: string) => /^(qm|eod|ib|ceo|te|tt)(?=[A-Z])/.exec(name)?.[1] ?? 'other';
|
||||
const tupleKey = (...parts: string[]) => parts.join('\u0000');
|
||||
const text = (value: unknown) => typeof value === 'string' ? value.trim() :
|
||||
typeof value === 'number' && Number.isFinite(value) ? String(value) : '';
|
||||
|
||||
function assertReadStages(value: unknown): void {
|
||||
if (!value || typeof value !== 'object') return;
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
if (key === '$' + 'out' || key === '$' + 'merge') throw Error('Aggregation stage is forbidden');
|
||||
assertReadStages(child);
|
||||
}
|
||||
}
|
||||
|
||||
function mongoReads(db: Db) {
|
||||
return {
|
||||
listCollections: () => db.listCollections({}, { nameOnly: true }).toArray(),
|
||||
estimatedDocumentCount: (name: string) => db.collection(name).estimatedDocumentCount(),
|
||||
countDocuments: (name: string) => db.collection(name).countDocuments({}),
|
||||
find: (name: string, filter: Document = {}) => ({
|
||||
limit: (n: number) => {
|
||||
if (!Number.isSafeInteger(n) || n < 1 || n > 2) throw Error('Expected a bounded example query');
|
||||
return db.collection(name).find(filter).sort({ _id: 1 }).limit(n).toArray();
|
||||
},
|
||||
}),
|
||||
aggregate: (name: string, stages: Document[]) => {
|
||||
assertReadStages(stages);
|
||||
return db.collection(name).aggregate(stages, { batchSize: 2_000 });
|
||||
},
|
||||
listIndexes: (name: string) => db.collection(name).listIndexes().toArray(),
|
||||
runCommand: (command: { usersInfo: 1 }) => {
|
||||
if (Object.keys(command).length !== 1 || command.usersInfo !== 1) throw Error('Expected usersInfo');
|
||||
return db.command(command, { readPreference: 'primary' });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
type MongoReads = ReturnType<typeof mongoReads>;
|
||||
type User = { user: string; db: string; roles: { role: string; db: string }[] };
|
||||
const readOnly = (user: User) => user.roles.length > 0 &&
|
||||
user.roles.every(({ role }) => role === 'read' || role === 'readAnyDatabase');
|
||||
const canRead = (user: User, db: string) => user.roles.some(role => role.role === 'readAnyDatabase' || role.db === db);
|
||||
|
||||
async function mongoUsers(client: MongoClient, name: string) {
|
||||
const results = await Promise.all(['admin', name].map(db => mongoReads(client.db(db)).runCommand({ usersInfo: 1 })));
|
||||
const users: User[] = results.flatMap(result => result.users.map(({ user, db, roles }: User) => ({ user, db, roles })));
|
||||
return [...new Map(users.map(user => [tupleKey(user.db, user.user), user])).values()]
|
||||
.sort((a, b) => cmp(tupleKey(a.db, a.user), tupleKey(b.db, b.user)));
|
||||
}
|
||||
|
||||
function safeMongoUri(raw: string) {
|
||||
const uri = new URL(raw);
|
||||
if (!['localhost', '127.0.0.1', '[::1]'].includes(uri.hostname)) throw Error('Expected a local MongoDB host');
|
||||
return uri;
|
||||
}
|
||||
|
||||
async function mongoReadUri(rootUri: string, name: string, users: User[], env: Partial<Record<string, string>>) {
|
||||
const available = users.filter(user => readOnly(user) && canRead(user, name));
|
||||
if (!available.length) return rootUri;
|
||||
const studioEnv = Bun.file(join(homedir(), '.studio', 'test-env', 'stock-bot.env'));
|
||||
const candidates = [env.PHASE1_MONGO_READ_URI, rootUri, await studioEnv.exists()
|
||||
? parseEnv(await studioEnv.text()).MONGODB_URI : undefined];
|
||||
for (const raw of candidates) {
|
||||
if (!raw) continue;
|
||||
const uri = safeMongoUri(raw), username = decodeURIComponent(uri.username);
|
||||
const authDb = uri.searchParams.get('authSource') ?? (uri.pathname.slice(1) || 'admin');
|
||||
if (available.some(user => user.user === username && user.db === authDb)) return raw;
|
||||
}
|
||||
throw Error('A read-only MongoDB user exists but its URI is unavailable; supply PHASE1_MONGO_READ_URI');
|
||||
}
|
||||
|
||||
function trimmed(doc: Document) {
|
||||
return Object.fromEntries(Object.entries(doc).map(([key, value]) => {
|
||||
if (Array.isArray(value)) return [key, { length: value.length, keys: [...new Set(value.slice(0, 5).flatMap(v =>
|
||||
v && typeof v === 'object' ? Object.keys(v) : []))].sort(cmp) }];
|
||||
if (value && Object.getPrototypeOf(value) === Object.prototype) return [key, { keys: Object.keys(value).sort(cmp) }];
|
||||
return [key, typeof value === 'string' && value.length > 180 ? value.slice(0, 180) + '…' : value];
|
||||
}));
|
||||
}
|
||||
|
||||
function expression(path: string) {
|
||||
return { $trim: { input: { $convert: { input: '$' + path, to: 'string', onError: '', onNull: '' } } } };
|
||||
}
|
||||
|
||||
const limitStages = (limit: number | null) => limit === null ? [] : [{ $limit: limit }];
|
||||
|
||||
async function fieldCoverage(mongo: MongoReads, name: string, mapping: Aliases, limit: number | null) {
|
||||
const names = fields.filter(field => requiredFields.includes(field) || mapping[field]);
|
||||
const group = Object.fromEntries(names.map(field => [field, { $sum: { $cond: [
|
||||
mapping[field]?.length ? { $or: mapping[field]!.map(path => ({ $ne: [expression(path), ''] })) } : false, 1, 0,
|
||||
] } }]));
|
||||
const [counts] = await mongo.aggregate(name, [...limitStages(limit),
|
||||
{ $group: { _id: null, total: { $sum: 1 }, ...group } }]).toArray();
|
||||
const total = Number(counts?.total ?? 0);
|
||||
return { total, aliases: mapping, fields: Object.fromEntries(names.map(field => {
|
||||
const filled = Number(counts?.[field] ?? 0);
|
||||
return [field, { filled, fraction: total ? filled / total : 0 }];
|
||||
})) };
|
||||
}
|
||||
|
||||
async function inventory(mongo: MongoReads, limit: number | null, sampleMemory: () => void) {
|
||||
const collections = [];
|
||||
const fillRates: Record<string, Awaited<ReturnType<typeof fieldCoverage>>> = {};
|
||||
const examples: Partial<Record<Entity, { collection: string; document: Document }[]>> = {};
|
||||
const group: Record<string, string[]> = {};
|
||||
for (const row of (await mongo.listCollections()).sort((a, b) => cmp(a.name, b.name))) {
|
||||
const name = row.name, source = sourceOf(name), entity = entities[name] ?? 'unclassified';
|
||||
const estimatedDocumentCount = await mongo.estimatedDocumentCount(name);
|
||||
const countDocuments = estimatedDocumentCount < 1_000_000 ? await mongo.countDocuments(name) : null;
|
||||
const indexes = (await mongo.listIndexes(name)).map(index => String(index.name)).sort(cmp);
|
||||
const keyRows = await mongo.aggregate(name, [
|
||||
{ $sample: { size: 200 } },
|
||||
{ $project: { _id: 0, keys: { $map: { input: { $objectToArray: '$$ROOT' }, as: 'field', in: '$$field.k' } } } },
|
||||
]).toArray();
|
||||
const topLevelKeys = [...new Set<string>(keyRows.flatMap(value => value.keys))].sort(cmp);
|
||||
(group[source] ??= []).push(name);
|
||||
collections.push({ name, source, entity, estimatedDocumentCount, countDocuments, indexes, topLevelKeys });
|
||||
const seen = examples[entity] ??= [];
|
||||
if (seen.length < 2 && estimatedDocumentCount) {
|
||||
for (const document of await mongo.find(name).limit(2 - seen.length)) seen.push({ collection: name, document: trimmed(document) });
|
||||
}
|
||||
if (aliases[name]) fillRates[name] = await fieldCoverage(mongo, name, aliases[name], limit);
|
||||
sampleMemory();
|
||||
console.error('Inspected ' + name);
|
||||
}
|
||||
return { collections, groups: group, examples, fillRates };
|
||||
}
|
||||
|
||||
const tables = [
|
||||
'exchanges', 'symbols', 'provider_mappings', 'provider_exchange_mappings', 'sync_status',
|
||||
'master_exchanges', 'master_symbols', 'provider_symbol_mappings',
|
||||
] as const;
|
||||
type Mapping = { provider: string; code: string; master: string | null; verified: boolean | null; auto: boolean | null };
|
||||
|
||||
async function readPostgres(client: Client) {
|
||||
await client.connect();
|
||||
await client.query('BEGIN TRANSACTION READ ONLY');
|
||||
try {
|
||||
const counts: Record<string, number | 'missing'> = {};
|
||||
for (const table of tables) {
|
||||
const { rows: [row] } = await client.query('SELECT to_regclass($1) IS NOT NULL AS present', ['public.' + table]);
|
||||
counts[table] = row.present
|
||||
? Number((await client.query('SELECT count(*) AS total FROM public.' + table)).rows[0].total) : 'missing';
|
||||
}
|
||||
const present = (table: string) => counts[table] !== 'missing';
|
||||
const rows = async (sql: string) => (await client.query(sql)).rows;
|
||||
const exchangeStatus = present('provider_exchange_mappings') ? await rows(`
|
||||
SELECT provider, master_exchange_id IS NOT NULL AS mapped, verified, active, auto_mapped, count(*)::int AS total
|
||||
FROM public.provider_exchange_mappings GROUP BY 1,2,3,4,5 ORDER BY 1,2,3,4,5`) : [];
|
||||
const symbolStatus = present('provider_mappings') ? await rows(`
|
||||
SELECT provider, verified, count(*)::int AS total
|
||||
FROM public.provider_mappings GROUP BY 1,2 ORDER BY 1,2`) : [];
|
||||
const confidence = present('provider_mappings') ? await rows(`
|
||||
SELECT provider, confidence, count(*)::int AS total
|
||||
FROM public.provider_mappings GROUP BY 1,2 ORDER BY 1,2`) : [];
|
||||
const mapping: Mapping[] = present('provider_exchange_mappings') ? await rows(`
|
||||
SELECT provider, provider_exchange_code AS code, master_exchange_id AS master,
|
||||
verified, auto_mapped AS auto FROM public.provider_exchange_mappings
|
||||
ORDER BY provider, provider_exchange_code`) : [];
|
||||
return { counts, exchangeStatus, symbolStatus, confidence, mapping };
|
||||
} finally {
|
||||
await client.query('ROLLBACK');
|
||||
}
|
||||
}
|
||||
|
||||
function mappingIndex(mapping: Mapping[]) {
|
||||
const result = new Map<string, Mapping>();
|
||||
for (const row of mapping) {
|
||||
const key = tupleKey(row.provider.toLowerCase(), upper(row.code.trim())), previous = result.get(key);
|
||||
if (previous?.master && row.master && previous.master !== row.master)
|
||||
throw Error('Conflicting master exchange mappings for a normalized provider code');
|
||||
if (!previous || row.master) result.set(key, row);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function pathValue(document: Document, path: string): unknown {
|
||||
return path.split('.').reduce<unknown>((parent, key) =>
|
||||
parent && typeof parent === 'object' ? (parent as Document)[key] : undefined, document);
|
||||
}
|
||||
|
||||
function identifiers(document: Document, mapping: Aliases) {
|
||||
return Object.fromEntries(fields.map(field => [field, mapping[field]?.map(path => text(pathValue(document, path))).find(Boolean) ?? ''])) as Record<Field, string>;
|
||||
}
|
||||
|
||||
function projection(mapping: Aliases) {
|
||||
return Object.fromEntries(Object.values(mapping).flat().map(path => [path, 1]));
|
||||
}
|
||||
|
||||
function validIsin(value: string) {
|
||||
if (!/^[A-Z]{2}[A-Z0-9]{9}[0-9]$/.test(value)) return false;
|
||||
const digits = value.replace(/[A-Z]/g, letter => String(letter.charCodeAt(0) - 55));
|
||||
let total = 0;
|
||||
for (let i = digits.length - 1; i >= 0; i--) {
|
||||
const n = Number(digits[i]) * ((digits.length - i) % 2 ? 1 : 2);
|
||||
total += n > 9 ? n - 9 : n;
|
||||
}
|
||||
return total % 10 === 0;
|
||||
}
|
||||
|
||||
const venues = 'US|CA|NASDAQ|NYSE|AMEX|NYSEARCA|TSX|TSE|TSXV|CSE|OTC';
|
||||
const prefix = new RegExp('^(?:' + venues + '):');
|
||||
const suffix = new RegExp(':(?:' + venues + ')$');
|
||||
function tickerKey(raw: string) {
|
||||
const rules: string[] = [];
|
||||
let key = raw;
|
||||
for (const [rule, pattern, replacement] of [
|
||||
['case', /[a-z]/, upper(key)],
|
||||
['venue_prefix', prefix, ''],
|
||||
['venue_suffix', suffix, ''],
|
||||
['us_dot_suffix', /\.US$/, ''],
|
||||
['share_class_separator', /^([A-Z0-9]+)[ /-]([A-Z])$/, '$1.$2'],
|
||||
['share_class_dot', /^[A-Z0-9]+\.[A-Z]$/, null],
|
||||
] as const) {
|
||||
if (!pattern.test(key)) continue;
|
||||
rules.push(rule);
|
||||
if (replacement !== null) key = rule === 'case' ? replacement : key.replace(pattern, replacement);
|
||||
}
|
||||
return { key, rules };
|
||||
}
|
||||
|
||||
function countryKey(value: string) {
|
||||
const code = upper(value);
|
||||
return ({ USA: 'US', 'UNITED STATES': 'US', 'UNITED STATES OF AMERICA': 'US', CAN: 'CA', CANADA: 'CA',
|
||||
GBR: 'GB', UK: 'GB', 'UNITED KINGDOM': 'GB', AUS: 'AU', AUSTRALIA: 'AU' } as Record<string, string>)[code] ?? code;
|
||||
}
|
||||
|
||||
const words = (name: string) => new Set(name.toLowerCase().normalize('NFKC').match(/[\p{L}\p{N}]+/gu) ?? []);
|
||||
function similar(a: string, b: string) {
|
||||
if (!a || !b) return false;
|
||||
if (a === b) return true;
|
||||
const one = words(a), two = words(b);
|
||||
let common = 0;
|
||||
for (const token of one) if (two.has(token)) common++;
|
||||
return common > 0 && common / (one.size + two.size - common) >= 0.8;
|
||||
}
|
||||
|
||||
type Stock = [source: Source, id: unknown, exact: string, ticker: string, exchange: string, master: string,
|
||||
rawIsin: string, isin: string, cusip: string, figi: string, name: string, country: string, currency: string];
|
||||
type Index = Map<string, number[]>;
|
||||
const add = (index: Index, key: string, id: number) => {
|
||||
if (!key) return;
|
||||
const ids = index.get(key);
|
||||
if (ids) ids.push(id);
|
||||
else index.set(key, [id]);
|
||||
};
|
||||
const marketKey = (ticker: string, market: string) => ticker && market ? tupleKey(ticker, market) : '';
|
||||
const stocksFor = (source: Source) => source + 'Symbols';
|
||||
const exchangeFor = (source: Source) => source + 'Exchanges';
|
||||
|
||||
async function gatherStocks(mongo: MongoReads, names: Set<string>, mapping: Map<string, Mapping>, limit: number | null, memory: () => void) {
|
||||
const records: Stock[] = [];
|
||||
const indices = { isin: new Map() as Index, cusip: new Map() as Index, figi: new Map() as Index,
|
||||
markets: new Map() as Index, rawMarkets: new Map() as Index, currency: new Map() as Index, rawCurrency: new Map() as Index,
|
||||
tickers: new Map() as Index };
|
||||
const counts = Object.fromEntries(sources.map(source => [source, {
|
||||
noExchangeCode: 0, mappingMissing: 0, mappingHasNullMaster: 0, hasMaster: 0,
|
||||
normalizations: {} as Record<string, number>,
|
||||
}])) as Record<Source, { noExchangeCode: number; mappingMissing: number; mappingHasNullMaster: number; hasMaster: number; normalizations: Record<string, number> }>;
|
||||
for (const source of sources) {
|
||||
const name = stocksFor(source);
|
||||
if (!names.has(name)) continue;
|
||||
const rules = aliases[name], stats = counts[source];
|
||||
for await (const row of mongo.aggregate(name, [{ $project: projection(rules) }, ...limitStages(limit)])) {
|
||||
const id = identifiers(row, rules), rawIsin = upper(id.isin);
|
||||
const isin = validIsin(rawIsin) ? rawIsin : '';
|
||||
const cusip = /^[0-9A-Z*@#]{9}$/.test(upper(id.cusip)) ? upper(id.cusip) : /^(US|CA)/.test(isin) ? isin.slice(2, 11) : '';
|
||||
const figi = /^[A-Z0-9]{12}$/.test(upper(id.figi)) ? upper(id.figi) : '';
|
||||
const exchange = upper(id.exchange), mapped = mapping.get(tupleKey(source, exchange));
|
||||
if (!exchange) stats.noExchangeCode++;
|
||||
else if (!mapped) stats.mappingMissing++;
|
||||
else if (!mapped.master) stats.mappingHasNullMaster++;
|
||||
else stats.hasMaster++;
|
||||
const { key: ticker, rules: applied } = tickerKey(id.ticker);
|
||||
for (const rule of applied) stats.normalizations[rule] = (stats.normalizations[rule] ?? 0) + 1;
|
||||
const master = mapped?.master ?? '', currency = upper(id.currency);
|
||||
const n = records.length;
|
||||
records.push([source, row._id, id.ticker, ticker, exchange, master, rawIsin, isin, cusip, figi, id.name, countryKey(id.country), currency]);
|
||||
add(indices.isin, isin, n);
|
||||
add(indices.cusip, cusip, n);
|
||||
add(indices.figi, figi, n);
|
||||
add(indices.tickers, ticker, n);
|
||||
add(indices.markets, marketKey(ticker, master), n);
|
||||
add(indices.rawMarkets, marketKey(id.ticker, master), n);
|
||||
if (master && id.name) {
|
||||
add(indices.currency, marketKey(ticker, currency), n);
|
||||
add(indices.rawCurrency, marketKey(id.ticker, currency), n);
|
||||
}
|
||||
if (n % 2048 === 0) memory();
|
||||
}
|
||||
console.error('Projected ' + name);
|
||||
}
|
||||
return { records, indices, counts };
|
||||
}
|
||||
|
||||
type StockData = Awaited<ReturnType<typeof gatherStocks>>;
|
||||
const tally = () => ({ total: 0, strong: 0, weak_only: 0, unmatched: 0, exact_after_trim: 0, normalized: 0 });
|
||||
type Tally = ReturnType<typeof tally>;
|
||||
const sourceBit = Object.fromEntries(sources.map((source, n) => [source, 1 << n])) as Record<Source, number>;
|
||||
|
||||
function hitBits(records: Stock[], ids: number[] | undefined, source: Source, predicate?: (record: Stock) => boolean) {
|
||||
let bits = 0;
|
||||
for (const id of ids ?? []) {
|
||||
const other = records[id];
|
||||
if (other[0] !== source && (!predicate || predicate(other))) bits |= sourceBit[other[0]];
|
||||
}
|
||||
return bits;
|
||||
}
|
||||
|
||||
function countRecord(counts: Tally, mask: number, strong: number, exact: number, normal: number) {
|
||||
counts.total++;
|
||||
if (strong & mask) { counts.strong++; return; }
|
||||
if (exact & mask) counts.exact_after_trim++;
|
||||
if (normal & mask) counts.normalized++;
|
||||
if ((exact | normal) & mask) counts.weak_only++;
|
||||
else counts.unmatched++;
|
||||
}
|
||||
|
||||
function measureStocks(data: StockData, memory: () => void) {
|
||||
const { records, indices, counts: coverage } = data;
|
||||
const bySource = Object.fromEntries(sources.map(source => [source, tally()])) as Record<Source, Tally>;
|
||||
const byPair: Record<string, Tally> = {};
|
||||
for (const source of sources) for (const target of sources) if (source !== target) byPair[source + '→' + target] = tally();
|
||||
for (let i = 0; i < records.length; i++) {
|
||||
const [source, , raw, ticker, , master, , isin, cusip, figi, name, , currency] = records[i];
|
||||
const hits = (index: Index, key: string) => key ? hitBits(records, index.get(key), source) : 0;
|
||||
const strong = hits(indices.isin, isin) | hits(indices.cusip, cusip) | hits(indices.figi, figi);
|
||||
const compareName = (row: Stock) => similar(name, row[10]);
|
||||
const nameHits = (index: Index, ticker: string) => master && name && ticker && currency
|
||||
? hitBits(records, index.get(marketKey(ticker, currency)), source, compareName) : 0;
|
||||
const exact = hits(indices.rawMarkets, marketKey(raw, master)) | nameHits(indices.rawCurrency, raw);
|
||||
const normal = hits(indices.markets, marketKey(ticker, master)) | nameHits(indices.currency, ticker);
|
||||
countRecord(bySource[source], 15, strong, exact, normal);
|
||||
for (const target of sources) if (source !== target)
|
||||
countRecord(byPair[source + '→' + target], sourceBit[target], strong, exact, normal);
|
||||
if (i % 2048 === 0) memory();
|
||||
}
|
||||
return { bySource, byPair, mappingCoverage: coverage };
|
||||
}
|
||||
|
||||
async function measureExchanges(mongo: MongoReads, names: Set<string>, mapping: Map<string, Mapping>, limit: number | null) {
|
||||
const codes = new Map<string, { source: Source; code: string; mic: string; country: string; name: string }>();
|
||||
for (const source of sources) {
|
||||
const collection = exchangeFor(source), rules = aliases[collection];
|
||||
if (!names.has(collection)) continue;
|
||||
for await (const row of mongo.aggregate(collection, [{ $project: projection(rules) }, ...limitStages(limit)])) {
|
||||
const fields = identifiers(row, rules), code = upper(fields.exchange);
|
||||
if (code) codes.set(tupleKey(source, code),
|
||||
{ source, code, mic: upper(fields.mic), country: countryKey(fields.country), name: fields.name });
|
||||
}
|
||||
}
|
||||
const rows = [...codes.values()];
|
||||
return Object.fromEntries(sources.map(source => {
|
||||
const counts = { total: 0, strong: 0, mappedVerified: 0, mappedAuto: 0, mappedOther: 0, weak_only: 0, unmatched: 0 };
|
||||
for (const row of rows.filter(value => value.source === source)) {
|
||||
counts.total++;
|
||||
const mapped = mapping.get(tupleKey(source, row.code));
|
||||
if (mapped?.master) {
|
||||
counts.strong++;
|
||||
if (mapped.verified) counts.mappedVerified++;
|
||||
else if (mapped.auto) counts.mappedAuto++;
|
||||
else counts.mappedOther++;
|
||||
} else if (rows.some(peer => peer.source !== source &&
|
||||
((row.mic && !/^(X{4}|N\/A|-)$/.test(row.mic) && peer.mic === row.mic) ||
|
||||
(row.country && peer.country === row.country && similar(row.name, peer.name))))) counts.weak_only++;
|
||||
else counts.unmatched++;
|
||||
}
|
||||
return [source, counts];
|
||||
}));
|
||||
}
|
||||
|
||||
type Pair = [number, number];
|
||||
type Case = { bucket: string; key: string; ids: number[] };
|
||||
const different = (a: string, b: string) => !!a && !!b && a !== b;
|
||||
function trickySelection({ records, indices }: StockData) {
|
||||
const cases: Case[] = [];
|
||||
const idOrder = (a: number, b: number) => cmp(records[a][0], records[b][0]) || cmp(String(records[a][1]), String(records[b][1]));
|
||||
const pair = (list: number[], test: (a: Stock, b: Stock) => boolean): Pair | undefined => {
|
||||
if (list.length < 2) return;
|
||||
const ordered = [...list].sort(idOrder);
|
||||
for (let i = 0; i < ordered.length; i++) for (let j = i + 1; j < ordered.length; j++) {
|
||||
const a = ordered[i], b = ordered[j];
|
||||
if (records[a][0] !== records[b][0] && test(records[a], records[b])) return [a, b];
|
||||
}
|
||||
};
|
||||
const grouped = (bucket: string, index: Index, test: (a: Stock, b: Stock) => boolean) => {
|
||||
let count = 0;
|
||||
for (const key of [...index.keys()].sort(cmp)) {
|
||||
const ids = pair(index.get(key)!, test);
|
||||
if (!ids) continue;
|
||||
cases.push({ bucket, key: key.replaceAll('\u0000', ' / '), ids });
|
||||
if (++count === 5) break;
|
||||
}
|
||||
};
|
||||
grouped('isin_currency_or_country_conflict', indices.isin, (a, b) => different(a[11], b[11]) || different(a[12], b[12]));
|
||||
grouped('isin_ticker_variation', indices.isin, (a, b) => different(a[2], b[2]));
|
||||
grouped('share_class_format', indices.tickers, (a, b) =>
|
||||
/^[A-Z0-9]+\.[A-Z]$/.test(a[3]) && different(a[2], b[2]) && [a[2], b[2]].some(value => /[ /-][A-Z]$/i.test(value)));
|
||||
grouped('dual_master_exchanges', indices.isin, (a, b) => different(a[5], b[5]));
|
||||
grouped('ticker_exchange_conflicting_isins', indices.markets, (a, b) => different(a[7], b[7]));
|
||||
const invalid = records.flatMap((row, id) => row[6] && !row[7] ? [id] : [])
|
||||
.sort((a, b) => cmp(records[a][6], records[b][6]) || cmp(records[a][2], records[b][2]) || idOrder(a, b));
|
||||
for (const id of invalid.slice(0, 5)) cases.push({ bucket: 'invalid_isin', key: records[id][6], ids: [id] });
|
||||
return cases;
|
||||
}
|
||||
|
||||
async function trickyDocuments(mongo: MongoReads, data: StockData) {
|
||||
const output = [];
|
||||
for (const { bucket, key, ids } of trickySelection(data)) {
|
||||
const documents = [];
|
||||
for (const i of ids) {
|
||||
const [source, _id, ticker, normalizedTicker, , master] = data.records[i], collection = stocksFor(source);
|
||||
const [doc] = await mongo.find(collection, { _id }).limit(1);
|
||||
if (!doc) throw Error('A selected fixture disappeared during the inventory');
|
||||
documents.push({ collection, _id, ticker, normalizedTicker, resolvedMasterExchangeId: master || null, document: trimmed(doc) });
|
||||
}
|
||||
output.push({ bucket, key, documents });
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const started = performance.now(), generatedAt = new Date().toISOString();
|
||||
let peakRSS = 0;
|
||||
const memory = () => { peakRSS = Math.max(peakRSS, process.memoryUsage.rss(), process.resourceUsage().maxRSS * 1024); };
|
||||
memory();
|
||||
const args = parseArgs({ options: { 'sample-limit': { type: 'string' } } });
|
||||
const limit = args.values['sample-limit'] === undefined ? null : Number(args.values['sample-limit']);
|
||||
if (limit !== null && (!Number.isSafeInteger(limit) || limit < 1)) throw Error('Expected a positive sample limit');
|
||||
const env = parseEnv(await Bun.file(resolve(import.meta.dir, '../../../../.env')).text());
|
||||
const rootUri = env.MONGODB_URI;
|
||||
if (!rootUri) throw Error('Missing MONGODB_URI');
|
||||
const parsed = safeMongoUri(rootUri), name = env.MONGODB_DATABASE || parsed.pathname.slice(1) || 'stock';
|
||||
const host = env.POSTGRES_HOST;
|
||||
if (!host || !['localhost', '127.0.0.1', '::1'].includes(host)) throw Error('Expected a local Postgres host');
|
||||
const metadata = new MongoClient(rootUri, { readPreference: 'secondaryPreferred', serverSelectionTimeoutMS: 5_000 });
|
||||
const pg = new Client({
|
||||
host, port: Number(env.POSTGRES_PORT || 5432), database: env.POSTGRES_DATABASE,
|
||||
user: env.POSTGRES_USERNAME, password: env.POSTGRES_PASSWORD, connectionTimeoutMillis: 5_000,
|
||||
});
|
||||
let reader: MongoClient | undefined;
|
||||
try {
|
||||
await metadata.connect();
|
||||
const users = await mongoUsers(metadata, name);
|
||||
const readUri = await mongoReadUri(rootUri, name, users, env), active = safeMongoUri(readUri);
|
||||
let dbClient = metadata;
|
||||
if (readUri !== rootUri) {
|
||||
reader = new MongoClient(readUri, { readPreference: 'secondaryPreferred', serverSelectionTimeoutMS: 5_000 });
|
||||
await reader.connect();
|
||||
dbClient = reader;
|
||||
}
|
||||
const mongo = mongoReads(dbClient.db(name));
|
||||
const { mapping: rows, ...postgres } = await readPostgres(pg);
|
||||
const mapping = mappingIndex(rows);
|
||||
const { collections, groups, examples, fillRates } = await inventory(mongo, limit, memory);
|
||||
const names = new Set(collections.map(collection => collection.name));
|
||||
const data = await gatherStocks(mongo, names, mapping, limit, memory);
|
||||
const stocks = measureStocks(data, memory);
|
||||
const exchanges = await measureExchanges(mongo, names, mapping, limit);
|
||||
const trickyCases = await trickyDocuments(mongo, data);
|
||||
memory();
|
||||
console.log(JSON.stringify({
|
||||
generatedAt,
|
||||
mongo: { uriMasked: active.protocol + '//***:***@' + active.host + '/' + name,
|
||||
db: name, users, readOnlyUserExists: users.some(readOnly), collectionLogin: readUri === rootUri ? 'configured' : 'read-only' },
|
||||
collections, sources: { collections: groups, examples }, fillRates, postgres, matching: { stocks, exchanges },
|
||||
trickyCases, sampleLimit: limit, runtimeMs: Math.round(performance.now() - started), peakRssMb: Math.round(peakRSS / 1048576),
|
||||
}));
|
||||
} finally {
|
||||
await Promise.allSettled([metadata.close(), pg.end(), reader?.close()]);
|
||||
}
|
||||
}
|
||||
|
||||
await main().catch(error => {
|
||||
const safeMessages = ['Aggregation stage is forbidden', 'Expected a bounded example query', 'Expected usersInfo',
|
||||
'Expected a local MongoDB host', 'Expected a local Postgres host', 'Missing MONGODB_URI', 'Expected a positive sample limit',
|
||||
'A read-only MongoDB user exists but its URI is unavailable; supply PHASE1_MONGO_READ_URI',
|
||||
'Conflicting master exchange mappings for a normalized provider code', 'A selected fixture disappeared during the inventory'];
|
||||
console.error('Inventory failed: ' + (safeMessages.includes(error?.message) ? error.message :
|
||||
String(error?.name || 'Error') + (error?.code ? ' (' + String(error.code) + ')' : '')));
|
||||
process.exitCode = 1;
|
||||
});
|
||||
310
docs/data-pipeline/phase1-investigation.md
Normal file
310
docs/data-pipeline/phase1-investigation.md
Normal file
|
|
@ -0,0 +1,310 @@
|
|||
# Phase 1 data-pipeline investigation
|
||||
|
||||
Full inventory run at **2026-11-26T08:29:35.173Z** against checkout `f8ca9b529bea0e1b6ab1f5ef73b79c2b1a29eb3b`. The inventory script was an uncommitted addition at that SHA. The run took **24.85 seconds** and peaked at **1,413 MiB RSS**.
|
||||
|
||||
Command `bun apps/stock/data-pipeline/scripts/phase1-inventory.ts > /tmp/p1.json` from the repository root. The private JSON contains the sampled key sets, index names, source excerpts, exact tallies and per-pair results. The report uses only the first full run for measured figures.
|
||||
|
||||
## a. Source inventory
|
||||
|
||||
The `stock` database contained **31 collections**. Source names start with lowercase provider prefixes followed by a camelCase entity name (`qm*`, `eod*`, `ib*`, `ceo*`, `te*`, `tt*`). No `XX_`-prefixed, TradingView, or Webshare collection was present. This describes persisted data. The ingestion code and [source notes](../../docs/data-sources.md) also cover providers with no collection in this snapshot.
|
||||
|
||||
The exact count column comes from `countDocuments({})` for collections whose estimate was below one million. A dash means the estimate was used. The inventory sampled top-level keys from up to 200 documents per collection. Large time-series and event collections had metadata and key samples only.
|
||||
|
||||
| Provider | Collection | Entity | Estimated documents | Exact documents | Indexes |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| ceo | `ceoExchanges` | exchange | 4 | 4 | 1 |
|
||||
| ceo | `ceoPosts` | other | 14,779,267 | — | 2 |
|
||||
| ceo | `ceoShorts` | other | 692,904 | 692,904 | 2 |
|
||||
| ceo | `ceoSymbols` | stock | 12,589 | 12,589 | 2 |
|
||||
| eod | `eodExchanges` | exchange | 76 | 76 | 1 |
|
||||
| eod | `eodFinancialsOLD` | other | 2,975,061 | — | 3 |
|
||||
| eod | `eodFundamentalsOLD` | other | 106,589 | 106,589 | 2 |
|
||||
| eod | `eodIntraday1H` | other | 110,450,096 | — | 4 |
|
||||
| eod | `eodIntraday1M` | other | 3,402,612,960 | — | 4 |
|
||||
| eod | `eodIntraday5M` | other | 1,075,367,880 | — | 4 |
|
||||
| eod | `eodPrices` | other | 845,701,704 | — | 4 |
|
||||
| eod | `eodSymbolChange` | other | 230 | 230 | 1 |
|
||||
| eod | `eodSymbols` | stock | 317,807 | 317,807 | 41 |
|
||||
| ib | `ibExchanges` | exchange | 214 | 214 | 1 |
|
||||
| ib | `ibSymbols` | stock | 18,402 | 18,402 | 1 |
|
||||
| qm | `qmDividends` | other | 495,942 | 495,942 | 2 |
|
||||
| qm | `qmEarnings` | other | 444,865 | 444,865 | 2 |
|
||||
| qm | `qmExchanges` | exchange | 25 | 25 | 1 |
|
||||
| qm | `qmFilings` | other | 30,521,360 | — | 2 |
|
||||
| qm | `qmFinancials` | other | 1,864,342 | — | 2 |
|
||||
| qm | `qmFinancials-old` | other | 907,764 | 907,764 | 4 |
|
||||
| qm | `qmIntraday` | other | 173,281,224 | — | 2 |
|
||||
| qm | `qmPrices` | other | 51,524,772 | — | 2 |
|
||||
| qm | `qmSplits` | other | 18,751 | 18,751 | 2 |
|
||||
| qm | `qmSymbols` | stock | 47,243 | 47,243 | 60 |
|
||||
| te | `teCountries` | country | 197 | 197 | 1 |
|
||||
| te | `teData` | country | 14,794 | 14,794 | 3 |
|
||||
| te | `teIndicators` | country | 163 | 163 | 1 |
|
||||
| te | `teMarketData` | country | 435 | 435 | 3 |
|
||||
| te | `teUrls` | other | 2,424,784 | — | 8 |
|
||||
| tt | `ttFutures` | other | 1,460,406 | — | 4 |
|
||||
|
||||
### Identifier coverage
|
||||
|
||||
Cells show filled records and percentages within the full collection. Coverage measures nonempty values, including values later rejected by identifier validation. The JSON records the tested field aliases, including EOD `eodExchange` before `Exchange`, IB `localSymbol` before `symbol`, and QM profile and symbol-info paths. Country and other collections are inventoried as their own entity types. The stock/exchange identifier pass is confined to the eight collections below.
|
||||
|
||||
| Collection | Records | Ticker | Exchange code | ISIN | FIGI | CUSIP | Name | Country | Currency |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| `ceoExchanges` | 4 | 0 (0.00%) | 4 (100.00%) | 0 (0.00%) | 0 (0.00%) | 0 (0.00%) | 0 (0.00%) | 4 (100.00%) | 0 (0.00%) |
|
||||
| `ceoSymbols` | 12,589 | 12,589 (100.00%) | 12,589 (100.00%) | 0 (0.00%) | 0 (0.00%) | 0 (0.00%) | 12,560 (99.77%) | 0 (0.00%) | 0 (0.00%) |
|
||||
| `eodExchanges` | 76 | 0 (0.00%) | 76 (100.00%) | 0 (0.00%) | 0 (0.00%) | 0 (0.00%) | 76 (100.00%) | 76 (100.00%) | 76 (100.00%) |
|
||||
| `eodSymbols` | 317,807 | 317,807 (100.00%) | 317,807 (100.00%) | 196,833 (61.93%) | 0 (0.00%) | 0 (0.00%) | 317,807 (100.00%) | 317,807 (100.00%) | 317,807 (100.00%) |
|
||||
| `ibExchanges` | 214 | 0 (0.00%) | 214 (100.00%) | 0 (0.00%) | 0 (0.00%) | 0 (0.00%) | 214 (100.00%) | 214 (100.00%) | 0 (0.00%) |
|
||||
| `ibSymbols` | 18,402 | 18,402 (100.00%) | 18,402 (100.00%) | 18,402 (100.00%) | 0 (0.00%) | 18,399 (99.98%) | 18,402 (100.00%) | 18,402 (100.00%) | 18,376 (99.86%) |
|
||||
| `qmExchanges` | 25 | 0 (0.00%) | 25 (100.00%) | 0 (0.00%) | 0 (0.00%) | 0 (0.00%) | 25 (100.00%) | 25 (100.00%) | 0 (0.00%) |
|
||||
| `qmSymbols` | 47,243 | 47,243 (100.00%) | 47,243 (100.00%) | 0 (0.00%) | 0 (0.00%) | 0 (0.00%) | 47,243 (100.00%) | 47,243 (100.00%) | 0 (0.00%) |
|
||||
|
||||
Supplemental identifiers and ranking fields
|
||||
|
||||
| Collection | Field | Filled |
|
||||
| --- | --- | --- |
|
||||
| `ceoExchanges` | `mic` | 0 (0.00%) |
|
||||
| `eodExchanges` | `mic` | 73 (96.05%) |
|
||||
| `ibExchanges` | `mic` | 0 (0.00%) |
|
||||
| `ibSymbols` | `conid` | 18,402 (100.00%) |
|
||||
| `qmExchanges` | `mic` | 0 (0.00%) |
|
||||
| `qmExchanges` | `priority` | 25 (100.00%) |
|
||||
|
||||
### Example documents
|
||||
|
||||
The excerpts below preserve real document IDs and selected fields. The full JSON trims nested objects and arrays and retains more of each record.
|
||||
|
||||
**Exchange**
|
||||
|
||||
`ceoExchanges`
|
||||
`{"_id": "685824287a995922a6f9b0e3", "exchange": "TSX", "countryCode": "CA"}`
|
||||
|
||||
`ceoExchanges`
|
||||
`{"_id": "685824287a995922a6f9b0e4", "exchange": "CDX", "countryCode": "CA"}`
|
||||
|
||||
**Other**
|
||||
|
||||
`ceoPosts`
|
||||
`{"_id": "68584d967a995922a6fa97d3", "spielId": "2875b3d77a40", "ceoId": "BGF", "timestamp": 1744193045999, "score": 1, "votes": 1}`
|
||||
|
||||
`ceoPosts`
|
||||
`{"_id": "68584d967a995922a6fa97d4", "spielId": "ef70832d6c62", "ceoId": "BGF", "timestamp": 1744290036418, "score": 7, "votes": 7}`
|
||||
|
||||
**Stock**
|
||||
|
||||
`ceoSymbols`
|
||||
`{"_id": "685824287a995922a6f9b0b3", "symbol": "1689.TO", "exchange": "TSX", "name": "WisdomTree Natural Gas", "type": "company", "stockType": null, "marketCap": null}`
|
||||
|
||||
`ceoSymbols`
|
||||
`{"_id": "685824287a995922a6f9b0b4", "symbol": "A.V", "exchange": "CDX", "name": "Armor Minerals Inc.", "type": "company", "stockType": null, "marketCap": 34481079.45}`
|
||||
|
||||
**Country**
|
||||
|
||||
`teCountries`
|
||||
`{"_id": "69cdcbe61d0a0362a5e5d120", "slug": "united-states", "name": "United States", "url": "/united-states"}`
|
||||
|
||||
`teCountries`
|
||||
`{"_id": "69cdcbe61d0a0362a5e5d121", "slug": "united-kingdom", "name": "United Kingdom", "url": "/united-kingdom"}`
|
||||
|
||||
### MongoDB access and repeatability
|
||||
|
||||
The planning run reported only `trading_admin` with `root@admin`. Fresh `usersInfo` queries on `admin` and `stock` returned both accounts below.
|
||||
|
||||
| User | Authentication database | Roles |
|
||||
| --- | --- | --- |
|
||||
| `trading_admin` | admin | `root@admin` |
|
||||
| `studio_stock_bot_read` | stock | `read@stock` |
|
||||
|
||||
The live result was **`readOnlyUserExists = true`**. The configured account was used for the two `usersInfo` calls. The pre-existing read-only account was used for collection reads. This investigation created no database users and made no database writes.
|
||||
|
||||
Collection names, complete index definitions and user roles were identical before and after the read-only checks. The estimates were also identical. No collection-level count drift was observed during the verification window.
|
||||
|
||||
The second full run returned identical match tallies and tricky-case excerpts. Random field-key samples may differ on repeat runs. Independent mongosh checks matched five collection estimates and all fixture references. A separate psql read-only transaction matched all five inventory table counts.
|
||||
|
||||
## b. Existing mapping UI, data, and merge rules
|
||||
|
||||
The exchange screen lists existing exchange mappings, displays their status and lets a user add or edit a provider exchange mapping. The pipeline screen starts sync operations and presents counts. The symbol screens browse and filter records. Repository search found no symbol-level mapping editor. Within the application code, the symbol sync paths own writes to `provider_mappings`; the separately exposed pipeline reset can clear the table.
|
||||
|
||||
**Exchange mapping UI**
|
||||
|
||||
- [`apps/stock/web-app/src/features/exchanges/ExchangesPage.tsx`](../../apps/stock/web-app/src/features/exchanges/ExchangesPage.tsx)
|
||||
- [`apps/stock/web-app/src/features/exchanges/components/AddProviderMappingDialog.tsx`](../../apps/stock/web-app/src/features/exchanges/components/AddProviderMappingDialog.tsx)
|
||||
- [`apps/stock/web-app/src/features/exchanges/components/ExchangesTable.tsx`](../../apps/stock/web-app/src/features/exchanges/components/ExchangesTable.tsx)
|
||||
- [`apps/stock/web-app/src/features/exchanges/services/exchangeApi.ts`](../../apps/stock/web-app/src/features/exchanges/services/exchangeApi.ts)
|
||||
|
||||
**Pipeline and symbol screens**
|
||||
|
||||
- [`apps/stock/web-app/src/features/pipeline/PipelinePage.tsx`](../../apps/stock/web-app/src/features/pipeline/PipelinePage.tsx)
|
||||
- [`apps/stock/web-app/src/features/pipeline/services/pipelineApi.ts`](../../apps/stock/web-app/src/features/pipeline/services/pipelineApi.ts)
|
||||
- [`apps/stock/web-app/src/features/symbols/SymbolsPage.tsx`](../../apps/stock/web-app/src/features/symbols/SymbolsPage.tsx)
|
||||
- [`apps/stock/web-app/src/features/symbols/SymbolDetailPage.tsx`](../../apps/stock/web-app/src/features/symbols/SymbolDetailPage.tsx)
|
||||
|
||||
**Web API**
|
||||
|
||||
- [`apps/stock/web-api/src/routes/exchange.routes.ts`](../../apps/stock/web-api/src/routes/exchange.routes.ts)
|
||||
- [`apps/stock/web-api/src/routes/pipeline.routes.ts`](../../apps/stock/web-api/src/routes/pipeline.routes.ts)
|
||||
- [`apps/stock/web-api/src/services/exchange.service.ts`](../../apps/stock/web-api/src/services/exchange.service.ts)
|
||||
- [`apps/stock/web-api/src/services/pipeline.service.ts`](../../apps/stock/web-api/src/services/pipeline.service.ts)
|
||||
|
||||
Exchange routes include `GET /provider-mappings/all`, `GET /provider-mappings/:provider`, `PATCH /provider-mappings/:id`, `POST /provider-mappings`, `GET /provider-exchanges/unmapped/:provider`, and `GET /stats/summary` under the exchanges prefix. Pipeline routes include `POST /symbols/:provider`, `POST /provider-mappings/qm`, `POST /provider-mappings/ib`, and `GET /stats/provider-mappings` under the pipeline prefix. The inventory invoked no API endpoints.
|
||||
|
||||
**Postgres storage and visibility**
|
||||
|
||||
- [`database/postgres/init/02-master-schema.sql`](../../database/postgres/init/02-master-schema.sql)
|
||||
- [`database/postgres/init/04-provider-exchange-mapping-schema.sql`](../../database/postgres/init/04-provider-exchange-mapping-schema.sql)
|
||||
- [`database/postgres/init/05-add-visible-column.sql`](../../database/postgres/init/05-add-visible-column.sql)
|
||||
|
||||
`exchanges` and `symbols` hold canonical records, keyed by exchange code and by ticker plus exchange ID respectively. `provider_exchange_mappings` links provider codes to exchange UUIDs and allows unresolved mappings. `provider_mappings` links provider symbols to canonical symbol UUIDs. `sync_status` records provider and operation status. The visibility flag affects which exchanges the UI and summary show. The live check used `to_regclass` before selecting each table.
|
||||
|
||||
| Table | Rows |
|
||||
| --- | --- |
|
||||
| `exchanges` | 301 |
|
||||
| `symbols` | 0 |
|
||||
| `provider_mappings` | 0 |
|
||||
| `provider_exchange_mappings` | 313 |
|
||||
| `sync_status` | 3 |
|
||||
| `master_exchanges` | missing |
|
||||
| `master_symbols` | missing |
|
||||
| `provider_symbol_mappings` | missing |
|
||||
|
||||
The plan’s names `master_exchanges`, `master_symbols` and `provider_symbol_mappings` are absent from the live Postgres schema. As separately inventoried in section a, the Mongo sources are the provider collections, and the legacy IB handler’s `masterExchanges` collection was also absent from this snapshot.
|
||||
|
||||
| Provider | Has exchange UUID | Verified | Active | Auto mapped | Rows |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| eod | yes | no | no | no | 2 |
|
||||
| eod | yes | no | no | yes | 72 |
|
||||
| eod | yes | no | yes | no | 2 |
|
||||
| ib | yes | no | no | no | 1 |
|
||||
| ib | yes | no | no | yes | 186 |
|
||||
| qm | yes | no | no | yes | 26 |
|
||||
| qm | yes | no | yes | no | 1 |
|
||||
| unified | yes | no | no | yes | 22 |
|
||||
| unified | yes | no | yes | no | 1 |
|
||||
|
||||
The symbol-mapping counts by provider and verification and the confidence histogram are both empty because `provider_mappings` contains zero rows.
|
||||
|
||||
### Existing field and source precedence
|
||||
|
||||
- **Provider normalization**. Uses the first populated ticker of `symbol`, `code`, and `Code`, and the first populated exchange of `exchangeCode`, `exchange`, `exchange_id`, and `Exchange`. It chooses a provider search code, name, country and currency by field precedence. This code does not read `exchangeId`, the live IB symbol spelling. It defines field precedence rather than a source ranking. [`apps/stock/data-pipeline/src/normalization/provider-symbol.ts`](../../apps/stock/data-pipeline/src/normalization/provider-symbol.ts)
|
||||
- **Generic provider symbol sync**. Supports QM, EOD and IB; normalizes the relevant Mongo source and sends each record to the shared repository. [`apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations.ts`](../../apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations.ts)
|
||||
- **Shared SQL sync**. Requires an exact active mapped exchange and matches symbols on ticker plus exchange UUID. Non-null incoming name, country and currency can replace existing values. Verified provider-symbol links retain their symbol and exchange assignments in this path; last-seen timestamps advance. Exchange mapping uses exact code and preserves existing conflicts rather than scoring candidates across sources. [`apps/stock/data-pipeline/src/repositories/PipelineSyncRepository.ts`](../../apps/stock/data-pipeline/src/repositories/PipelineSyncRepository.ts)
|
||||
- **Dedicated QM symbol sync**. Has a fixed exchange-code translation map, a ticker and exchange lookup, and non-null field precedence for name, country and currency. It has its own provider mapping SQL and does not share the verified-link protection in the common repository. [`apps/stock/data-pipeline/src/handlers/symbols/operations/qm-symbols.operations.ts`](../../apps/stock/data-pipeline/src/handlers/symbols/operations/qm-symbols.operations.ts)
|
||||
- **QM exchange mapping sync**. Groups provider exchange codes, supplies name and country, infers CAD for Canada and USD otherwise, and calls the SQL repository with 0.80 confidence. [`apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-qm-provider-mappings.operations.ts`](../../apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-qm-provider-mappings.operations.ts)
|
||||
- **Dedicated QM exchange sync**. Processes QM exchange records through its own SQL path, with exchange lookup and metadata handling. [`apps/stock/data-pipeline/src/handlers/exchanges/operations/qm-exchanges.operations.ts`](../../apps/stock/data-pipeline/src/handlers/exchanges/operations/qm-exchanges.operations.ts)
|
||||
- **Legacy IB exchange sync**. Builds an IB-derived canonical exchange identifier and aliases and targets the Mongo collection `masterExchanges`. Its new records mark the direct IB mapping verified at 1.00 confidence, independent of the live SQL mapping flags. That code path was inspected only. [`apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts`](../../apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts)
|
||||
- **QM ingestion deduplication**. Sets `qmExchanges.priority` from a hard-coded venue list. Within a ticker and country, it prefers a bare QM search code in the US and `symbol:COUNTRY` elsewhere. If neither is present it chooses exchange priority, then market cap, and uses the result to set active flags. This ranks listings inside QM, rather than sources against one another. [`apps/stock/data-ingestion/src/handlers/qm/actions/symbol-dedup.action.ts`](../../apps/stock/data-ingestion/src/handlers/qm/actions/symbol-dedup.action.ts)
|
||||
|
||||
The canonical symbol storage lacks ISIN and FIGI columns, per-field provenance, a match-review queue and a separate country entity. The current symbol and exchange sync paths provide no CEO, TE or TT mappings. The existing code and data support listing and manual exchange mapping by provider, not a general cross-provider merge policy.
|
||||
|
||||
## c. Cross-source matching
|
||||
|
||||
Each source record is counted once across the other providers. Strong means a shared checksum-valid ISIN, a nine-character CUSIP (including the embedded value of valid US and Canadian ISINs), or a 12-character FIGI when supplied. The effective FIGI input was empty. Weak-only means no strong match and either the same ticker and mapped exchange UUID or the same ticker and currency with name token Jaccard ≥ 0.8. Both records require an existing non-null exchange mapping for either weak heuristic. These are candidate links and measured overlaps, not confirmed entity identity.
|
||||
|
||||
| Provider | Projected records | Strong | Weak only | Unmatched | Exact weak | Normalized weak |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| qm | 47,243 | 0 | 976 | 46,267 | 913 | 976 |
|
||||
| eod | 317,807 | 21,200 | 2,710 | 293,897 | 2,452 | 2,710 |
|
||||
| ib | 18,402 | 14,216 | 1,555 | 2,631 | 1,351 | 1,555 |
|
||||
| ceo | 12,589 | 0 | 0 | 12,589 | 0 | 0 |
|
||||
|
||||
Exact weak uses the trimmed raw ticker. Normalized weak also folds case, strips known venue affixes such as `.US` and `:NASDAQ`, and canonicalizes one-letter share classes across dot, dash, slash and whitespace forms. The two weak columns overlap. Their union is the weak-only classification. Each rule occurrence is recorded in the JSON.
|
||||
|
||||
| Provider | Missing exchange code | No mapping row | Mapping has null master | Has master |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| qm | 0 | 0 | 0 | 47,243 |
|
||||
| eod | 0 | 9,845 | 0 | 307,962 |
|
||||
| ib | 0 | 0 | 0 | 18,402 |
|
||||
| ceo | 0 | 12,589 | 0 | 0 |
|
||||
|
||||
| Provider | Observed normalization rules |
|
||||
| --- | --- |
|
||||
| qm | `share_class_dot` 1,298, `share_class_separator` 2 |
|
||||
| eod | `case` 1,727, `share_class_dot` 2,561, `share_class_separator` 2,561 |
|
||||
| ib | `share_class_dot` 579, `share_class_separator` 45 |
|
||||
| ceo | `share_class_dot` 3,105 |
|
||||
|
||||
The pair counts are directed and count records in the source on the left. A record can appear in more than one pair.
|
||||
|
||||
| Pair | Projected records | Strong | Weak only | Unmatched | Exact weak | Normalized weak |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| qm→eod | 47,243 | 0 | 712 | 46,531 | 650 | 712 |
|
||||
| qm→ib | 47,243 | 0 | 264 | 46,979 | 263 | 264 |
|
||||
| qm→ceo | 47,243 | 0 | 0 | 47,243 | 0 | 0 |
|
||||
| eod→qm | 317,807 | 0 | 712 | 317,095 | 650 | 712 |
|
||||
| eod→ib | 317,807 | 21,200 | 2,620 | 293,987 | 2,398 | 2,620 |
|
||||
| eod→ceo | 317,807 | 0 | 0 | 317,807 | 0 | 0 |
|
||||
| ib→qm | 18,402 | 0 | 264 | 18,138 | 263 | 264 |
|
||||
| ib→eod | 18,402 | 14,216 | 1,546 | 2,640 | 1,342 | 1,546 |
|
||||
| ib→ceo | 18,402 | 0 | 0 | 18,402 | 0 | 0 |
|
||||
| ceo→qm | 12,589 | 0 | 0 | 12,589 | 0 | 0 |
|
||||
| ceo→eod | 12,589 | 0 | 0 | 12,589 | 0 | 0 |
|
||||
| ceo→ib | 12,589 | 0 | 0 | 12,589 | 0 | 0 |
|
||||
|
||||
### Exchange codes
|
||||
|
||||
The denominator is distinct nonempty exchange codes per source after case and whitespace normalization. A non-null explicit SQL mapping counts as strong, split into verified, otherwise auto-mapped, and other. The instrument heuristic for unresolved exchanges uses an exact non-placeholder OperatingMIC or country and name token agreement. A SQL mapping may point to an exchange with no equivalent code in the other Mongo sources.
|
||||
|
||||
| Provider | Distinct codes | Mapped / strong | Verified | Auto | Other mapped | Cross-source only | Unmatched |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| qm | 25 | 25 | 0 | 24 | 1 | 0 | 0 |
|
||||
| eod | 76 | 73 | 0 | 69 | 4 | 0 | 3 |
|
||||
| ib | 188 | 187 | 0 | 186 | 1 | 0 | 1 |
|
||||
| ceo | 4 | 0 | 0 | 0 | 0 | 0 | 4 |
|
||||
|
||||
### Tricky cases
|
||||
|
||||
The deterministic selection produced **25 candidates** across 5 buckets. The same record pair can qualify for more than one bucket. The script sorts by identifier or ticker, then source and document ID, and keeps up to five per bucket. No cross-source candidate shared both ticker and mapped exchange while carrying two distinct valid ISINs.
|
||||
|
||||
| Bucket | Candidate key | Source document excerpts |
|
||||
| --- | --- | --- |
|
||||
| `isin_currency_or_country_conflict` | `AGP8696W1045` | `eodSymbols/6870729a89b14ad0b4a7fc48` · Code=SVQ, eodSearchCode=SVQ.F, eodExchange=F, Exchange=F, Isin=AGP8696W1045, Country=Germany, Currency=EUR · master `d9df353b-dae0-43c1-b722-1a0a043d38d2` <br> `ibSymbols/684cd228ba15394e9c03cafd` · symbol=SVA, localSymbol=SVA, exchangeId=NASDAQ, isin=AGP8696W1045, cusip=P8696W104, country=US, currency=USD · master `17eaa972-fac5-4701-8c51-61fe61287820` |
|
||||
| `isin_currency_or_country_conflict` | `AN8068571086` | `eodSymbols/6870729a89b14ad0b4a7f07b` · Code=SLB, eodSearchCode=SLB.PA, eodExchange=PA, Exchange=PA, Isin=AN8068571086, Country=France, Currency=EUR · master `4b186932-19e2-4151-8728-6c9f3469260c` <br> `ibSymbols/684cd226ba15394e9c03c7f9` · symbol=SLB, localSymbol=SLB, exchangeId=EDGX, isin=AN8068571086, cusip=806857108, country=US, currency=USD · master `34c0796c-8d15-434c-9c87-806b062327f3` |
|
||||
| `isin_currency_or_country_conflict` | `AU000000AGD4` | `eodSymbols/6870729f89b14ad0b4a9e61d` · Code=AGD, eodSearchCode=AGD.AU, eodExchange=AU, Exchange=AU, Isin=AU000000AGD4, Country=Australia, Currency=AUD · master `84fe59d5-8228-4e13-b70e-1f507b6597eb` <br> `ibSymbols/684cd08bba15394e9c038dda` · symbol=AGLD, localSymbol=AGLD, exchangeId=AEQLIT, isin=AU000000AGD4, cusip=Q0819E102, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `isin_currency_or_country_conflict` | `AU000000CIA2` | `eodSymbols/6870729b89b14ad0b4a83e5f` · Code=MMPI, eodSearchCode=MMPI.F, eodExchange=F, Exchange=F, Isin=AU000000CIA2, Country=Germany, Currency=EUR · master `d9df353b-dae0-43c1-b722-1a0a043d38d2` <br> `ibSymbols/684cd213ba15394e9c039ad2` · symbol=CIA, localSymbol=CIA, exchangeId=AEQLIT, isin=AU000000CIA2, cusip=Q22964102, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `isin_currency_or_country_conflict` | `AU000000CY57` | `eodSymbols/6870729f89b14ad0b4a9eeef` · Code=CY5, eodSearchCode=CY5.AU, eodExchange=AU, Exchange=AU, Isin=AU000000CY57, Country=Australia, Currency=AUD · master `84fe59d5-8228-4e13-b70e-1f507b6597eb` <br> `ibSymbols/684cd214ba15394e9c039eaa` · symbol=CYG, localSymbol=CYG, exchangeId=VENTURE, isin=AU000000CY57, cusip=Q3080P103, country=CA, currency=CAD · master `bb86f438-d8c1-40b5-ad03-897274de6377` |
|
||||
| `isin_ticker_variation` | `AGP8696W1045` | `eodSymbols/6870729a89b14ad0b4a7fc48` · Code=SVQ, eodSearchCode=SVQ.F, eodExchange=F, Exchange=F, Isin=AGP8696W1045, Country=Germany, Currency=EUR · master `d9df353b-dae0-43c1-b722-1a0a043d38d2` <br> `ibSymbols/684cd228ba15394e9c03cafd` · symbol=SVA, localSymbol=SVA, exchangeId=NASDAQ, isin=AGP8696W1045, cusip=P8696W104, country=US, currency=USD · master `17eaa972-fac5-4701-8c51-61fe61287820` |
|
||||
| `isin_ticker_variation` | `AN8068571086` | `eodSymbols/6870729a89b14ad0b4a804dc` · Code=SCL, eodSearchCode=SCL.STU, eodExchange=STU, Exchange=STU, Isin=AN8068571086, Country=Germany, Currency=EUR · master `6b1ed995-47c4-4e8a-98a8-eefdb1513189` <br> `ibSymbols/684cd226ba15394e9c03c7f9` · symbol=SLB, localSymbol=SLB, exchangeId=EDGX, isin=AN8068571086, cusip=806857108, country=US, currency=USD · master `34c0796c-8d15-434c-9c87-806b062327f3` |
|
||||
| `isin_ticker_variation` | `AU000000AGD4` | `eodSymbols/6870729f89b14ad0b4a9e61d` · Code=AGD, eodSearchCode=AGD.AU, eodExchange=AU, Exchange=AU, Isin=AU000000AGD4, Country=Australia, Currency=AUD · master `84fe59d5-8228-4e13-b70e-1f507b6597eb` <br> `ibSymbols/684cd08bba15394e9c038dda` · symbol=AGLD, localSymbol=AGLD, exchangeId=AEQLIT, isin=AU000000AGD4, cusip=Q0819E102, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `isin_ticker_variation` | `AU000000CIA2` | `eodSymbols/6870729b89b14ad0b4a83e5f` · Code=MMPI, eodSearchCode=MMPI.F, eodExchange=F, Exchange=F, Isin=AU000000CIA2, Country=Germany, Currency=EUR · master `d9df353b-dae0-43c1-b722-1a0a043d38d2` <br> `ibSymbols/684cd213ba15394e9c039ad2` · symbol=CIA, localSymbol=CIA, exchangeId=AEQLIT, isin=AU000000CIA2, cusip=Q22964102, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `isin_ticker_variation` | `AU000000CY57` | `eodSymbols/6870729f89b14ad0b4a9eeef` · Code=CY5, eodSearchCode=CY5.AU, eodExchange=AU, Exchange=AU, Isin=AU000000CY57, Country=Australia, Currency=AUD · master `84fe59d5-8228-4e13-b70e-1f507b6597eb` <br> `ibSymbols/684cd214ba15394e9c039eaa` · symbol=CYG, localSymbol=CYG, exchangeId=VENTURE, isin=AU000000CY57, cusip=Q3080P103, country=CA, currency=CAD · master `bb86f438-d8c1-40b5-ad03-897274de6377` |
|
||||
| `share_class_format` | `AAA.P` | `eodSymbols/6870729789b14ad0b4a719de` · Code=AAA-P, eodSearchCode=AAA-P.V, eodExchange=V, Exchange=V, Country=Canada, Currency=CAD · master `c4d21513-3671-4187-9f87-1a8138b39a33` <br> `ibSymbols/684cd08bba15394e9c038c1a` · symbol=AAA.P, localSymbol=AAA.P, exchangeId=VENTURE, isin=CA33719F1099, cusip=33719F109, country=CA, currency=CAD · master `bb86f438-d8c1-40b5-ad03-897274de6377` |
|
||||
| `share_class_format` | `AAAJ.P` | `eodSymbols/6870729789b14ad0b4a72085` · Code=AAAJ-P, eodSearchCode=AAAJ-P.V, eodExchange=V, Exchange=V, Country=Canada, Currency=CAD · master `c4d21513-3671-4187-9f87-1a8138b39a33` <br> `ibSymbols/684cd08bba15394e9c038c1b` · symbol=AAAJ.P, localSymbol=AAAJ.P, exchangeId=AEQLIT, isin=CA00036L1013, cusip=00036L101, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `share_class_format` | `AACT.U` | `ibSymbols/684cd08bba15394e9c038c28` · symbol=AACT U, localSymbol=AACT U, exchangeId=PSX, isin=KYG330331128, cusip=G33033112, country=US, currency=USD · master `48898e5f-0749-47c6-9832-2af991768477` <br> `qmSymbols/685f48529aba109fcce7be10` · symbol=AACT.U, qmSearchCode=AACT.U:EGX, exchange=EDGX, countryCode=US · master `34c0796c-8d15-434c-9c87-806b062327f3` |
|
||||
| `share_class_format` | `AAM.U` | `ibSymbols/684cd08bba15394e9c038c38` · symbol=AAM U, localSymbol=AAM U, exchangeId=IBEOS, isin=KYG1000R1193, cusip=G1000R119, country=US, currency=USD · master `d0209689-cbe9-4258-919a-7f6cd73db322` <br> `qmSymbols/685f484f9aba109fcce7b6ba` · symbol=AAM.U, qmSearchCode=AAM.U, exchange=NYE, countryCode=US · master `662967e1-3293-4a40-bbd3-297f200c156a` |
|
||||
| `share_class_format` | `ACAP.P` | `eodSymbols/6870729789b14ad0b4a719e6` · Code=ACAP-P, eodSearchCode=ACAP-P.V, eodExchange=V, Exchange=V, Country=Canada, Currency=CAD · master `c4d21513-3671-4187-9f87-1a8138b39a33` <br> `ibSymbols/684cd08bba15394e9c038ca6` · symbol=ACAP.P, localSymbol=ACAP.P, exchangeId=VENTURE, isin=CA04941B1094, cusip=04941B109, country=CA, currency=CAD · master `bb86f438-d8c1-40b5-ad03-897274de6377` |
|
||||
| `dual_master_exchanges` | `AGP8696W1045` | `eodSymbols/6870729a89b14ad0b4a7fc48` · Code=SVQ, eodSearchCode=SVQ.F, eodExchange=F, Exchange=F, Isin=AGP8696W1045, Country=Germany, Currency=EUR · master `d9df353b-dae0-43c1-b722-1a0a043d38d2` <br> `ibSymbols/684cd228ba15394e9c03cafd` · symbol=SVA, localSymbol=SVA, exchangeId=NASDAQ, isin=AGP8696W1045, cusip=P8696W104, country=US, currency=USD · master `17eaa972-fac5-4701-8c51-61fe61287820` |
|
||||
| `dual_master_exchanges` | `AN8068571086` | `eodSymbols/6870729a89b14ad0b4a7f07b` · Code=SLB, eodSearchCode=SLB.PA, eodExchange=PA, Exchange=PA, Isin=AN8068571086, Country=France, Currency=EUR · master `4b186932-19e2-4151-8728-6c9f3469260c` <br> `ibSymbols/684cd226ba15394e9c03c7f9` · symbol=SLB, localSymbol=SLB, exchangeId=EDGX, isin=AN8068571086, cusip=806857108, country=US, currency=USD · master `34c0796c-8d15-434c-9c87-806b062327f3` |
|
||||
| `dual_master_exchanges` | `AU000000AGD4` | `eodSymbols/6870729789b14ad0b4a719fc` · Code=AGLD, eodSearchCode=AGLD.V, eodExchange=V, Exchange=V, Isin=AU000000AGD4, Country=Canada, Currency=CAD · master `c4d21513-3671-4187-9f87-1a8138b39a33` <br> `ibSymbols/684cd08bba15394e9c038dda` · symbol=AGLD, localSymbol=AGLD, exchangeId=AEQLIT, isin=AU000000AGD4, cusip=Q0819E102, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `dual_master_exchanges` | `AU000000CIA2` | `eodSymbols/6870729889b14ad0b4a723d9` · Code=CIA, eodSearchCode=CIA.TO, eodExchange=TO, Exchange=TO, Isin=AU000000CIA2, Country=Canada, Currency=CAD · master `54a5f743-5dde-4de2-a0f9-0a11bc517a73` <br> `ibSymbols/684cd213ba15394e9c039ad2` · symbol=CIA, localSymbol=CIA, exchangeId=AEQLIT, isin=AU000000CIA2, cusip=Q22964102, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `dual_master_exchanges` | `AU000000CY57` | `eodSymbols/6870729f89b14ad0b4a9eeef` · Code=CY5, eodSearchCode=CY5.AU, eodExchange=AU, Exchange=AU, Isin=AU000000CY57, Country=Australia, Currency=AUD · master `84fe59d5-8228-4e13-b70e-1f507b6597eb` <br> `ibSymbols/684cd214ba15394e9c039eaa` · symbol=CYG, localSymbol=CYG, exchangeId=VENTURE, isin=AU000000CY57, cusip=Q3080P103, country=CA, currency=CAD · master `bb86f438-d8c1-40b5-ad03-897274de6377` |
|
||||
| `invalid_isin` | `CA00149WBAD4` | `ibSymbols/684cd212ba15394e9c038fd5` · symbol=AIP.U.BAD, localSymbol=AIP.U.BAD, exchangeId=AEQLIT, isin=CA00149WBAD4, cusip=00149WBAD, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `invalid_isin` | `CA45175CBAD7` | `ibSymbols/684cd218ba15394e9c03ae3f` · symbol=IKNK.BADN, localSymbol=IKNK.BAD.NEW, exchangeId=AEQLIT, isin=CA45175CBAD7, cusip=45175CBAD, country=CA · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `invalid_isin` | `CA52886N1024` | `eodSymbols/6870729d89b14ad0b4a91247` · Code=LEXXW, eodSearchCode=LEXXW.US, eodExchange=US, Exchange=NASDAQ, Isin=CA52886N1024, Country=USA, Currency=USD · master `c6aebb89-82fb-403e-9e82-2cae8068bf55` |
|
||||
| `invalid_isin` | `CA8131391062` | `ibSymbols/684cd225ba15394e9c03c664` · symbol=SCU.UN, localSymbol=SCU.UN.NEW, exchangeId=TSE, isin=CA8131391062, cusip=813139106, country=CA · master `d8272e91-5cd3-4a74-ba38-f77d527b5b8d` |
|
||||
| `invalid_isin` | `CATSETEST001` | `ibSymbols/684cd230ba15394e9c03d587` · symbol=ZYZ.A, localSymbol=ZYZ.A, exchangeId=AEQLIT, isin=CATSETEST001, cusip=TSETEST00, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
|
||||
## d. Stack and conventions
|
||||
|
||||
- **Runtime and workspace**. Bun workspaces and Turbo tasks drive package orchestration.
|
||||
[`package.json`](../../package.json) · [`turbo.json`](../../turbo.json) · [`bunfig.toml`](../../bunfig.toml)
|
||||
- **Query layer**. The Postgres library uses `pg` and raw SQL. The pipeline repository follows that pattern and uses transaction helpers. There is no ORM in this layer.
|
||||
[`libs/data/postgres/package.json`](../../libs/data/postgres/package.json) · [`libs/data/postgres/src/client.ts`](../../libs/data/postgres/src/client.ts) · [`libs/data/postgres/src/transactions.ts`](../../libs/data/postgres/src/transactions.ts) · [`apps/stock/data-pipeline/src/repositories/PipelineSyncRepository.ts`](../../apps/stock/data-pipeline/src/repositories/PipelineSyncRepository.ts)
|
||||
- **Schema changes**. Numbered SQL files are mounted into the Postgres container’s init directory. This is container initialization, so changes to an already initialized volume need a separate application decision. The Studio migration skill refers to Studio’s own Drizzle schema and does not describe this repository.
|
||||
[`docker-compose.yml`](../../docker-compose.yml) · [`database/postgres/init/02-master-schema.sql`](../../database/postgres/init/02-master-schema.sql) · [`database/postgres/init/04-provider-exchange-mapping-schema.sql`](../../database/postgres/init/04-provider-exchange-mapping-schema.sql) · [`database/postgres/init/05-add-visible-column.sql`](../../database/postgres/init/05-add-visible-column.sql)
|
||||
- **Queue and handlers**. The workspace queue and handler libraries provide registration, job dispatch, scheduled operations and metrics. The pipeline registers exchange and symbol handlers.
|
||||
[`libs/core/queue/src/queue-manager.ts`](../../libs/core/queue/src/queue-manager.ts) · [`libs/core/handlers/src/index.ts`](../../libs/core/handlers/src/index.ts) · [`apps/stock/data-pipeline/src/handlers/index.ts`](../../apps/stock/data-pipeline/src/handlers/index.ts) · [`apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts`](../../apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts) · [`apps/stock/data-pipeline/src/handlers/symbols/symbols.handler.ts`](../../apps/stock/data-pipeline/src/handlers/symbols/symbols.handler.ts)
|
||||
- **HTTP API**. Hono routers delegate to services.
|
||||
[`apps/stock/web-api/package.json`](../../apps/stock/web-api/package.json) · [`apps/stock/web-api/src/routes/exchange.routes.ts`](../../apps/stock/web-api/src/routes/exchange.routes.ts) · [`apps/stock/web-api/src/routes/pipeline.routes.ts`](../../apps/stock/web-api/src/routes/pipeline.routes.ts)
|
||||
- **Tests**. The pipeline package runs Bun tests. The Mongo workspace has an example Bun test suite.
|
||||
[`apps/stock/data-pipeline/package.json`](../../apps/stock/data-pipeline/package.json) · [`libs/data/mongodb/test/mongodb.test.ts`](../../libs/data/mongodb/test/mongodb.test.ts)
|
||||
- **Web app**. React and Vite, with the application split into feature folders.
|
||||
[`apps/stock/web-app/package.json`](../../apps/stock/web-app/package.json) · [`apps/stock/web-app/vite.config.ts`](../../apps/stock/web-app/vite.config.ts) · [`apps/stock/web-app/src/features/exchanges/ExchangesPage.tsx`](../../apps/stock/web-app/src/features/exchanges/ExchangesPage.tsx)
|
||||
|
||||
## e. Open questions for the director
|
||||
|
||||
- Should the project adopt the existing scoped read-only MongoDB login for routine audits, and how should environments that only have `trading_admin` supply an equivalent login?
|
||||
- Should the design use the observed camelCase collection names as the contract, and where should any legacy `XX_` assumptions be corrected?
|
||||
- Which of `exchanges`, `symbols`, `provider_mappings` and `provider_exchange_mappings` should be extended or replaced? How does the legacy IB Mongo path fit?
|
||||
- Which sources should win conflicts for individual fields? The QM venue priority covers a narrower case within a single source.
|
||||
- Are CEO, TE and TT in scope for the next phase, and which entities or feeds should each contribute?
|
||||
- What applies schema changes to existing Postgres volumes? The repository uses numbered SQL init files and the Studio skill refers to Drizzle.
|
||||
BIN
docs/development/v2pqz94jyz0i1.jpeg
Normal file
BIN
docs/development/v2pqz94jyz0i1.jpeg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 162 KiB |
36
studio.config.json
Normal file
36
studio.config.json
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
{
|
||||
"agentExecution": {
|
||||
"programmer": {
|
||||
"shell": true,
|
||||
"networkDomains": []
|
||||
},
|
||||
"qa": {
|
||||
"shell": true,
|
||||
"networkDomains": []
|
||||
}
|
||||
},
|
||||
"test": {
|
||||
"command": "bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/pipeline-safety.test.ts",
|
||||
"env": {}
|
||||
},
|
||||
"ci": "off",
|
||||
"baseBranch": "master",
|
||||
"devBranch": "dev",
|
||||
"mergeStrategy": "ff-or-merge",
|
||||
"autoSetup": true,
|
||||
"build": {
|
||||
"command": "bun run build",
|
||||
"env": {}
|
||||
},
|
||||
"worktreeSlots": 2,
|
||||
"links": [],
|
||||
"designDir": "design",
|
||||
"docs": {
|
||||
"pitch": "design/pitch.md",
|
||||
"pillars": "design/pillars.md",
|
||||
"brand": "docs/marketing/brand.md",
|
||||
"agents": "AGENTS.md"
|
||||
},
|
||||
"modules": {},
|
||||
"autoPickup": true
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue