diff --git a/apps/api/src/services/benchmark/prototype/activity-matched-benchmark.pipeline.spec.ts b/apps/api/src/services/benchmark/prototype/activity-matched-benchmark.pipeline.spec.ts new file mode 100644 index 0000000000..500de4b18c --- /dev/null +++ b/apps/api/src/services/benchmark/prototype/activity-matched-benchmark.pipeline.spec.ts @@ -0,0 +1,384 @@ +import { Activity } from '@ghostfolio/common/interfaces'; +import { AssetSubClass } from '@ghostfolio/prisma/browser'; + +import { runActivityMatchedBenchmarkPipeline } from './activity-matched-benchmark.pipeline'; + +function makeActivity({ + id, + date, + value, + type = 'BUY' +}: { + id: string; + date: string; + value: number; + type?: Activity['type']; +}): Activity { + return { + id, + type, + date: new Date(`${date}T00:00:00Z`), + valueInBaseCurrency: value, + assetProfile: { + assetSubClass: AssetSubClass.ETF + } + } as Activity; +} + +describe('Activity-matched benchmark pipeline', () => { + it('evaluates ROAI over a partial range with constant invested capital', () => { + const result = runActivityMatchedBenchmarkPipeline({ + activities: [ + makeActivity({ + id: 'buy-before-range', + date: '2025-01-10', + value: 100 + }) + ], + currency: 'EUR', + benchmarkCurrency: 'EUR', + prices: [ + { date: '2025-01-10', price: '10' }, + { date: '2025-01-20', price: '12' }, + { date: '2025-01-30', price: '15' } + ], + fxQuotes: [], + valuationDates: ['2025-01-20', '2025-01-30'], + start: '2025-01-20', + end: '2025-01-30', + method: 'ROAI' + }); + + expect(result.performance.map(({ date }) => date)).toEqual([ + '2025-01-20', + '2025-01-30' + ]); + + expect(result.performance[0].returnFraction.toString()).toBe('0'); + expect(result.performance[1].netPerformance.toString()).toBe('30'); + expect(result.performance[1].capital.toString()).toBe('120'); + expect(result.performance[1].returnFraction.toString()).toBe('0.25'); + }); + + it.each([ + ['ROI', '180', '0.25'], + ['ROAI', '152.72727272727272727273', '0.29464285714285714286'] + ] as const)( + 'evaluates %s with an additional investment inside the range', + (method, expectedCapital, expectedReturn) => { + const result = runActivityMatchedBenchmarkPipeline({ + activities: [ + makeActivity({ + id: 'initial-buy', + date: '2025-01-10', + value: 100 + }), + makeActivity({ + id: 'additional-buy', + date: '2025-01-25', + value: 60 + }) + ], + currency: 'EUR', + benchmarkCurrency: 'EUR', + prices: [ + { date: '2025-01-10', price: '10' }, + { date: '2025-01-20', price: '12' }, + { date: '2025-01-25', price: '12' }, + { date: '2025-01-30', price: '15' } + ], + fxQuotes: [], + valuationDates: ['2025-01-20', '2025-01-30'], + start: '2025-01-20', + end: '2025-01-30', + method + }); + + const finalPoint = result.points.find( + ({ date }) => date === '2025-01-30' + ); + + expect(finalPoint?.units.toString()).toBe('15'); + expect(finalPoint?.value.toString()).toBe('225'); + + const finalPerformance = result.performance.at(-1); + + expect(finalPerformance?.date).toBe('2025-01-30'); + expect(finalPerformance?.netPerformance.toString()).toBe('45'); + + expect(finalPerformance?.capital.toNumber()).toBeCloseTo( + Number(expectedCapital), + 12 + ); + + expect(finalPerformance?.returnFraction.toNumber()).toBeCloseTo( + Number(expectedReturn), + 12 + ); + } + ); + + it('preserves average cost and realized gains after a SELL', () => { + const result = runActivityMatchedBenchmarkPipeline({ + activities: [ + makeActivity({ + id: 'buy', + date: '2025-01-10', + value: 100 + }), + makeActivity({ + id: 'sell', + date: '2025-01-20', + value: 60, + type: 'SELL' + }) + ], + currency: 'EUR', + benchmarkCurrency: 'EUR', + prices: [ + { date: '2025-01-10', price: '10' }, + { date: '2025-01-20', price: '12' }, + { date: '2025-01-30', price: '15' } + ], + fxQuotes: [], + valuationDates: ['2025-01-30'], + start: '2025-01-10', + end: '2025-01-30', + method: 'ROI' + }); + + const finalPoint = result.points.at(-1); + + expect(finalPoint?.units.toString()).toBe('5'); + expect(finalPoint?.costBasis.toString()).toBe('50'); + expect(finalPoint?.realizedGain.toString()).toBe('10'); + expect(finalPoint?.withdrawals.toString()).toBe('60'); + expect(finalPoint?.value.toString()).toBe('75'); + expect(finalPoint?.netPerformance.toString()).toBe('35'); + + expect(result.funding.flows).toEqual([ + { date: '2025-01-10', amount: '100' }, + { date: '2025-01-20', amount: '-60' } + ]); + }); + + it('uses Sunday FX with Friday benchmark price', () => { + const result = runActivityMatchedBenchmarkPipeline({ + activities: [ + makeActivity({ + id: 'weekend-buy', + date: '2025-01-12', + value: 90 + }) + ], + currency: 'EUR', + benchmarkCurrency: 'USD', + prices: [ + { date: '2025-01-10', price: '100' }, + { date: '2025-01-13', price: '110' } + ], + fxQuotes: [ + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-10', + rate: '0.90' + }, + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-12', + rate: '0.92' + }, + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-13', + rate: '0.93' + } + ], + valuationDates: ['2025-01-13'], + start: '2025-01-12', + end: '2025-01-13', + method: 'ROI' + }); + + expect(result.preparedPrices.carriedForward).toEqual([ + { + date: '2025-01-12', + sourceDate: '2025-01-10', + ageInDays: 2 + } + ]); + + const sourceExecutionPrice = result.preparedPrices.prices.find( + ({ date }) => date === '2025-01-12' + ); + + expect(sourceExecutionPrice).toEqual({ + date: '2025-01-12', + price: '100', + sourceDate: '2025-01-10' + }); + + const executionConversion = result.fx.conversions.find( + ({ date }) => date === '2025-01-12' + ); + + expect(executionConversion?.method).toBe('DIRECT'); + expect(executionConversion?.rate).toBe('0.92'); + expect(executionConversion?.components).toEqual([ + { + pair: 'USDEUR', + sourceDate: '2025-01-12', + ageInDays: 0, + rate: '0.92', + kind: 'MARKET' + } + ]); + + const executionPrice = result.fx.prices.find( + ({ date }) => date === '2025-01-12' + ); + + expect(executionPrice?.price).toBe('92'); + expect(executionPrice?.sourceDate).toBe('2025-01-10'); + + expect( + result.points.find(({ date }) => date === '2025-01-12')?.units.toNumber() + ).toBeCloseTo(90 / 92, 12); + }); + + it('currently retains the last converted price on display-only dates', () => { + const result = runActivityMatchedBenchmarkPipeline({ + activities: [ + makeActivity({ + id: 'initial-buy', + date: '2025-01-10', + value: 90 + }) + ], + currency: 'EUR', + benchmarkCurrency: 'USD', + prices: [ + { date: '2025-01-10', price: '100' }, + { date: '2025-01-13', price: '110' } + ], + fxQuotes: [ + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-10', + rate: '0.90' + }, + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-11', + rate: '0.91' + }, + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-12', + rate: '0.92' + }, + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-13', + rate: '0.93' + } + ], + valuationDates: ['2025-01-11', '2025-01-12'], + start: '2025-01-10', + end: '2025-01-13', + method: 'ROI' + }); + + const friday = result.points.find(({ date }) => date === '2025-01-10'); + + const saturday = result.points.find(({ date }) => date === '2025-01-11'); + + const sunday = result.points.find(({ date }) => date === '2025-01-12'); + + const monday = result.points.find(({ date }) => date === '2025-01-13'); + + expect(friday?.value.toString()).toBe('90'); + expect(friday?.displayOnly).toBeUndefined(); + + expect(saturday?.displayOnly).toBe(true); + expect(saturday?.value.toString()).toBe('90'); + + expect(sunday?.displayOnly).toBe(true); + expect(sunday?.value.toString()).toBe('90'); + + expect(monday?.displayOnly).toBeUndefined(); + expect(monday?.value.toString()).toBe('102.3'); + + expect(result.performance.map(({ date }) => date)).toEqual([ + '2025-01-10', + '2025-01-13' + ]); + + expect(result.performance.at(-1)?.netPerformance.toString()).toBe('12.3'); + }); + + it('preserves investments preceding the requested ROI range', () => { + const activities = [ + makeActivity({ + id: 'buy-before-range', + date: '2025-01-10', + value: 100 + }) + ]; + + const prices = [ + { date: '2025-01-10', price: '10' }, + { date: '2025-01-20', price: '12' }, + { date: '2025-01-30', price: '15' } + ]; + + const result = runActivityMatchedBenchmarkPipeline({ + activities, + currency: 'EUR', + benchmarkCurrency: 'EUR', + prices, + fxQuotes: [], + valuationDates: ['2025-01-20', '2025-01-30'], + start: '2025-01-20', + end: '2025-01-30', + method: 'ROI' + }); + + expect(result.funding.canSimulate).toBe(true); + expect(result.funding.flows).toEqual([ + { date: '2025-01-10', amount: '100' } + ]); + + expect( + result.points.find(({ date }) => date === '2025-01-20')?.units.toString() + ).toBe('10'); + + expect( + result.points.find(({ date }) => date === '2025-01-20')?.value.toString() + ).toBe('120'); + + expect( + result.points.find(({ date }) => date === '2025-01-30')?.value.toString() + ).toBe('150'); + + expect(result.performance.map(({ date }) => date)).toEqual([ + '2025-01-20', + '2025-01-30' + ]); + + expect(result.performance[0].returnFraction.toString()).toBe('0'); + expect(result.performance[1].netPerformance.toString()).toBe('30'); + expect(result.performance[1].capital.toString()).toBe('120'); + expect(result.performance[1].returnFraction.toString()).toBe('0.25'); + + expect(activities[0].valueInBaseCurrency).toBe(100); + expect(prices[0].price).toBe('10'); + }); +}); diff --git a/apps/api/src/services/benchmark/prototype/activity-matched-benchmark.pipeline.ts b/apps/api/src/services/benchmark/prototype/activity-matched-benchmark.pipeline.ts new file mode 100644 index 0000000000..74fc6eaff1 --- /dev/null +++ b/apps/api/src/services/benchmark/prototype/activity-matched-benchmark.pipeline.ts @@ -0,0 +1,97 @@ +import { Activity } from '@ghostfolio/common/interfaces'; + +import { + ActivityFundingResult, + createActivityFunding +} from './activity-cash-flow.provider'; +import { + BenchmarkPrice, + evaluateRange, + FinancialPoint, + simulateBenchmark +} from './activity-matched-benchmark'; +import { + BenchmarkFxQuote, + BenchmarkFxResult, + convertBenchmarkPrices +} from './benchmark-fx.adapter'; +import { + BenchmarkPriceAdapterResult, + prepareBenchmarkPrices +} from './benchmark-price.adapter'; + +export interface ActivityMatchedBenchmarkPipelineInput { + activities: Activity[]; + currency: string; + benchmarkCurrency: string; + prices: BenchmarkPrice[]; + fxQuotes: BenchmarkFxQuote[]; + valuationDates: string[]; + start: string; + end: string; + method: 'ROI' | 'ROAI'; + maxPriceAgeDays?: number; + maxFxAgeDays?: number; +} + +export interface ActivityMatchedBenchmarkPipelineResult { + funding: ActivityFundingResult; + fx: BenchmarkFxResult; + preparedPrices: BenchmarkPriceAdapterResult; + points: FinancialPoint[]; + performance: ReturnType; +} + +export function runActivityMatchedBenchmarkPipeline({ + activities, + currency, + benchmarkCurrency, + prices, + fxQuotes, + valuationDates, + start, + end, + method, + maxPriceAgeDays, + maxFxAgeDays +}: ActivityMatchedBenchmarkPipelineInput): ActivityMatchedBenchmarkPipelineResult { + const funding = createActivityFunding({ + activities, + currency + }); + + if (!funding.canSimulate) { + throw new Error('Invalid activity funding'); + } + + const preparedPrices = prepareBenchmarkPrices({ + executionDates: funding.flows.map(({ date }) => date), + prices, + maxExecutionAgeDays: maxPriceAgeDays + }); + + const fx = convertBenchmarkPrices({ + prices: preparedPrices.prices, + currencyFrom: benchmarkCurrency, + currencyTo: currency, + fxQuotes, + maxFxAgeDays + }); + + const points = simulateBenchmark({ + flows: funding.flows, + prices: fx.prices, + valuationDates, + maxPriceAgeDays + }); + + const performance = evaluateRange(points, method, start, end); + + return { + funding, + fx, + preparedPrices, + points, + performance + }; +} diff --git a/apps/api/src/services/benchmark/prototype/benchmark-display-valuation.adapter.spec.ts b/apps/api/src/services/benchmark/prototype/benchmark-display-valuation.adapter.spec.ts new file mode 100644 index 0000000000..a4d8d449ea --- /dev/null +++ b/apps/api/src/services/benchmark/prototype/benchmark-display-valuation.adapter.spec.ts @@ -0,0 +1,735 @@ +import { Activity } from '@ghostfolio/common/interfaces'; +import { AssetSubClass } from '@ghostfolio/prisma/browser'; + +import { Big } from 'big.js'; + +import { evaluateRange, FinancialPoint } from './activity-matched-benchmark'; +import { runActivityMatchedBenchmarkPipeline } from './activity-matched-benchmark.pipeline'; +import { createBenchmarkDisplayValuations } from './benchmark-display-valuation.adapter'; +import { convertBenchmarkPrices } from './benchmark-fx.adapter'; + +describe('Benchmark display FX valuation staleness', () => { + it('rejects a display valuation using an eight-day-old benchmark price', () => { + const points = [ + { + date: '2025-01-18', + displayOnly: true, + units: new Big(1) + } + ] as FinancialPoint[]; + + expect(() => + createBenchmarkDisplayValuations({ + points, + prices: [{ date: '2025-01-10', price: '100' }], + fxQuotes: [], + currencyFrom: 'EUR', + currencyTo: 'EUR', + maxPriceAgeDays: 7 + }) + ).toThrow('Stale display price: 2025-01-18'); + }); +}); + +describe('Benchmark display FX valuation without holdings', () => { + it('returns zero without requiring market data after liquidation', () => { + const points = [ + { + date: '2025-01-18', + displayOnly: true, + units: new Big(0) + } + ] as FinancialPoint[]; + + const result = createBenchmarkDisplayValuations({ + points, + prices: [], + fxQuotes: [], + currencyFrom: 'USD', + currencyTo: 'EUR' + }); + + expect(result).toEqual([ + { + date: '2025-01-18', + value: '0', + benchmarkPriceSourceDate: '', + fxComponents: [], + valuationStatus: 'NOT_APPLICABLE' + } + ]); + }); +}); + +describe('Benchmark display FX provenance', () => { + it('preserves both historical components of an indirect FX conversion', () => { + const points = [ + { + date: '2025-01-12', + displayOnly: true, + units: new Big(2) + } + ] as FinancialPoint[]; + + const result = createBenchmarkDisplayValuations({ + points, + prices: [{ date: '2025-01-10', price: '80' }], + fxQuotes: [ + { + currencyFrom: 'GBP', + currencyTo: 'USD', + date: '2025-01-10', + rate: '1.25' + }, + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-11', + rate: '0.92' + } + ], + currencyFrom: 'GBP', + currencyTo: 'EUR' + }); + + expect(result).toHaveLength(1); + expect(result[0].value).toBe('184'); + expect(result[0].benchmarkPriceSourceDate).toBe('2025-01-10'); + expect(result[0].valuationStatus).toBe('CARRIED_FORWARD'); + + expect(result[0].fxComponents).toEqual([ + { + pair: 'GBPUSD', + sourceDate: '2025-01-10', + ageInDays: 2, + rate: '1.25', + kind: 'MARKET' + }, + { + pair: 'USDEUR', + sourceDate: '2025-01-11', + ageInDays: 1, + rate: '0.92', + kind: 'MARKET' + } + ]); + + expect(result[0].fxSourceDate).toBeUndefined(); + }); +}); + +describe('Benchmark display FX independent staleness', () => { + it('rejects stale FX even when the benchmark price is recent', () => { + const points = [ + { + date: '2025-01-18', + displayOnly: true, + units: new Big(1) + } + ] as FinancialPoint[]; + + expect(() => + createBenchmarkDisplayValuations({ + points, + prices: [{ date: '2025-01-17', price: '100' }], + fxQuotes: [ + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-10', + rate: '0.90' + } + ], + currencyFrom: 'USD', + currencyTo: 'EUR', + maxPriceAgeDays: 7, + maxFxAgeDays: 7 + }) + ).toThrow('Stale FX rate: USDEUR 2025-01-18'); + }); +}); + +describe('Benchmark display FX batch parity', () => { + it('preserves input order, independent FX dates and liquidated positions', () => { + const points = [ + { + date: '2025-01-12', + displayOnly: true, + units: new Big(2) + }, + { + date: '2025-01-14', + displayOnly: true, + units: new Big(0) + }, + { + date: '2025-01-11', + displayOnly: true, + units: new Big(1) + } + ] as FinancialPoint[]; + + const result = createBenchmarkDisplayValuations({ + points, + prices: [ + { date: '2025-01-10', price: '100' }, + { date: '2025-01-13', price: '110' } + ], + fxQuotes: [ + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-10', + rate: '0.90' + }, + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-11', + rate: '0.91' + }, + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-12', + rate: '0.92' + } + ], + currencyFrom: 'USD', + currencyTo: 'EUR' + }); + + expect(result.map(({ date, value }) => ({ date, value }))).toEqual([ + { date: '2025-01-12', value: '184' }, + { date: '2025-01-14', value: '0' }, + { date: '2025-01-11', value: '91' } + ]); + + expect( + result.map(({ benchmarkPriceSourceDate }) => benchmarkPriceSourceDate) + ).toEqual(['2025-01-10', '', '2025-01-10']); + + expect(result.map(({ fxSourceDate }) => fxSourceDate)).toEqual([ + '2025-01-12', + undefined, + '2025-01-11' + ]); + + expect(result[0].fxComponents).toEqual([ + { + pair: 'USDEUR', + sourceDate: '2025-01-12', + ageInDays: 0, + rate: '0.92', + kind: 'MARKET' + } + ]); + + expect(result[1].fxComponents).toEqual([]); + expect(result[1].valuationStatus).toBe('NOT_APPLICABLE'); + + expect(result[2].fxComponents).toEqual([ + { + pair: 'USDEUR', + sourceDate: '2025-01-11', + ageInDays: 0, + rate: '0.91', + kind: 'MARKET' + } + ]); + + expect(points.map(({ date }) => date)).toEqual([ + '2025-01-12', + '2025-01-14', + '2025-01-11' + ]); + }); +}); + +describe('Benchmark display FX valuations', () => { + it('updates display-only values using independent historical FX rates', () => { + const activities = [ + { + id: 'initial-buy', + type: 'BUY', + date: new Date('2025-01-10T00:00:00Z'), + valueInBaseCurrency: 90, + assetProfile: { + assetSubClass: AssetSubClass.ETF + } + } as Activity + ]; + + const prices = [ + { date: '2025-01-10', price: '100' }, + { date: '2025-01-13', price: '110' } + ]; + + const fxQuotes = [ + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-10', + rate: '0.90' + }, + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-11', + rate: '0.91' + }, + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-12', + rate: '0.92' + }, + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-13', + rate: '0.93' + } + ]; + + const pipeline = runActivityMatchedBenchmarkPipeline({ + activities, + currency: 'EUR', + benchmarkCurrency: 'USD', + prices, + fxQuotes, + valuationDates: ['2025-01-11', '2025-01-12'], + start: '2025-01-10', + end: '2025-01-13', + method: 'ROI' + }); + + const originalValues = pipeline.points.map(({ value }) => value.toString()); + + const originalPerformance = pipeline.performance.map(({ returnFraction }) => + returnFraction.toString() + ); + + const display = createBenchmarkDisplayValuations({ + points: pipeline.points, + prices, + fxQuotes, + currencyFrom: 'USD', + currencyTo: 'EUR' + }); + + expect(display.map(({ date, value }) => ({ date, value }))).toEqual([ + { date: '2025-01-11', value: '91' }, + { date: '2025-01-12', value: '92' } + ]); + + expect( + display.map(({ benchmarkPriceSourceDate }) => benchmarkPriceSourceDate) + ).toEqual(['2025-01-10', '2025-01-10']); + + expect(display.map(({ fxSourceDate }) => fxSourceDate)).toEqual([ + '2025-01-11', + '2025-01-12' + ]); + + expect( + display.every( + ({ valuationStatus }) => valuationStatus === 'CARRIED_FORWARD' + ) + ).toBe(true); + + expect(pipeline.points.map(({ value }) => value.toString())).toEqual( + originalValues + ); + + expect( + pipeline.performance.map(({ returnFraction }) => + returnFraction.toString() + ) + ).toEqual(originalPerformance); + }); +}); + +describe('Benchmark display validation and batch contract', () => { + const point = (date = '2025-01-18', units = '1') => + ({ date, units: new Big(units), displayOnly: true }) as FinancialPoint; + const input = () => ({ + points: [point()], + prices: [{ date: '2025-01-17', price: '100', sourceDate: '2025-01-10' }], + fxQuotes: [ + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-18', + rate: '0.92' + } + ], + currencyFrom: 'USD', + currencyTo: 'EUR', + maxPriceAgeDays: 7 + }); + + it('rejects an original source price older than the limit', () => { + expect(() => createBenchmarkDisplayValuations(input())).toThrow( + 'Stale display price: 2025-01-18' + ); + }); + + it.each(['2025-02-30', 'bad-date', '2025-01-18'])( + 'rejects invalid or future source date %s', + (sourceDate) => { + const data = input(); + data.prices[0].sourceDate = sourceDate; + expect(() => createBenchmarkDisplayValuations(data)).toThrow( + sourceDate === '2025-01-18' + ? 'Invalid benchmark source date: 2025-01-18' + : `Invalid benchmark date: ${sourceDate}` + ); + } + ); + + it('uses original age at the inclusive limit and on the quotation day', () => { + const data = input(); + data.points = [point('2025-01-17')]; + data.fxQuotes[0].date = '2025-01-17'; + expect(createBenchmarkDisplayValuations(data)[0]).toMatchObject({ + value: '92', + benchmarkPriceSourceDate: '2025-01-10', + valuationStatus: 'CARRIED_FORWARD' + }); + }); + + it('uses quotation date when no source date is provided', () => { + const data = { + ...input(), + prices: [{ date: '2025-01-18', price: '0.1234567890123456789' }] + }; + expect(createBenchmarkDisplayValuations(data)[0]).toMatchObject({ + value: '0.113580245891358024588', + benchmarkPriceSourceDate: '2025-01-18', + valuationStatus: 'CURRENT' + }); + }); + + it('rejects duplicate benchmark dates rather than choosing an arbitrary price', () => { + const data = { + ...input(), + prices: [ + { date: '2025-01-18', price: '100' }, + { date: '2025-01-18', price: '101' } + ] + }; + expect(() => createBenchmarkDisplayValuations(data)).toThrow( + 'Duplicate benchmark price: 2025-01-18' + ); + }); + + it.each(['0', '-1', 'NaN', 'invalid'])( + 'rejects invalid selected benchmark price %s', + (price) => { + expect(() => + createBenchmarkDisplayValuations({ + ...input(), + prices: [{ date: '2025-01-18', price }] + }) + ).toThrow('Invalid benchmark price: 2025-01-18'); + } + ); + + it('rejects invalid quotation dates', () => { + expect(() => + createBenchmarkDisplayValuations({ + ...input(), + prices: [{ date: '2025-02-30', price: '100' }] + }) + ).toThrow('Invalid benchmark date: 2025-02-30'); + }); + + it('rejects invalid display dates', () => { + expect(() => + createBenchmarkDisplayValuations({ + ...input(), + points: [point('2025-02-30')] + }) + ).toThrow('Invalid benchmark date: 2025-02-30'); + }); + + it('rejects missing historical benchmark data', () => { + expect(() => + createBenchmarkDisplayValuations({ + ...input(), + points: [point('2025-01-09')] + }) + ).toThrow('Missing display price: 2025-01-09'); + }); + + it.each(['invalid', 'duplicate', 'missing'])('rejects %s FX data', (kind) => { + const data = { ...input(), prices: [{ date: '2025-01-18', price: '100' }] }; + if (kind === 'invalid') data.fxQuotes[0].date = '2025-02-30'; + if (kind === 'duplicate') data.fxQuotes.push({ ...data.fxQuotes[0] }); + if (kind === 'missing') data.fxQuotes = []; + expect(() => createBenchmarkDisplayValuations(data)).toThrow( + kind === 'invalid' + ? 'Invalid FX date: 2025-02-30' + : kind === 'duplicate' + ? 'Duplicate FX rate: USDEUR 2025-01-18' + : 'Missing FX rate: USDEUR 2025-01-18' + ); + }); + + it('preserves unsorted duplicate display points and does not mutate caller data', () => { + const data = { + ...input(), + prices: [{ date: '2025-01-17', price: '100' }], + points: [ + point(), + point('2025-01-17', '2'), + point(), + point('2025-01-19', '0') + ] + }; + data.fxQuotes.push({ + ...data.fxQuotes[0], + date: '2025-01-17', + rate: '0.9' + }); + const before = JSON.stringify(data); + for (const array of [data.points, data.prices, data.fxQuotes]) { + array.forEach(Object.freeze); + Object.freeze(array); + } + const batch = createBenchmarkDisplayValuations(data); + expect(batch).toEqual( + data.points.flatMap((p) => + createBenchmarkDisplayValuations({ ...data, points: [p] }) + ) + ); + expect(batch.map(({ value }) => value)).toEqual(['92', '180', '92', '0']); + expect(JSON.stringify(data)).toBe(before); + }); + + it('returns empty for empty or exclusively financial points', () => { + expect( + createBenchmarkDisplayValuations({ ...input(), points: [] }) + ).toEqual([]); + expect( + createBenchmarkDisplayValuations({ + ...input(), + points: [{ ...point(), displayOnly: false }] + }) + ).toEqual([]); + }); + + it('does not require FX or prices for exclusively zero holdings', () => { + expect( + createBenchmarkDisplayValuations({ + ...input(), + points: [point('2025-01-18', '0')], + prices: [], + fxQuotes: [] + })[0].valuationStatus + ).toBe('NOT_APPLICABLE'); + }); + + it('reports benchmark preparation errors before batch FX errors', () => { + const data = { + ...input(), + prices: [{ date: '2025-01-17', price: '100' }], + points: [point('2025-01-18'), point('2025-02-01')], + fxQuotes: [] + }; + expect(() => createBenchmarkDisplayValuations(data)).toThrow( + 'Stale display price: 2025-02-01' + ); + }); +}); + +describe('Benchmark display conversion provenance across a batch', () => { + it.each([ + [ + 'USD', + 'EUR', + [ + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-10', + rate: '0.92' + } + ], + '184' + ], + [ + 'EUR', + 'USD', + [ + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-10', + rate: '0.8' + } + ], + '250' + ], + [ + 'GBP', + 'EUR', + [ + { + currencyFrom: 'GBP', + currencyTo: 'USD', + date: '2025-01-10', + rate: '1.25' + }, + { + currencyFrom: 'USD', + currencyTo: 'EUR', + date: '2025-01-11', + rate: '0.92' + } + ], + '230' + ], + ['GBp', 'GBP', [], '2'], + ['GBP', 'GBp', [], '20000'], + [ + 'GBp', + 'EUR', + [ + { + currencyFrom: 'GBP', + currencyTo: 'EUR', + date: '2025-01-10', + rate: '1.2' + } + ], + '2.4' + ], + [ + 'EUR', + 'GBp', + [ + { + currencyFrom: 'EUR', + currencyTo: 'GBP', + date: '2025-01-10', + rate: '0.8' + } + ], + '16000' + ] + ])( + 'retains every component for %s to %s', + (currencyFrom, currencyTo, fxQuotes, value) => { + const dates = ['2025-01-12', '2025-01-11', '2025-01-12']; + const prices = [{ date: '2025-01-10', price: '100' }]; + const points = dates.map((date) => ({ + date, + displayOnly: true, + units: new Big(2) + })) as FinancialPoint[]; + const data = { points, prices, fxQuotes, currencyFrom, currencyTo }; + const batch = createBenchmarkDisplayValuations(data); + expect(batch).toEqual( + points.flatMap((point) => + createBenchmarkDisplayValuations({ ...data, points: [point] }) + ) + ); + for (const [i, result] of batch.entries()) { + const conversion = convertBenchmarkPrices({ + prices: [{ date: dates[i], price: '100' }], + fxQuotes, + currencyFrom, + currencyTo + }).conversions[0]; + const market = conversion.components.filter( + ({ kind }) => kind === 'MARKET' + ); + expect(result.value).toBe(value); + expect(result.fxComponents).toEqual(conversion.components); + expect(result.fxSourceDate).toBe( + market.length === 1 ? market[0].sourceDate : undefined + ); + } + } + ); +}); + +describe('Benchmark display financial isolation', () => { + it.each(['ROI', 'ROAI'] as const)( + 'preserves all financial state and %s through partial and full liquidation', + (method) => { + const activities = [ + { + id: 'buy', + type: 'BUY', + date: new Date('2025-01-10T00:00:00Z'), + valueInBaseCurrency: 100 + }, + { + id: 'partial', + type: 'SELL', + date: new Date('2025-01-13T00:00:00Z'), + valueInBaseCurrency: 60 + }, + { + id: 'liquidate', + type: 'SELL', + date: new Date('2025-01-16T00:00:00Z'), + valueInBaseCurrency: 75 + } + ].map((activity) => ({ + ...activity, + assetProfile: { assetSubClass: AssetSubClass.ETF } + })) as Activity[]; + const prices = [ + { date: '2025-01-10', price: '10' }, + { date: '2025-01-13', price: '12' }, + { date: '2025-01-16', price: '15' } + ]; + const pipeline = runActivityMatchedBenchmarkPipeline({ + activities, + currency: 'EUR', + benchmarkCurrency: 'EUR', + prices, + fxQuotes: [], + valuationDates: ['2025-01-11', '2025-01-14', '2025-01-17'], + start: '2025-01-10', + end: '2025-01-17', + method + }); + const before = JSON.stringify(pipeline); + const performance = evaluateRange( + pipeline.points, + method, + '2025-01-10', + '2025-01-17' + ); + pipeline.points.forEach(Object.freeze); + Object.freeze(pipeline.points); + const display = createBenchmarkDisplayValuations({ + points: pipeline.points, + prices, + fxQuotes: [ + { + currencyFrom: 'EUR', + currencyTo: 'USD', + date: '2025-01-10', + rate: '2' + } + ], + currencyFrom: 'EUR', + currencyTo: 'USD' + }); + expect(display.map(({ value }) => value)).toEqual(['200', '120', '0']); + expect(display.at(-1)?.valuationStatus).toBe('NOT_APPLICABLE'); + expect(pipeline.points.at(-1)?.units.toString()).toBe('0'); + expect(JSON.stringify(pipeline)).toBe(before); + expect( + evaluateRange(pipeline.points, method, '2025-01-10', '2025-01-17') + ).toEqual(performance); + expect(pipeline.performance).toEqual(performance); + } + ); +}); diff --git a/apps/api/src/services/benchmark/prototype/benchmark-display-valuation.adapter.ts b/apps/api/src/services/benchmark/prototype/benchmark-display-valuation.adapter.ts new file mode 100644 index 0000000000..43f4391c07 --- /dev/null +++ b/apps/api/src/services/benchmark/prototype/benchmark-display-valuation.adapter.ts @@ -0,0 +1,204 @@ +import { Big } from 'big.js'; + +import { + BenchmarkPrice, + BenchmarkValuationStatus, + FinancialPoint +} from './activity-matched-benchmark'; +import { + BenchmarkFxComponent, + BenchmarkFxQuote, + convertBenchmarkPrices +} from './benchmark-fx.adapter'; +import { + DEFAULT_MAX_PRICE_AGE_DAYS, + validateMaxPriceAgeDays +} from './benchmark-price-policy'; + +export interface BenchmarkDisplayValuation { + date: string; + value: string; + benchmarkPriceSourceDate: string; + fxSourceDate?: string; + fxComponents: BenchmarkFxComponent[]; + valuationStatus: BenchmarkValuationStatus; +} + +export interface BenchmarkDisplayValuationInput { + points: FinancialPoint[]; + prices: BenchmarkPrice[]; + fxQuotes: BenchmarkFxQuote[]; + currencyFrom: string; + currencyTo: string; + maxPriceAgeDays?: number; + maxFxAgeDays?: number; +} + +function calendarDay(date: string): number { + const time = Date.parse(`${date}T00:00:00Z`); + + if ( + !/^\d{4}-\d{2}-\d{2}$/.test(date) || + !Number.isFinite(time) || + new Date(time).toISOString().slice(0, 10) !== date + ) { + throw new Error(`Invalid benchmark date: ${date}`); + } + + return time / 86400000; +} + +export function createBenchmarkDisplayValuations({ + points, + prices, + fxQuotes, + currencyFrom, + currencyTo, + maxPriceAgeDays = DEFAULT_MAX_PRICE_AGE_DAYS, + maxFxAgeDays +}: BenchmarkDisplayValuationInput): BenchmarkDisplayValuation[] { + validateMaxPriceAgeDays(maxPriceAgeDays); + + const displayPoints = points.filter(({ displayOnly }) => displayOnly); + + if (displayPoints.length === 0) { + return []; + } + + const quotes = prices + .map((price) => { + const day = calendarDay(price.date); + const sourceDate = price.sourceDate ?? price.date; + const sourceDay = + sourceDate === price.date ? day : calendarDay(sourceDate); + + if (sourceDay > day) { + throw new Error(`Invalid benchmark source date: ${sourceDate}`); + } + + return { ...price, day, sourceDate, sourceDay }; + }) + .sort((a, b) => a.day - b.day); + + for (let i = 1; i < quotes.length; i++) { + if (quotes[i].day === quotes[i - 1].day) { + throw new Error(`Duplicate benchmark price: ${quotes[i].date}`); + } + } + + const findLatestPrice = (targetDay: number) => { + let low = 0; + let high = quotes.length - 1; + let result: (typeof quotes)[number] | undefined; + + while (low <= high) { + const middle = Math.floor((low + high) / 2); + const quote = quotes[middle]; + + if (quote.day <= targetDay) { + result = quote; + low = middle + 1; + } else { + high = middle - 1; + } + } + + return result; + }; + + // Validate benchmark history and display points before converting FX once. + // If several inputs are invalid, preparation errors precede batch FX errors; + // display points retain caller order in preparation and conversion. + const prepared = displayPoints.map((point) => { + const targetDay = calendarDay(point.date); + + if (!point.units.gt(0)) { + return { + point, + price: undefined, + sourceDate: undefined, + ageInDays: 0 + }; + } + + const quote = findLatestPrice(targetDay); + + if (!quote) { + throw new Error(`Missing display price: ${point.date}`); + } + + const ageInDays = targetDay - quote.sourceDay; + + if (ageInDays > maxPriceAgeDays) { + throw new Error(`Stale display price: ${point.date}`); + } + + return { + point, + price: { + date: point.date, + price: quote.price, + sourceDate: quote.sourceDate + }, + sourceDate: quote.sourceDate, + ageInDays + }; + }); + + const active = prepared.filter( + ( + item + ): item is typeof item & { + price: BenchmarkPrice; + } => item.price !== undefined + ); + + const converted = + active.length > 0 + ? convertBenchmarkPrices({ + prices: active.map(({ price }) => price), + currencyFrom, + currencyTo, + fxQuotes, + maxFxAgeDays + }) + : { prices: [], conversions: [] }; + + let conversionIndex = 0; + + return prepared.map(({ point, price, sourceDate, ageInDays }) => { + if (!price) { + return { + date: point.date, + value: '0', + benchmarkPriceSourceDate: '', + fxComponents: [], + valuationStatus: 'NOT_APPLICABLE' + }; + } + + const convertedPrice = converted.prices[conversionIndex]; + const conversion = converted.conversions[conversionIndex]; + + conversionIndex += 1; + + const fxComponents = conversion.components; + const marketComponents = fxComponents.filter( + ({ kind }) => kind === 'MARKET' + ); + + const fxSourceDate = + marketComponents.length === 1 + ? marketComponents[0].sourceDate + : undefined; + + return { + date: point.date, + value: point.units.mul(new Big(convertedPrice.price)).toString(), + benchmarkPriceSourceDate: sourceDate, + ...(fxSourceDate ? { fxSourceDate } : {}), + fxComponents, + valuationStatus: ageInDays === 0 ? 'CURRENT' : 'CARRIED_FORWARD' + }; + }); +} diff --git a/apps/api/src/services/benchmark/prototype/benchmark-display-valuation.performance.spec.ts b/apps/api/src/services/benchmark/prototype/benchmark-display-valuation.performance.spec.ts new file mode 100644 index 0000000000..59b9d84ca8 --- /dev/null +++ b/apps/api/src/services/benchmark/prototype/benchmark-display-valuation.performance.spec.ts @@ -0,0 +1,98 @@ +import { Big } from 'big.js'; +import { performance } from 'node:perf_hooks'; + +import { FinancialPoint } from './activity-matched-benchmark'; +import { createBenchmarkDisplayValuations } from './benchmark-display-valuation.adapter'; + +const date = (day: number): string => + new Date(Date.UTC(2000, 0, 1 + day)).toISOString().slice(0, 10); + +function percentileMetrics(samples: number[]) { + const sorted = [...samples].sort((a, b) => a - b); + + return [Number(sorted[3].toFixed(2)), Number(sorted[6].toFixed(2))]; +} + +(process.env.BENCHMARK_PERFORMANCE ? describe : describe.skip)( + 'benchmark display FX profiling', + () => { + it('profiles historical display valuations', () => { + const rows = []; + + for (const count of [365, 1825, 3650]) { + const points = Array.from({ length: count }, (_, i) => ({ + date: date(i), + displayOnly: true, + units: new Big(1) + })) as FinancialPoint[]; + + const prices = Array.from({ length: count }, (_, i) => ({ + date: date(i), + price: String(100 + (i % 17)) + })); + + const fxQuotes = Array.from({ length: count }, (_, i) => ({ + currencyFrom: 'USD', + currencyTo: 'EUR', + date: date(i), + rate: String(0.9 + (i % 10) / 100) + })); + + const execute = () => { + const start = performance.now(); + + const result = createBenchmarkDisplayValuations({ + points, + prices, + fxQuotes, + currencyFrom: 'USD', + currencyTo: 'EUR' + }); + + const elapsed = performance.now() - start; + + return { elapsed, result }; + }; + + execute(); + + const samples = Array.from({ length: 7 }, execute); + + const expected = samples[0].result; + + expect(expected).toHaveLength(count); + + expected.forEach((valuation, i) => { + expect(valuation).toMatchObject({ + date: date(i), + value: new Big(prices[i].price).mul(fxQuotes[i].rate).toString(), + benchmarkPriceSourceDate: date(i), + fxSourceDate: date(i), + valuationStatus: 'CURRENT' + }); + }); + + for (const sample of samples) { + expect(sample.result).toEqual(expected); + } + + rows.push({ + displayDates: count, + fxQuotes: fxQuotes.length, + benchmarkPrices: prices.length, + total: percentileMetrics(samples.map(({ elapsed }) => elapsed)) + }); + } + + console.log( + JSON.stringify({ + label: process.env.PROFILE_LABEL ?? 'display-fx-baseline', + units: 'ms [median,p95]', + warmups: 1, + repeats: 7, + rows + }) + ); + }); + } +);