Browse Source

feat(benchmark): integrate historical market data and FX providers

pull/8438/head
piggei 3 weeks ago
parent
commit
902c6d80a9
  1. 16
      apps/api/src/services/benchmark/prototype/activity-cash-flow.provider.spec.ts
  2. 3
      apps/api/src/services/benchmark/prototype/activity-cash-flow.provider.ts
  3. 20
      apps/api/src/services/benchmark/prototype/benchmark-date-range.ts
  4. 191
      apps/api/src/services/benchmark/prototype/benchmark-fx-market-data.provider.spec.ts
  5. 67
      apps/api/src/services/benchmark/prototype/benchmark-fx-market-data.provider.ts
  6. 74
      apps/api/src/services/benchmark/prototype/benchmark-fx-pairs.spec.ts
  7. 64
      apps/api/src/services/benchmark/prototype/benchmark-fx-pairs.ts
  8. 30
      apps/api/src/services/benchmark/prototype/benchmark-fx.adapter.spec.ts
  9. 13
      apps/api/src/services/benchmark/prototype/benchmark-market-data.adapter.spec.ts
  10. 5
      apps/api/src/services/benchmark/prototype/benchmark-market-data.adapter.ts
  11. 172
      apps/api/src/services/benchmark/prototype/benchmark-market-data.provider.spec.ts
  12. 62
      apps/api/src/services/benchmark/prototype/benchmark-market-data.provider.ts

16
apps/api/src/services/benchmark/prototype/activity-cash-flow.provider.spec.ts

@ -26,6 +26,22 @@ function makeActivity({
} }
describe('ActivityCashFlowProvider', () => { describe('ActivityCashFlowProvider', () => {
it('preserves the UTC calendar date of activities', () => {
const result = createActivityFunding({
activities: [
makeActivity({
id: 'utc-midnight',
date: new Date('2025-01-10T00:00:00.000Z')
})
],
currency: 'EUR'
});
expect(result.canSimulate).toBe(true);
expect(result.events[0].date).toBe('2025-01-10');
expect(result.flows[0].date).toBe('2025-01-10');
});
it('converts BUY and SELL into signed investment proxies', () => { it('converts BUY and SELL into signed investment proxies', () => {
const result = createActivityFunding({ const result = createActivityFunding({
activities: [ activities: [

3
apps/api/src/services/benchmark/prototype/activity-cash-flow.provider.ts

@ -1,6 +1,7 @@
import { Activity } from '@ghostfolio/common/interfaces'; import { Activity } from '@ghostfolio/common/interfaces';
import { AssetSubClass } from '@ghostfolio/prisma/browser'; import { AssetSubClass } from '@ghostfolio/prisma/browser';
import { utc } from '@date-fns/utc';
import { Big } from 'big.js'; import { Big } from 'big.js';
import { format } from 'date-fns'; import { format } from 'date-fns';
@ -95,7 +96,7 @@ export function createActivityFunding({
activityType: activity.type, activityType: activity.type,
amount: (activity.type === 'BUY' ? amount : amount.neg()).toString(), amount: (activity.type === 'BUY' ? amount : amount.neg()).toString(),
currency, currency,
date: format(activity.date, 'yyyy-MM-dd'), date: format(activity.date, 'yyyy-MM-dd', { in: utc }),
source: 'ACTIVITY_PROXY' source: 'ACTIVITY_PROXY'
}); });
} }

20
apps/api/src/services/benchmark/prototype/benchmark-date-range.ts

@ -0,0 +1,20 @@
export function validateBenchmarkDateRange({
startDate,
endDate
}: {
startDate: Date;
endDate: Date;
}): void {
if (
!(startDate instanceof Date) ||
!(endDate instanceof Date) ||
!Number.isFinite(startDate.getTime()) ||
!Number.isFinite(endDate.getTime())
) {
throw new Error('Invalid benchmark date range');
}
if (startDate > endDate) {
throw new Error('Reversed benchmark date range');
}
}

191
apps/api/src/services/benchmark/prototype/benchmark-fx-market-data.provider.spec.ts

@ -0,0 +1,191 @@
import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service';
import { BenchmarkFxMarketDataProvider } from './benchmark-fx-market-data.provider';
import { convertBenchmarkPrices } from './benchmark-fx.adapter';
import { BenchmarkMarketDataProvider } from './benchmark-market-data.provider';
describe('Benchmark FX historical MarketData provider', () => {
const getDataSourceForExchangeRates = jest.fn();
const getHistoricalPrices = jest.fn();
const provider = new BenchmarkFxMarketDataProvider(
{
getDataSourceForExchangeRates
} as unknown as DataProviderService,
{
getHistoricalPrices
} as unknown as BenchmarkMarketDataProvider
);
const startDate = new Date('2025-01-10T00:00:00Z');
const endDate = new Date('2025-01-15T00:00:00Z');
beforeEach(() => {
getDataSourceForExchangeRates.mockReset();
getHistoricalPrices.mockReset();
getDataSourceForExchangeRates.mockReturnValue('YAHOO');
getHistoricalPrices.mockImplementation(async ({ symbol }) => ({
prices:
symbol === 'GBPEUR' ? [{ date: '2025-01-10', price: '1.15' }] : [],
excludedCarriedForward: 0,
excludedIntraday: 0
}));
});
it('does not query MarketData for identical currencies', async () => {
const result = await provider.getHistoricalFxQuotes({
currencyFrom: 'EUR',
currencyTo: 'EUR',
startDate,
endDate
});
expect(result).toEqual([]);
expect(getHistoricalPrices).not.toHaveBeenCalled();
expect(getDataSourceForExchangeRates).not.toHaveBeenCalled();
});
it('does not query MarketData for derived currencies sharing a root', async () => {
const result = await provider.getHistoricalFxQuotes({
currencyFrom: 'GBP',
currencyTo: 'GBp',
startDate,
endDate
});
expect(result).toEqual([]);
expect(getHistoricalPrices).not.toHaveBeenCalled();
});
it('rejects invalid dates even for identical currencies', async () => {
await expect(
provider.getHistoricalFxQuotes({
currencyFrom: 'EUR',
currencyTo: 'EUR',
startDate: new Date(NaN),
endDate
})
).rejects.toThrow('Invalid benchmark date range');
expect(getHistoricalPrices).not.toHaveBeenCalled();
expect(getDataSourceForExchangeRates).not.toHaveBeenCalled();
});
it('rejects reversed ranges for derived currencies', async () => {
await expect(
provider.getHistoricalFxQuotes({
currencyFrom: 'GBP',
currencyTo: 'GBp',
startDate: endDate,
endDate: startDate
})
).rejects.toThrow('Reversed benchmark date range');
expect(getHistoricalPrices).not.toHaveBeenCalled();
});
it('rejects invalid dates before retrieving FX market data', async () => {
await expect(
provider.getHistoricalFxQuotes({
currencyFrom: 'GBP',
currencyTo: 'EUR',
startDate,
endDate: new Date(NaN)
})
).rejects.toThrow('Invalid benchmark date range');
expect(getHistoricalPrices).not.toHaveBeenCalled();
expect(getDataSourceForExchangeRates).not.toHaveBeenCalled();
});
it('uses the configured FX data source', async () => {
await provider.getHistoricalFxQuotes({
currencyFrom: 'GBP',
currencyTo: 'EUR',
startDate,
endDate
});
expect(getDataSourceForExchangeRates).toHaveBeenCalledTimes(1);
expect(getHistoricalPrices).toHaveBeenCalledWith(
expect.objectContaining({
dataSource: 'YAHOO',
symbol: 'GBPEUR',
startDate,
endDate
})
);
});
it('retrieves all six candidate pairs for GBP to EUR', async () => {
await provider.getHistoricalFxQuotes({
currencyFrom: 'GBP',
currencyTo: 'EUR',
startDate,
endDate
});
expect(
getHistoricalPrices.mock.calls.map(([input]) => input.symbol)
).toEqual(['GBPEUR', 'EURGBP', 'USDGBP', 'GBPUSD', 'USDEUR', 'EURUSD']);
});
it('preserves original FX quotation dates and values', async () => {
const result = await provider.getHistoricalFxQuotes({
currencyFrom: 'GBP',
currencyTo: 'EUR',
startDate,
endDate
});
expect(result).toEqual([
{
currencyFrom: 'GBP',
currencyTo: 'EUR',
date: '2025-01-10',
rate: '1.15'
}
]);
});
it('integrates with the historical FX converter', async () => {
const fxQuotes = await provider.getHistoricalFxQuotes({
currencyFrom: 'GBP',
currencyTo: 'EUR',
startDate,
endDate
});
const result = convertBenchmarkPrices({
prices: [{ date: '2025-01-12', price: '100' }],
currencyFrom: 'GBP',
currencyTo: 'EUR',
fxQuotes
});
expect(result.prices[0].price).toBe('115');
expect(result.conversions[0].components[0]).toEqual({
pair: 'GBPEUR',
sourceDate: '2025-01-10',
ageInDays: 2,
rate: '1.15',
kind: 'MARKET'
});
});
it('propagates historical data retrieval errors', async () => {
getHistoricalPrices.mockRejectedValue(new Error('MarketData unavailable'));
await expect(
provider.getHistoricalFxQuotes({
currencyFrom: 'GBP',
currencyTo: 'EUR',
startDate,
endDate
})
).rejects.toThrow('MarketData unavailable');
});
});

67
apps/api/src/services/benchmark/prototype/benchmark-fx-market-data.provider.ts

@ -0,0 +1,67 @@
import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service';
import { Injectable } from '@nestjs/common';
import { validateBenchmarkDateRange } from './benchmark-date-range';
import { getBenchmarkFxPairs } from './benchmark-fx-pairs';
import { BenchmarkFxQuote } from './benchmark-fx.adapter';
import { BenchmarkMarketDataProvider } from './benchmark-market-data.provider';
export interface BenchmarkHistoricalFxInput {
currencyFrom: string;
currencyTo: string;
startDate: Date;
endDate: Date;
}
@Injectable()
export class BenchmarkFxMarketDataProvider {
public constructor(
private readonly dataProviderService: DataProviderService,
private readonly benchmarkMarketDataProvider: BenchmarkMarketDataProvider
) {}
public async getHistoricalFxQuotes({
currencyFrom,
currencyTo,
startDate,
endDate
}: BenchmarkHistoricalFxInput): Promise<BenchmarkFxQuote[]> {
validateBenchmarkDateRange({ startDate, endDate });
const pairs = getBenchmarkFxPairs({
currencyFrom,
currencyTo
});
if (pairs.length === 0) {
return [];
}
const dataSource = this.dataProviderService.getDataSourceForExchangeRates();
const quotes: BenchmarkFxQuote[] = [];
for (const pair of pairs) {
const result = await this.benchmarkMarketDataProvider.getHistoricalPrices(
{
dataSource,
symbol: pair.symbol,
startDate,
endDate
}
);
for (const price of result.prices) {
quotes.push({
currencyFrom: pair.currencyFrom,
currencyTo: pair.currencyTo,
date: price.date,
rate: price.price
});
}
}
return quotes;
}
}

74
apps/api/src/services/benchmark/prototype/benchmark-fx-pairs.spec.ts

@ -0,0 +1,74 @@
import { getBenchmarkFxPairs } from './benchmark-fx-pairs';
describe('Benchmark FX candidate pairs', () => {
const symbols = (currencyFrom: string, currencyTo: string) =>
getBenchmarkFxPairs({ currencyFrom, currencyTo }).map(
({ symbol }) => symbol
);
it('requires no FX quotes for identical currencies', () => {
expect(symbols('EUR', 'EUR')).toEqual([]);
});
it('requires no market FX for derived currencies sharing a root', () => {
expect(symbols('GBP', 'GBp')).toEqual([]);
expect(symbols('GBp', 'GBP')).toEqual([]);
});
it('includes both directions for a USD conversion', () => {
expect(symbols('USD', 'EUR')).toEqual(['USDEUR', 'EURUSD']);
});
it('includes direct, inverse and USD bridge candidates', () => {
expect(symbols('GBP', 'EUR')).toEqual([
'GBPEUR',
'EURGBP',
'USDGBP',
'GBPUSD',
'USDEUR',
'EURUSD'
]);
});
it('normalizes a derived source currency', () => {
expect(symbols('GBp', 'EUR')).toEqual(symbols('GBP', 'EUR'));
});
it('normalizes a derived target currency', () => {
expect(symbols('EUR', 'GBp')).toEqual(symbols('EUR', 'GBP'));
});
it('does not introduce duplicate symbols', () => {
for (const [currencyFrom, currencyTo] of [
['USD', 'EUR'],
['GBP', 'EUR'],
['GBp', 'EUR'],
['EUR', 'GBp'],
['GBP', 'GBp']
]) {
const result = symbols(currencyFrom, currencyTo);
expect(new Set(result).size).toBe(result.length);
}
});
it('preserves pair direction metadata', () => {
expect(
getBenchmarkFxPairs({
currencyFrom: 'USD',
currencyTo: 'EUR'
})
).toEqual([
{
currencyFrom: 'USD',
currencyTo: 'EUR',
symbol: 'USDEUR'
},
{
currencyFrom: 'EUR',
currencyTo: 'USD',
symbol: 'EURUSD'
}
]);
});
});

64
apps/api/src/services/benchmark/prototype/benchmark-fx-pairs.ts

@ -0,0 +1,64 @@
import {
DEFAULT_CURRENCY,
DERIVED_CURRENCIES
} from '@ghostfolio/common/config';
export interface BenchmarkFxPair {
currencyFrom: string;
currencyTo: string;
symbol: string;
}
export function getBenchmarkFxPairs({
currencyFrom,
currencyTo
}: {
currencyFrom: string;
currencyTo: string;
}): BenchmarkFxPair[] {
if (currencyFrom === currencyTo) {
return [];
}
const rootFrom =
DERIVED_CURRENCIES.find(({ currency }) => currency === currencyFrom)
?.rootCurrency ?? currencyFrom;
const rootTo =
DERIVED_CURRENCIES.find(({ currency }) => currency === currencyTo)
?.rootCurrency ?? currencyTo;
if (rootFrom === rootTo) {
return [];
}
const pairs = new Map<string, BenchmarkFxPair>();
const addPair = (from: string, to: string) => {
if (from === to) {
return;
}
const symbol = `${from}${to}`;
pairs.set(symbol, {
currencyFrom: from,
currencyTo: to,
symbol
});
};
const addBothDirections = (from: string, to: string) => {
addPair(from, to);
addPair(to, from);
};
addBothDirections(rootFrom, rootTo);
if (rootFrom !== DEFAULT_CURRENCY && rootTo !== DEFAULT_CURRENCY) {
addBothDirections(DEFAULT_CURRENCY, rootFrom);
addBothDirections(DEFAULT_CURRENCY, rootTo);
}
return [...pairs.values()];
}

30
apps/api/src/services/benchmark/prototype/benchmark-fx.adapter.spec.ts

@ -182,6 +182,36 @@ describe('Benchmark historical FX adapter', () => {
).toThrow('Stale FX rate: USDEUR 2025-01-18'); ).toThrow('Stale FX rate: USDEUR 2025-01-18');
}); });
it('does not fall back to USD when a direct pair starts after the valuation date', () => {
expect(() =>
convertBenchmarkPrices({
prices: [{ date: '2025-01-05', price: '100' }],
currencyFrom: 'GBP',
currencyTo: 'EUR',
fxQuotes: [
{
currencyFrom: 'GBP',
currencyTo: 'EUR',
date: '2025-01-10',
rate: '1.15'
},
{
currencyFrom: 'GBP',
currencyTo: 'USD',
date: '2025-01-02',
rate: '1.25'
},
{
currencyFrom: 'USD',
currencyTo: 'EUR',
date: '2025-01-02',
rate: '0.92'
}
]
})
).toThrow('Missing FX rate: GBPEUR 2025-01-05');
});
it('converts indirectly from GBP to EUR through USD', () => { it('converts indirectly from GBP to EUR through USD', () => {
const result = convertBenchmarkPrices({ const result = convertBenchmarkPrices({
prices: [{ date: '2025-01-10', price: '80' }], prices: [{ date: '2025-01-10', price: '80' }],

13
apps/api/src/services/benchmark/prototype/benchmark-market-data.adapter.spec.ts

@ -26,6 +26,19 @@ function marketData({
} }
describe('Benchmark MarketData adapter', () => { describe('Benchmark MarketData adapter', () => {
it('preserves the UTC calendar date of original quotations', () => {
const result = adaptBenchmarkMarketData({
marketData: [
marketData({
date: '2025-01-10',
price: 100
})
]
});
expect(result.prices[0].date).toBe('2025-01-10');
});
it('keeps original CLOSE prices in chronological order', () => { it('keeps original CLOSE prices in chronological order', () => {
const result = adaptBenchmarkMarketData({ const result = adaptBenchmarkMarketData({
marketData: [ marketData: [

5
apps/api/src/services/benchmark/prototype/benchmark-market-data.adapter.ts

@ -1,3 +1,4 @@
import { utc } from '@date-fns/utc';
import { MarketData } from '@prisma/client'; import { MarketData } from '@prisma/client';
import { Big } from 'big.js'; import { Big } from 'big.js';
import { format } from 'date-fns'; import { format } from 'date-fns';
@ -36,14 +37,14 @@ export function adaptBenchmarkMarketData({
if (!Number.isFinite(item.marketPrice) || item.marketPrice <= 0) { if (!Number.isFinite(item.marketPrice) || item.marketPrice <= 0) {
throw new Error( throw new Error(
`Invalid benchmark market price: ${format(item.date, 'yyyy-MM-dd')}` `Invalid benchmark market price: ${format(item.date, 'yyyy-MM-dd', { in: utc })}`
); );
} }
const price = new Big(item.marketPrice); const price = new Big(item.marketPrice);
prices.push({ prices.push({
date: format(item.date, 'yyyy-MM-dd'), date: format(item.date, 'yyyy-MM-dd', { in: utc }),
price: price.toString() price: price.toString()
}); });
} }

172
apps/api/src/services/benchmark/prototype/benchmark-market-data.provider.spec.ts

@ -0,0 +1,172 @@
import { MarketDataService } from '@ghostfolio/api/services/market-data/market-data.service';
import { MarketData } from '@prisma/client';
import { BenchmarkMarketDataProvider } from './benchmark-market-data.provider';
import { prepareBenchmarkPrices } from './benchmark-price.adapter';
function quote({
date,
price = 100,
carriedForward = false,
state = 'CLOSE'
}: {
date: string;
price?: number;
carriedForward?: boolean;
state?: MarketData['state'];
}): MarketData {
return {
id: `quote-${date}`,
createdAt: new Date('2025-01-01T00:00:00Z'),
dataSource: 'YAHOO',
symbol: 'SPY',
date: new Date(`${date}T00:00:00Z`),
marketPrice: price,
isCarriedForward: carriedForward,
state
};
}
describe('Benchmark historical MarketData provider', () => {
const startDate = new Date('2025-01-11T00:00:00Z');
const endDate = new Date('2025-01-15T00:00:00Z');
const records = [
quote({ date: '2025-01-03', price: 90 }),
quote({ date: '2025-01-10', price: 100 }),
quote({
date: '2025-01-11',
price: 100,
carriedForward: true
}),
quote({
date: '2025-01-12',
price: 100,
carriedForward: true
}),
quote({ date: '2025-01-13', price: 105 }),
quote({ date: '2025-01-14', price: 106, state: 'INTRADAY' }),
quote({ date: '2025-01-15', price: 110 }),
quote({ date: '2025-01-16', price: 115 })
];
const marketDataItems = jest.fn();
const provider = new BenchmarkMarketDataProvider({
marketDataItems
} as unknown as MarketDataService);
beforeEach(() => {
marketDataItems.mockReset();
marketDataItems.mockImplementation(async ({ where, orderBy, take }) => {
const filtered = records.filter((item) => {
if (item.dataSource !== where.dataSource) return false;
if (item.symbol !== where.symbol) return false;
if (item.state !== where.state) return false;
if (item.isCarriedForward !== where.isCarriedForward) return false;
if (where.date.lt && !(item.date < where.date.lt)) return false;
if (where.date.gte && !(item.date >= where.date.gte)) return false;
if (where.date.lte && !(item.date <= where.date.lte)) return false;
return true;
});
filtered.sort((a, b) =>
orderBy.date === 'desc'
? b.date.getTime() - a.date.getTime()
: a.date.getTime() - b.date.getTime()
);
return take === undefined ? filtered : filtered.slice(0, take);
});
});
const input = {
dataSource: 'YAHOO' as const,
symbol: 'SPY',
startDate,
endDate
};
it('retrieves the latest original quotation before the interval', async () => {
const result = await provider.getHistoricalPrices(input);
expect(result.prices[0]).toEqual({
date: '2025-01-10',
price: '100'
});
expect(result.prices.map(({ date }) => date)).toEqual([
'2025-01-10',
'2025-01-13',
'2025-01-15'
]);
});
it('filters carried-forward and intraday records in the query', async () => {
await provider.getHistoricalPrices(input);
expect(marketDataItems).toHaveBeenCalledTimes(2);
for (const [query] of marketDataItems.mock.calls) {
expect(query.where.state).toBe('CLOSE');
expect(query.where.isCarriedForward).toBe(false);
}
expect(marketDataItems.mock.calls[0][0]).toEqual(
expect.objectContaining({
orderBy: { date: 'desc' },
take: 1
})
);
});
it('preserves the Friday source for a Sunday execution', async () => {
const result = await provider.getHistoricalPrices(input);
const prepared = prepareBenchmarkPrices({
executionDates: ['2025-01-12'],
prices: result.prices
});
expect(prepared.carriedForward).toEqual([
{
date: '2025-01-12',
sourceDate: '2025-01-10',
ageInDays: 2
}
]);
});
it('rejects reversed date ranges without querying the database', async () => {
await expect(
provider.getHistoricalPrices({
...input,
startDate: endDate,
endDate: startDate
})
).rejects.toThrow('Reversed benchmark date range');
expect(marketDataItems).not.toHaveBeenCalled();
});
it('rejects invalid dates without querying the database', async () => {
await expect(
provider.getHistoricalPrices({
...input,
startDate: new Date(NaN)
})
).rejects.toThrow('Invalid benchmark date range');
expect(marketDataItems).not.toHaveBeenCalled();
});
it('returns no prices when the database has no records', async () => {
marketDataItems.mockResolvedValue([]);
const result = await provider.getHistoricalPrices(input);
expect(result.prices).toEqual([]);
});
});

62
apps/api/src/services/benchmark/prototype/benchmark-market-data.provider.ts

@ -0,0 +1,62 @@
import { MarketDataService } from '@ghostfolio/api/services/market-data/market-data.service';
import { AssetProfileIdentifier } from '@ghostfolio/common/interfaces';
import { Injectable } from '@nestjs/common';
import { MarketDataState } from '@prisma/client';
import { validateBenchmarkDateRange } from './benchmark-date-range';
import {
adaptBenchmarkMarketData,
BenchmarkMarketDataResult
} from './benchmark-market-data.adapter';
export interface BenchmarkHistoricalPricesInput extends AssetProfileIdentifier {
startDate: Date;
endDate: Date;
}
@Injectable()
export class BenchmarkMarketDataProvider {
public constructor(private readonly marketDataService: MarketDataService) {}
public async getHistoricalPrices({
dataSource,
symbol,
startDate,
endDate
}: BenchmarkHistoricalPricesInput): Promise<BenchmarkMarketDataResult> {
validateBenchmarkDateRange({ startDate, endDate });
const where = {
dataSource,
symbol,
state: MarketDataState.CLOSE,
isCarriedForward: false
};
const [previous, current] = await Promise.all([
this.marketDataService.marketDataItems({
where: {
...where,
date: { lt: startDate }
},
orderBy: { date: 'desc' },
take: 1
}),
this.marketDataService.marketDataItems({
where: {
...where,
date: {
gte: startDate,
lte: endDate
}
},
orderBy: { date: 'asc' }
})
]);
return adaptBenchmarkMarketData({
marketData: [...previous, ...current]
});
}
}
Loading…
Cancel
Save