From 71290c8b38db93e31a91d439e3a0e962ab72f41f Mon Sep 17 00:00:00 2001 From: piggei Date: Tue, 24 Nov 2026 03:17:57 +0100 Subject: [PATCH] feat: add reusable ETF composition normalizer --- .../etf-composition.normalizer.spec.ts | 203 ++++++++++++++++++ .../etf-composition.normalizer.ts | 178 +++++++++++++++ 2 files changed, 381 insertions(+) create mode 100644 apps/api/src/services/data-provider/data-enhancer/etf-composition/etf-composition.normalizer.spec.ts create mode 100644 apps/api/src/services/data-provider/data-enhancer/etf-composition/etf-composition.normalizer.ts diff --git a/apps/api/src/services/data-provider/data-enhancer/etf-composition/etf-composition.normalizer.spec.ts b/apps/api/src/services/data-provider/data-enhancer/etf-composition/etf-composition.normalizer.spec.ts new file mode 100644 index 0000000000..9226687ddc --- /dev/null +++ b/apps/api/src/services/data-provider/data-enhancer/etf-composition/etf-composition.normalizer.spec.ts @@ -0,0 +1,203 @@ +import { normalizeEtfComposition } from './etf-composition.normalizer'; + +describe('ETF composition normalizer', () => { + describe('classified sector coverage regression', () => { + it('excludes an entirely Other distribution', () => { + const result = normalizeEtfComposition({ + sectors: [{ name: 'Other', weight: 1 }] + }); + + expect(result.sectorCoverage).toBe(1); + expect(result.classifiedSectorCoverage).toBe(0); + }); + + it('preserves 99 percent classified coverage', () => { + const result = normalizeEtfComposition({ + sectors: [ + { name: 'Information Technology', weight: 0.99 }, + { name: 'Other', weight: 0.01 } + ] + }); + + expect(result.sectorCoverage).toBe(1); + expect(result.classifiedSectorCoverage).toBe(0.99); + }); + + it('preserves 1 percent classified coverage', () => { + const result = normalizeEtfComposition({ + sectors: [ + { name: 'Information Technology', weight: 0.01 }, + { name: 'Other', weight: 0.99 } + ] + }); + + expect(result.sectorCoverage).toBe(1); + expect(result.classifiedSectorCoverage).toBe(0.01); + }); + + it('excludes unknown sectors mapped to Other', () => { + const result = normalizeEtfComposition({ + sectors: [ + { name: 'Unrecognized Sector', weight: 0.4 }, + { name: 'Financials', weight: 0.6 } + ] + }); + + expect(result.sectorCoverage).toBe(1); + expect(result.classifiedSectorCoverage).toBe(0.6); + expect(result.sectors).toContainEqual({ + name: 'Other', + weight: 0.4 + }); + }); + }); + + it('accepts ISO country codes directly', () => { + const result = normalizeEtfComposition({ + countries: [ + { name: 'US', weight: 0.6 }, + { name: 'JP', weight: 0.4 } + ] + }); + + expect(result.countries).toEqual([ + { code: 'US', weight: 0.6 }, + { code: 'JP', weight: 0.4 } + ]); + }); + + it('normalizes countries and aggregates duplicates', () => { + const result = normalizeEtfComposition({ + countries: [ + { name: 'United States', weight: 0.5 }, + { name: 'United States', weight: 0.2 }, + { name: 'Japan', weight: 0.1 } + ] + }); + + expect(result.countries).toEqual([ + { code: 'US', weight: 0.7 }, + { code: 'JP', weight: 0.1 } + ]); + + expect(result.countryCoverage).toBe(0.8); + expect(result.missingCountryWeight).toBe(0.2); + }); + + it('preserves unclassified and missing country exposure', () => { + const result = normalizeEtfComposition({ + countries: [ + { name: 'United States', weight: 0.6 }, + { name: 'Japan', weight: 0.3 }, + { name: 'Other', weight: 0.07 } + ] + }); + + expect(result.countryCoverage).toBe(0.9); + expect(result.unclassifiedCountryWeight).toBe(0.07); + expect(result.missingCountryWeight).toBe(0.03); + }); + + it('maps provider sectors to Ghostfolio ontology', () => { + const result = normalizeEtfComposition({ + sectors: [ + { name: 'Information Technology', weight: 0.2 }, + { name: 'Technology', weight: 0.1 }, + { name: 'Financials', weight: 0.15 }, + { name: 'Health Care', weight: 0.1 }, + { name: 'Consumer Discretionary', weight: 0.1 }, + { name: 'Consumer Staples', weight: 0.1 }, + { name: 'Communication', weight: 0.05 }, + { name: 'Materials', weight: 0.05 }, + { name: 'Unrecognized Sector', weight: 0.05 } + ] + }); + + expect(result.sectors).toEqual([ + { name: 'Technology', weight: 0.3 }, + { name: 'Financial Services', weight: 0.15 }, + { name: 'Healthcare', weight: 0.1 }, + { name: 'Consumer Cyclical', weight: 0.1 }, + { name: 'Consumer Defensive', weight: 0.1 }, + { name: 'Communication Services', weight: 0.05 }, + { name: 'Basic Materials', weight: 0.05 }, + { name: 'Other', weight: 0.05 } + ]); + }); + + it('rejects negative and non-finite weights', () => { + for (const weight of [-0.01, NaN, Infinity]) { + expect(() => + normalizeEtfComposition({ + countries: [{ name: 'Japan', weight }] + }) + ).toThrow('Invalid ETF exposure weight'); + } + }); + + it('rejects country allocations above 100%', () => { + expect(() => + normalizeEtfComposition({ + countries: [ + { name: 'Japan', weight: 0.7 }, + { name: 'United States', weight: 0.4 } + ] + }) + ).toThrow('ETF country weights exceed 100%'); + }); + + it('rejects sector allocations above 100%', () => { + expect(() => + normalizeEtfComposition({ + sectors: [ + { name: 'Technology', weight: 0.7 }, + { name: 'Financials', weight: 0.4 } + ] + }) + ).toThrow('ETF sector weights exceed 100%'); + }); + + it('rejects invalid exposure names', () => { + expect(() => + normalizeEtfComposition({ + countries: [{ name: ' ', weight: 0.5 }] + }) + ).toThrow('Invalid ETF exposure name'); + }); + + it('accepts floating point rounding near 100%', () => { + const result = normalizeEtfComposition({ + countries: [ + { name: 'United States', weight: 0.6 }, + { name: 'Japan', weight: 0.40000001 } + ] + }); + + expect(result.missingCountryWeight).toBe(0); + }); + + it('keeps incomplete allocations without renormalizing', () => { + const result = normalizeEtfComposition({ + countries: [ + { name: 'United States', weight: 0.6 }, + { name: 'Japan', weight: 0.1 } + ] + }); + + expect(result.countryCoverage).toBe(0.7); + expect(result.missingCountryWeight).toBe(0.3); + }); + + it('distinguishes absent and empty input', () => { + const absent = normalizeEtfComposition({}); + const empty = normalizeEtfComposition({ + countries: [], + sectors: [] + }); + + expect(absent.countries).toEqual([]); + expect(empty.countries).toEqual([]); + expect(absent.missingCountryWeight).toBe(1); + expect(empty.missingCountryWeight).toBe(1); + }); +}); diff --git a/apps/api/src/services/data-provider/data-enhancer/etf-composition/etf-composition.normalizer.ts b/apps/api/src/services/data-provider/data-enhancer/etf-composition/etf-composition.normalizer.ts new file mode 100644 index 0000000000..2163bee2de --- /dev/null +++ b/apps/api/src/services/data-provider/data-enhancer/etf-composition/etf-composition.normalizer.ts @@ -0,0 +1,178 @@ +import { getCountryCodeByName } from '@ghostfolio/api/helper/country.helper'; +import { getSectorName } from '@ghostfolio/api/helper/sector.helper'; +import { Country } from '@ghostfolio/common/interfaces/country.interface'; +import { Sector } from '@ghostfolio/common/interfaces/sector.interface'; +import { SectorName } from '@ghostfolio/common/types'; + +import { Big } from 'big.js'; +import { countries as isoCountries } from 'countries-list'; + +export interface EtfExposure { + name: string; + weight: number; +} + +export interface EtfComposition { + countries?: EtfExposure[]; + sectors?: EtfExposure[]; +} + +export interface NormalizedEtfComposition { + countries: Pick[]; + sectors: Sector[]; + countryCoverage: number; + sectorCoverage: number; + classifiedSectorCoverage: number; + unclassifiedCountryWeight: number; + missingCountryWeight: number; +} + +export const ETF_WEIGHT_TOLERANCE = 0.00001; + +const COUNTRY_ALIASES: Record = { + 'Czech Republic': 'CZ', + 'Korea, Republic of': 'KR', + 'Russian Federation': 'RU', + 'South Korea': 'KR', + Taiwan: 'TW', + Turkey: 'TR', + 'United Kingdom': 'GB', + 'United States': 'US' +}; + +const SECTOR_ALIASES: Record = { + 'Business Services': 'Industrials', + Communication: 'Communication Services', + 'Consumer Discretionary': 'Consumer Cyclical', + 'Consumer Staples': 'Consumer Defensive', + Financials: 'Financial Services', + 'Health Care': 'Healthcare', + 'Information Technology': 'Technology', + Materials: 'Basic Materials' +}; + +function validateExposure({ name, weight }: EtfExposure): void { + if (typeof name !== 'string' || name.trim().length === 0) { + throw new Error('Invalid ETF exposure name'); + } + + if ( + typeof weight !== 'number' || + !Number.isFinite(weight) || + weight < 0 || + weight > 1 + ETF_WEIGHT_TOLERANCE + ) { + throw new Error(`Invalid ETF exposure weight: ${weight}`); + } +} + +function validateTotal(weight: Big, label: string): void { + if (weight.gt(new Big(1).plus(ETF_WEIGHT_TOLERANCE))) { + throw new Error(`ETF ${label} weights exceed 100%`); + } +} + +export function normalizeEtfComposition({ + countries, + sectors +}: EtfComposition): NormalizedEtfComposition { + if (countries !== undefined && !Array.isArray(countries)) { + throw new Error('Invalid ETF country exposures'); + } + + if (sectors !== undefined && !Array.isArray(sectors)) { + throw new Error('Invalid ETF sector exposures'); + } + + const countryWeights = new Map(); + const sectorWeights = new Map(); + + let unclassifiedCountryWeight = new Big(0); + + for (const exposure of countries ?? []) { + if (!exposure || typeof exposure !== 'object') { + throw new Error('Invalid ETF country exposure'); + } + + validateExposure(exposure); + + const { name, weight } = exposure; + + const code = Object.prototype.hasOwnProperty.call(isoCountries, name) + ? name + : getCountryCodeByName({ + aliases: COUNTRY_ALIASES, + name: name.trim() + }); + + if (!code) { + unclassifiedCountryWeight = unclassifiedCountryWeight.plus(weight); + continue; + } + + countryWeights.set( + code, + (countryWeights.get(code) ?? new Big(0)).plus(weight) + ); + } + + for (const exposure of sectors ?? []) { + if (!exposure || typeof exposure !== 'object') { + throw new Error('Invalid ETF sector exposure'); + } + + validateExposure(exposure); + + const { name, weight } = exposure; + + const sector = getSectorName({ + aliases: SECTOR_ALIASES, + name: name.trim() + }); + + sectorWeights.set( + sector, + (sectorWeights.get(sector) ?? new Big(0)).plus(weight) + ); + } + + const countryCoverage = [...countryWeights.values()].reduce( + (sum, weight) => sum.plus(weight), + new Big(0) + ); + + const sectorCoverage = [...sectorWeights.values()].reduce( + (sum, weight) => sum.plus(weight), + new Big(0) + ); + + const classifiedSectorCoverage = [...sectorWeights.entries()].reduce( + (sum, [name, weight]) => (name === 'Other' ? sum : sum.plus(weight)), + new Big(0) + ); + + const totalCountryWeight = countryCoverage.plus(unclassifiedCountryWeight); + + validateTotal(totalCountryWeight, 'country'); + validateTotal(sectorCoverage, 'sector'); + + const missingCountryWeight = new Big(1).minus(totalCountryWeight); + + return { + countries: [...countryWeights.entries()].map(([code, weight]) => ({ + code, + weight: weight.toNumber() + })), + sectors: [...sectorWeights.entries()].map(([name, weight]) => ({ + name, + weight: weight.toNumber() + })), + countryCoverage: countryCoverage.toNumber(), + sectorCoverage: sectorCoverage.toNumber(), + classifiedSectorCoverage: classifiedSectorCoverage.toNumber(), + unclassifiedCountryWeight: unclassifiedCountryWeight.toNumber(), + missingCountryWeight: missingCountryWeight.lt(0) + ? 0 + : missingCountryWeight.toNumber() + }; +}