Browse Source

feat(benchmark): add activity-matched ROI and ROAI prototype

pull/8438/head
piggei 3 weeks ago
parent
commit
2ffab47ced
  1. 70
      apps/api/src/services/benchmark/prototype/PROFILING.md
  2. 134
      apps/api/src/services/benchmark/prototype/README.md
  3. 159
      apps/api/src/services/benchmark/prototype/activity-cash-flow.provider.spec.ts
  4. 111
      apps/api/src/services/benchmark/prototype/activity-cash-flow.provider.ts
  5. 87
      apps/api/src/services/benchmark/prototype/activity-funding.integration.spec.ts
  6. 56
      apps/api/src/services/benchmark/prototype/activity-matched-benchmark.parity.spec.ts
  7. 98
      apps/api/src/services/benchmark/prototype/activity-matched-benchmark.performance.spec.ts
  8. 188
      apps/api/src/services/benchmark/prototype/activity-matched-benchmark.pipeline.performance.spec.ts
  9. 455
      apps/api/src/services/benchmark/prototype/activity-matched-benchmark.spec.ts
  10. 340
      apps/api/src/services/benchmark/prototype/activity-matched-benchmark.ts
  11. 72
      apps/api/src/services/benchmark/prototype/benchmark-fx-search.spec.ts
  12. 572
      apps/api/src/services/benchmark/prototype/benchmark-fx.adapter.spec.ts
  13. 368
      apps/api/src/services/benchmark/prototype/benchmark-fx.adapter.ts
  14. 175
      apps/api/src/services/benchmark/prototype/benchmark-market-data.adapter.spec.ts
  15. 64
      apps/api/src/services/benchmark/prototype/benchmark-market-data.adapter.ts
  16. 100
      apps/api/src/services/benchmark/prototype/benchmark-market-data.integration.spec.ts
  17. 106
      apps/api/src/services/benchmark/prototype/benchmark-price-policy.spec.ts
  18. 9
      apps/api/src/services/benchmark/prototype/benchmark-price-policy.ts
  19. 152
      apps/api/src/services/benchmark/prototype/benchmark-price-staleness.spec.ts
  20. 105
      apps/api/src/services/benchmark/prototype/benchmark-price.adapter.spec.ts
  21. 116
      apps/api/src/services/benchmark/prototype/benchmark-price.adapter.ts
  22. 108
      apps/api/src/services/benchmark/prototype/benchmark-valuation-status.spec.ts
  23. 178
      apps/api/src/services/benchmark/prototype/upstream-realized-gain.characterization.spec.ts

70
apps/api/src/services/benchmark/prototype/PROFILING.md

@ -0,0 +1,70 @@
# Task 3 stage profiling
Measured 2026-11-09, Node 22.23.4, Linux x86_64, installed Jest/ts-jest.
No dependencies added. Run the performance spec with `BENCHMARK_PERFORMANCE=1`;
`PROFILE_LABEL` labels its JSON output. Deterministic inputs, one warm-up and
seven measured iterations per workload. Each cell is median/p95 milliseconds;
p95 uses nearest rank (the maximum of seven). These are small-sample observations,
not a production SLA. Runtime/GC contention can affect individual samples.
Prices cover a fixed 10,000-day financial timeline. Events and requested valuation
counts vary independently. Valuation dates are subsets of the price timeline:
all workloads therefore evaluate 10,000 canonical points, verifying that display
sampling does not remove financial history. Dataset construction, assertions,
Jest startup, transforms and printing are excluded from measured stages.
Normalization includes decimal/date validation, stable event ordering, price
sorting, duplicate checks and timeline/set construction. Simulation consumes the
normalized input once. ROI and ROAI include range validation and output allocation.
Combined evaluation is the contiguous ROI-then-ROAI interval. Total spans
normalization through both evaluations, with no repeated simulation. Quantiles of
stages need not sum to the quantile of their combined interval.
## After optimization
| Events | Valuation dates | Normalize/sort | Simulation | ROI | ROAI | Combined evaluation | Total |
| -----: | --------------: | -------------: | ------------: | -----------: | ------------: | ------------------: | ------------: |
| 500 | 100 | 28.29/30.60 | 30.19/32.76 | 75.58/76.95 | 383.63/407.03 | 459.45/481.57 | 516.32/532.67 |
| 500 | 1000 | 29.83/31.25 | 27.39/28.36 | 79.87/80.73 | 381.99/392.07 | 461.86/472.80 | 518.54/531.00 |
| 500 | 10000 | 45.52/45.84 | 27.67/34.20 | 79.04/82.30 | 388.63/400.58 | 465.67/478.94 | 538.88/553.88 |
| 2000 | 100 | 30.49/32.17 | 45.26/49.61 | 82.95/119.81 | 397.38/399.79 | 482.66/517.28 | 559.56/594.16 |
| 2000 | 1000 | 32.31/33.34 | 42.27/46.72 | 80.47/81.84 | 392.95/404.99 | 472.65/486.72 | 547.58/563.11 |
| 2000 | 10000 | 45.76/69.99 | 44.64/49.25 | 84.74/91.98 | 400.32/443.12 | 485.39/535.10 | 577.46/654.34 |
| 10000 | 100 | 44.51/48.83 | 137.65/179.72 | 92.25/95.71 | 397.89/404.42 | 490.73/498.14 | 676.61/724.22 |
| 10000 | 1000 | 46.23/52.20 | 141.75/143.83 | 89.34/90.99 | 400.74/413.15 | 490.48/503.75 | 679.13/697.59 |
| 10000 | 10000 | 63.05/117.10 | 138.57/140.43 | 89.68/91.67 | 398.59/443.31 | 489.42/532.23 | 691.94/738.07 |
## Before evaluator optimization, on the same hardened timeline
This baseline already includes Task 3's explicit liquidation and complete price
history. Only evaluator scan/allocation and method-specific computation changed
between these runs. Input normalization and simulation were not optimized.
| Events | Valuation dates | Normalize/sort | Simulation | ROI | ROAI | Combined evaluation | Total |
| -----: | --------------: | -------------: | ------------: | ------------: | ------------: | ------------------: | -------------: |
| 500 | 100 | 27.27/28.82 | 31.48/32.68 | 202.52/239.34 | 419.89/424.69 | 622.07/658.63 | 680.86/710.13 |
| 500 | 1000 | 29.15/30.05 | 26.82/27.89 | 205.00/211.23 | 423.57/437.02 | 631.63/646.71 | 683.45/703.93 |
| 500 | 10000 | 41.65/44.45 | 26.89/28.41 | 209.05/231.92 | 432.31/436.97 | 638.00/668.68 | 708.59/733.18 |
| 2000 | 100 | 27.45/29.99 | 45.22/48.29 | 216.06/221.51 | 451.27/461.89 | 672.78/678.25 | 745.14/753.83 |
| 2000 | 1000 | 29.68/30.54 | 44.64/47.99 | 211.54/217.64 | 436.69/492.40 | 650.05/703.26 | 726.25/775.53 |
| 2000 | 10000 | 42.76/45.83 | 41.82/46.96 | 209.54/221.60 | 441.95/484.95 | 663.56/694.50 | 750.77/783.86 |
| 10000 | 100 | 42.23/44.75 | 137.42/141.64 | 222.78/227.41 | 446.42/453.41 | 665.93/676.44 | 843.06/860.69 |
| 10000 | 1000 | 46.95/47.57 | 140.60/149.49 | 218.70/257.88 | 443.07/476.38 | 661.77/734.26 | 853.79/931.31 |
| 10000 | 10000 | 61.02/63.20 | 139.23/158.20 | 217.86/292.34 | 445.13/541.61 | 662.51/833.96 | 860.26/1055.35 |
The optimized evaluator merges validation, range selection and output production
into one scan instead of validation + filter + map. It avoids the filtered-array
allocation and repeated date parsing. ROI does not calculate weighted ROAI
capital; ROAI does not accumulate ROI capital. Arithmetic order within each
chosen method is preserved, as confirmed by deterministic fixtures and direct
upstream method comparisons. Median combined evaluation fell by 25.9–28.3%;
median total time fell by 19.6–24.9%. ROAI remains the dominant evaluation cost.
Both public evaluations still independently validate the history; no shared cache
or trust boundary was introduced. Retaining linear scans is preferable here to
repeated reconstruction or introducing hidden shared mutable prepared state.
Task 2's totals are not directly comparable: its output timeline omitted price
dates not requested for display. The present canonical timeline intentionally
fixes that sampling dependence. Sorting is O(E log E + P log P + N log N), merge
O(E+P+N), and each evaluator O(N), where N <= E+P+D. Memory remains linear.

134
apps/api/src/services/benchmark/prototype/README.md

@ -0,0 +1,134 @@
# Activity-matched financial prototype
Isolated pure TypeScript; no production imports or registration. Flows are signed
investment proxies, not verified external cash flows. Positive amounts buy units;
negative amounts withdraw sale proceeds. Inputs are not mutated. Monetary inputs
are decimal strings and internal arithmetic uses the existing big.js dependency.
All amounts/prices must already be in one common currency. No FX, dividends,
fees, cash yield, leverage, TWR or MWR are implemented. Net performance equals
gross performance only under these zero-fee, price-only assumptions.
## Financial conventions and upstream comparison
Remaining average cost is reduced proportionally on sales. Realized gain survives
complete liquidation; contributions and withdrawals remain separate totals.
Historical investment means remaining cost, not cumulative signed proxy amounts.
Range profit subtracts the first included point's cumulative profit. ROI starts
with that point's market value and adds positive changes in daily closing cost.
ROAI uses upstream historical range weighting: positive-cost intervals only,
opening unrealized gain added to the investment basis, and the endpoint day
included when endpoint investment is positive. Percentages are return fractions.
The parity spec invokes the existing protected pure historical range methods
without constructing calculators/services. Both methods agree to 12 decimal
places on identical history across four selected ranges. Existing upstream
same-day BALN ROI and BTC partial-sale ROI/ROAI suites also pass unchanged.
This does not establish parity for holding-level or aggregate snapshot ROAI.
Important clarification to Task 1: a profitable sale removes COST, not proceeds,
from historical investment. A same-day sale of all units for 120 followed by a
120 purchase, with prior cost 100, increases ROI capital by 20. Same-day flows
net only to the extent that their cost changes net. The prototype tests this.
The canonical financial timeline is the union of every supplied price date and
economic event date. Requested display dates are added as carry-forward rows;
rows with no price/event on that date are marked `displayOnly` and ignored by
range evaluation. Changing display sampling therefore cannot discard events or
move the financial baseline. The full supplied financial history is retained,
including price dates outside the requested display period; use explicit range
bounds to select a period. Selected ranges use the first canonical observation
on/after start and the last on/before end, exactly as upstream does on its input
history. No artificial boundary valuation is inserted. If a range contains no
canonical observation, evaluation returns an empty array. With no prices or
events, requested dates remain zero-valued observations.
Upstream parity holds on identical financial histories. An upstream history
already missing event dates or boundary observations cannot recover those facts;
its denominators and baseline can therefore differ. Upstream chart output should
be sampled only after evaluating the complete agreed financial timeline.
Execution requires an exact-date quote. Display carry-forward uses only the last
preceding quote, without a staleness limit. Duplicate prices, invalid dates,
nonpositive prices, missing execution quotes and excess withdrawals throw.
Same-day input flow order is preserved; one financial snapshot follows all flows.
There is no settlement queue. Fully liquidated intervals remain in history.
### Liquidation precision (Task 3)
The former relative `1e-18` tolerance has been removed. An amount-based withdrawal
strictly rejects **any** excess over the current units times execution price.
Explicit `{ date, kind: 'liquidate' }` instead sells all actual units at that
price and clears units/cost exactly. It has no amount field; contradictory inputs
are rejected. The caller must explicitly choose this intent: it must not be
inferred just because a proxy withdrawal is close to the available value.
Example: 10/3 units at Big.DP=20 are rounded. A nominal 12 withdrawal at price 3.6
can exceed their actual decimal value and now throws. Explicit liquidation
withdraws their actual value, without silently rewriting a requested amount.
Partial sales use the upstream proportional average-cost rule. If configured
precision would round a partial sale to zero/all units or zero/all cost, throw
`Insufficient division precision` rather than silently change its intent.
Purchases rounding to zero units also throw. Tests preserve residual units of
`1e-19` at default precision and test rounding failures beyond that precision.
The prototype honors the caller's Big.DP and Big.RM; it does not change global
settings. Tests restore settings with finally, cover DP 0, 2, 20, 40, and all
four rounding modes. Normal finite-precision purchase rounding still affects the
represented units/value. Integration must agree on a precision policy; this is
not an arbitrary-precision rational-unit engine. Explicit liquidation is based
on represented units and never permits an overdraft.
## Numerical fixtures
Daily observations on days 0, 1, 2; opening purchase is included in baseline:
| Flows | Prices | Gain | ROI | ROAI |
| -------------- | -------- | ---- | --------- | ---------- |
| +100 | 10,10,12 | 20 | 20% | 20% |
| +100,+100 | 10,10,12 | 40 | 20% | 24% |
| +100,-50 | 10,10,12 | 10 | 10% | 15% |
| +100,-60 | 10,12,14 | 30 | 30% | 45% |
| +100,-120 | 10,12,12 | 20 | 20% | 20% |
| +100,-80 | 10,8,8 | -20 | -20% | -20% |
| +100,-120,+120 | 10,12,12 | 20 | 9.090909% | 18.181818% |
For the profitable partial sale, ending units=5, cost=50, realized gain=10,
withdrawals=60, value=70. Gain=70-50+10=30. ROAI capital=(100+50+50)/3.
For selected-range opening value 120 and closing value 132, both methods produce
12/120=10%, excluding the prior 20 gain. Irregular observations separately test
calendar-day weighting rather than averaging observation values.
## Verification and reproduction
From repository root (already-installed dependencies only):
```bash
./node_modules/.bin/jest --config apps/api/jest.config.ts --runInBand --runTestsByPath apps/api/src/services/benchmark/prototype/activity-matched-benchmark.spec.ts apps/api/src/services/benchmark/prototype/activity-matched-benchmark.parity.spec.ts
BENCHMARK_PERFORMANCE=1 ./node_modules/.bin/jest --config apps/api/jest.config.ts --runInBand --runTestsByPath apps/api/src/services/benchmark/prototype/activity-matched-benchmark.performance.spec.ts
```
Upstream suites need `.env.example` loaded, as in the repository test workflow.
The installed dotenv executable uses `dotenv run -f .env.example -- COMMAND`.
Task 2's configuration-validation failure was resolved by loading that file;
all six selected upstream tests passed then. Task 3 retains those fixtures and
adds precision, dense/sparse timeline and normalized-input reuse assertions.
See [PROFILING.md](./PROFILING.md) for Task 3 stage timings and controlled
before/after evaluation measurements. Task 2 totals used a different, display-
dependent timeline and must not be treated as an optimization baseline.
For E events, P prices, D requested dates and N <= E+P+D output dates, sorting
costs O(E log E + P log P + N log N). The simulation merge costs O(E+P+N).
Each range evaluation costs O(N), with linear memory. Big operation costs depend
on operand length and division precision. No per-date reconstruction or queries.
The evaluator validates, selects and evaluates in one pass, without allocating a
filtered history. ROI no longer calculates ROAI denominators, and vice versa.
Each independent public evaluation still validates its input; combined evaluation
in the harness deliberately measures ROI followed by ROAI, not a new financial
method. A future shared preparation stage could remove repeated validation but
would require a trusted/immutable history contract.
Review before integration: missing-price/staleness policy, range-boundary
sampling, precision policy, cash treatment and supported portfolio scopes remain
unresolved. FX, dividends, fees, Ledger, TWR and MWR remain outside this task.

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

@ -0,0 +1,159 @@
import { Activity } from '@ghostfolio/common/interfaces';
import { AssetSubClass } from '@ghostfolio/prisma/browser';
import { createActivityFunding } from './activity-cash-flow.provider';
function makeActivity({
id,
type = 'BUY',
date = new Date('2025-01-10T12:00:00Z'),
value = 100,
assetSubClass = AssetSubClass.ETF
}: {
id: string;
type?: Activity['type'];
date?: Date;
value?: number;
assetSubClass?: AssetSubClass;
}): Activity {
return {
id,
type,
date,
valueInBaseCurrency: value,
assetProfile: { assetSubClass }
} as Activity;
}
describe('ActivityCashFlowProvider', () => {
it('converts BUY and SELL into signed investment proxies', () => {
const result = createActivityFunding({
activities: [
makeActivity({ id: 'buy', value: 100.25 }),
makeActivity({ id: 'sell', type: 'SELL', value: 40.1 })
],
currency: 'EUR'
});
expect(result.canSimulate).toBe(true);
expect(result.diagnostics).toEqual([]);
expect(result.flows).toEqual([
{ date: '2025-01-10', amount: '100.25' },
{ date: '2025-01-10', amount: '-40.1' }
]);
expect(result.events.map(({ activityId }) => activityId)).toEqual([
'buy',
'sell'
]);
});
it('excludes synthetic CASH activities', () => {
const result = createActivityFunding({
activities: [
makeActivity({
id: 'cash',
assetSubClass: AssetSubClass.CASH
})
],
currency: 'EUR'
});
expect(result.canSimulate).toBe(true);
expect(result.flows).toEqual([]);
expect(result.diagnostics).toEqual([
{ activityId: 'cash', code: 'CASH_ACTIVITY_EXCLUDED' }
]);
});
it('does not treat dividends and fees as investment flows', () => {
const result = createActivityFunding({
activities: [
makeActivity({ id: 'dividend', type: 'DIVIDEND' }),
makeActivity({ id: 'fee', type: 'FEE' })
],
currency: 'EUR'
});
expect(result.canSimulate).toBe(true);
expect(result.flows).toEqual([]);
expect(result.diagnostics).toHaveLength(2);
expect(
result.diagnostics.every(
({ code }) => code === 'UNSUPPORTED_ACTIVITY_TYPE'
)
).toBe(true);
});
it.each([0, -1, NaN, Infinity])('rejects invalid BUY value %s', (value) => {
const result = createActivityFunding({
activities: [makeActivity({ id: 'invalid', value })],
currency: 'EUR'
});
expect(result.canSimulate).toBe(false);
expect(result.events).toEqual([]);
expect(result.flows).toEqual([]);
expect(result.diagnostics).toEqual([
{ activityId: 'invalid', code: 'INVALID_AMOUNT' }
]);
});
it('rejects invalid dates without throwing', () => {
const result = createActivityFunding({
activities: [
makeActivity({
id: 'invalid-date',
date: new Date(NaN)
})
],
currency: 'EUR'
});
expect(result.canSimulate).toBe(false);
expect(result.flows).toEqual([]);
expect(result.diagnostics).toEqual([
{ activityId: 'invalid-date', code: 'INVALID_DATE' }
]);
});
it('never returns partial flows after a blocking error', () => {
const result = createActivityFunding({
activities: [
makeActivity({ id: 'valid' }),
makeActivity({ id: 'invalid', value: NaN })
],
currency: 'EUR'
});
expect(result.canSimulate).toBe(false);
expect(result.events).toEqual([]);
expect(result.flows).toEqual([]);
});
it('preserves same-day ordering and does not mutate activities', () => {
const activities = [
makeActivity({ id: 'sell', type: 'SELL', value: 25 }),
makeActivity({ id: 'buy', value: 50 })
];
const original = activities.map(({ id, valueInBaseCurrency }) => ({
id,
valueInBaseCurrency
}));
const result = createActivityFunding({
activities,
currency: 'EUR'
});
expect(result.events.map(({ activityId }) => activityId)).toEqual([
'sell',
'buy'
]);
expect(
activities.map(({ id, valueInBaseCurrency }) => ({
id,
valueInBaseCurrency
}))
).toEqual(original);
});
});

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

@ -0,0 +1,111 @@
import { Activity } from '@ghostfolio/common/interfaces';
import { AssetSubClass } from '@ghostfolio/prisma/browser';
import { Big } from 'big.js';
import { format } from 'date-fns';
import { InvestmentProxyFlow } from './activity-matched-benchmark';
export interface ActivityFundingEvent {
activityId: string;
activityType: 'BUY' | 'SELL';
amount: string;
currency: string;
date: string;
source: 'ACTIVITY_PROXY';
}
export type ActivityFundingDiagnosticCode =
| 'CASH_ACTIVITY_EXCLUDED'
| 'UNSUPPORTED_ACTIVITY_TYPE'
| 'INVALID_AMOUNT'
| 'INVALID_DATE';
export interface ActivityFundingDiagnostic {
activityId: string;
code: ActivityFundingDiagnosticCode;
}
export interface ActivityFundingResult {
canSimulate: boolean;
diagnostics: ActivityFundingDiagnostic[];
events: ActivityFundingEvent[];
flows: InvestmentProxyFlow[];
}
export function createActivityFunding({
activities,
currency
}: {
activities: Activity[];
currency: string;
}): ActivityFundingResult {
const diagnostics: ActivityFundingDiagnostic[] = [];
const events: ActivityFundingEvent[] = [];
let canSimulate = true;
for (const activity of activities) {
if (activity.assetProfile?.assetSubClass === AssetSubClass.CASH) {
diagnostics.push({
activityId: activity.id,
code: 'CASH_ACTIVITY_EXCLUDED'
});
continue;
}
if (activity.type !== 'BUY' && activity.type !== 'SELL') {
diagnostics.push({
activityId: activity.id,
code: 'UNSUPPORTED_ACTIVITY_TYPE'
});
continue;
}
let amount: Big;
try {
amount = new Big(activity.valueInBaseCurrency);
if (!amount.gt(0)) {
throw new Error('Non-positive activity value');
}
} catch {
diagnostics.push({
activityId: activity.id,
code: 'INVALID_AMOUNT'
});
canSimulate = false;
continue;
}
if (
!(activity.date instanceof Date) ||
!Number.isFinite(activity.date.getTime())
) {
diagnostics.push({
activityId: activity.id,
code: 'INVALID_DATE'
});
canSimulate = false;
continue;
}
events.push({
activityId: activity.id,
activityType: activity.type,
amount: (activity.type === 'BUY' ? amount : amount.neg()).toString(),
currency,
date: format(activity.date, 'yyyy-MM-dd'),
source: 'ACTIVITY_PROXY'
});
}
return {
canSimulate,
diagnostics,
events: canSimulate ? events : [],
flows: canSimulate
? events.map(({ amount, date }) => ({ amount, date }))
: []
};
}

87
apps/api/src/services/benchmark/prototype/activity-funding.integration.spec.ts

@ -0,0 +1,87 @@
import { Activity } from '@ghostfolio/common/interfaces';
import { AssetSubClass } from '@ghostfolio/prisma/browser';
import { createActivityFunding } from './activity-cash-flow.provider';
import { evaluateRange, simulateBenchmark } from './activity-matched-benchmark';
const dates = ['2025-01-10', '2025-01-11', '2025-01-12', '2025-01-13'];
function activity({
id,
index,
type,
value
}: {
id: string;
index: number;
type: 'BUY' | 'SELL';
value: number;
}): Activity {
return {
id,
type,
date: new Date(`${dates[index]}T12:00:00Z`),
valueInBaseCurrency: value,
assetProfile: { assetSubClass: AssetSubClass.ETF }
} as Activity;
}
describe('Activity funding and benchmark integration', () => {
it('simulates activity-matched ROI and ROAI', () => {
const funding = createActivityFunding({
activities: [
activity({ id: 'buy-1', index: 0, type: 'BUY', value: 100 }),
activity({ id: 'sell-1', index: 1, type: 'SELL', value: 60 }),
activity({ id: 'buy-2', index: 2, type: 'BUY', value: 100 }),
activity({ id: 'sell-2', index: 3, type: 'SELL', value: 100 })
],
currency: 'EUR'
});
expect(funding.canSimulate).toBe(true);
expect(funding.diagnostics).toEqual([]);
const points = simulateBenchmark({
flows: funding.flows,
prices: dates.map((date, index) => ({
date,
price: String([10, 12, 20, 20][index])
})),
valuationDates: dates
});
const last = points.at(-1);
expect(last.costBasis.toNumber()).toBeCloseTo(75, 10);
expect(last.realizedGain.toNumber()).toBeCloseTo(35, 10);
expect(last.value.toNumber()).toBeCloseTo(100, 10);
expect(last.netPerformance.toNumber()).toBeCloseTo(60, 10);
for (const method of ['ROI', 'ROAI'] as const) {
const result = evaluateRange(points, method, dates[0], dates.at(-1));
expect(result).toHaveLength(dates.length);
expect(result.at(-1).netPerformance.toNumber()).toBeCloseTo(60, 10);
expect(Number.isFinite(result.at(-1).returnFraction.toNumber())).toBe(
true
);
}
});
it('does not expose partial flows after invalid activities', () => {
const funding = createActivityFunding({
activities: [
activity({ id: 'valid', index: 0, type: 'BUY', value: 100 }),
activity({ id: 'invalid', index: 1, type: 'SELL', value: NaN })
],
currency: 'EUR'
});
expect(funding.canSimulate).toBe(false);
expect(funding.events).toEqual([]);
expect(funding.flows).toEqual([]);
expect(funding.diagnostics).toEqual([
{ activityId: 'invalid', code: 'INVALID_AMOUNT' }
]);
});
});

56
apps/api/src/services/benchmark/prototype/activity-matched-benchmark.parity.spec.ts

@ -0,0 +1,56 @@
import { RoaiPortfolioCalculator } from '../../../app/portfolio/calculator/roai/portfolio-calculator';
import { RoiPortfolioCalculator } from '../../../app/portfolio/calculator/roi/portfolio-calculator';
import { evaluateRange, simulateBenchmark } from './activity-matched-benchmark';
describe('upstream historical range parity (no calculator construction)', () => {
it.each([
['ROI', RoiPortfolioCalculator],
['ROAI', RoaiPortfolioCalculator]
] as const)(
'matches %s denominators and normalization on identical historical inputs',
(method, Calculator) => {
const dates = ['2024-01-01', '2024-01-03', '2024-01-06', '2024-01-07'];
const points = simulateBenchmark({
flows: [
{ date: dates[0], amount: '100' },
{ date: dates[1], amount: '-60' },
{ date: dates[2], amount: '90' }
],
prices: dates.map((date, i) => ({ date, price: String(10 + i * 2) })),
valuationDates: dates
});
for (const start of dates) {
const range = points.filter(({ date }) => date >= start);
const historicalDataItems = range.map((point) => ({
date: point.date,
value: point.value.toNumber(),
valueWithCurrencyEffect: point.value.toNumber(),
totalInvestment: point.costBasis.toNumber(),
totalInvestmentValueWithCurrencyEffect: point.costBasis.toNumber(),
dividendInBaseCurrency: 0,
netPerformance: point.netPerformance
.minus(range[0].netPerformance)
.toNumber(),
netPerformanceWithCurrencyEffect: point.netPerformance
.minus(range[0].netPerformance)
.toNumber()
}));
// Protected pure range method only: no constructor, database, HTTP or snapshot services.
const upstream = (
Object.create(Calculator.prototype) as any
).calculatePerformancePercentagesForDateRange({ historicalDataItems });
for (const point of evaluateRange(
points,
method,
start,
dates.at(-1)
)) {
expect(point.returnFraction.toNumber()).toBeCloseTo(
upstream[point.date].netPerformanceInPercentage,
12
);
}
}
}
);
});

98
apps/api/src/services/benchmark/prototype/activity-matched-benchmark.performance.spec.ts

@ -0,0 +1,98 @@
import { performance } from 'node:perf_hooks';
import {
evaluateRange,
normalizeBenchmarkInput,
simulateNormalizedBenchmark
} from './activity-matched-benchmark';
/** Opt-in deterministic workload. Timing is observational, never a flaky gate. */
(process.env.BENCHMARK_PERFORMANCE ? describe : describe.skip)(
'benchmark stage profiling',
() => {
it('profiles normalization, simulation, each method, combined evaluation and total', () => {
const rows = [];
const date = (i: number) =>
new Date(Date.UTC(2000, 0, 1 + i)).toISOString().slice(0, 10);
const startDate = date(0);
const endDate = date(9999);
for (const count of [500, 2000, 10000]) {
for (const chartLength of [100, 1000, 10000]) {
const prices = Array.from({ length: 10000 }, (_, i) => ({
date: date(i),
price: String(100 + (i % 17))
}));
const flows = Array.from({ length: count }, (_, i) => ({
date: date(Math.floor((i * 9999) / Math.max(1, count - 1))),
amount: i % 5 === 4 ? '-1' : '10'
}));
const valuationDates = Array.from({ length: chartLength }, (_, i) =>
date(Math.floor((i * 9999) / (chartLength - 1)))
);
const execute = () => {
const t0 = performance.now();
const normalized = normalizeBenchmarkInput({
flows,
prices,
valuationDates
});
const t1 = performance.now();
const points = simulateNormalizedBenchmark(normalized);
const t2 = performance.now();
const roi = evaluateRange(points, 'ROI', startDate, endDate);
const t3 = performance.now();
const roai = evaluateRange(points, 'ROAI', startDate, endDate);
const t4 = performance.now();
// Assertions are deliberately outside the timed region.
expect(roi.length).toBe(points.length);
expect(Number.isFinite(roai.at(-1).returnFraction.toNumber())).toBe(
true
);
return {
normalize: t1 - t0,
simulate: t2 - t1,
roi: t3 - t2,
roai: t4 - t3,
combined: t4 - t2,
total: t4 - t0
};
};
execute();
const samples = Array.from({ length: 7 }, execute);
const metrics = {};
for (const key of [
'normalize',
'simulate',
'roi',
'roai',
'combined',
'total'
] as const) {
const sorted = samples
.map((sample) => sample[key])
.sort((a, b) => a - b);
metrics[key] = [
Number(sorted[3].toFixed(2)),
Number(sorted[6].toFixed(2))
];
}
rows.push({
events: count,
valuationDates: chartLength,
points: 10000,
...metrics
});
}
}
console.log(
JSON.stringify({
label: process.env.PROFILE_LABEL ?? 'current',
units: 'ms [median,p95]',
warmups: 1,
repeats: 7,
rows
})
);
}, 120000);
}
);

188
apps/api/src/services/benchmark/prototype/activity-matched-benchmark.pipeline.performance.spec.ts

@ -0,0 +1,188 @@
import { Activity } from '@ghostfolio/common/interfaces';
import { AssetSubClass } from '@ghostfolio/prisma/browser';
import { performance } from 'node:perf_hooks';
import { createActivityFunding } from './activity-cash-flow.provider';
import {
evaluateRange,
normalizeBenchmarkInput,
simulateNormalizedBenchmark
} from './activity-matched-benchmark';
import { prepareBenchmarkPrices } from './benchmark-price.adapter';
const date = (i: number): string =>
new Date(Date.UTC(2000, 0, 1 + i)).toISOString().slice(0, 10);
const startDate = date(0);
const endDate = date(9999);
function createActivities(count: number): Activity[] {
return Array.from({ length: count }, (_, i) => {
const isSell = i % 5 === 4;
const dayIndex = Math.floor((i * 9999) / Math.max(1, count - 1));
return {
id: `activity-${i}`,
type: isSell ? 'SELL' : 'BUY',
date: new Date(`${date(dayIndex)}T12:00:00Z`),
valueInBaseCurrency: isSell ? 1 : 100,
assetProfile: {
assetSubClass: AssetSubClass.ETF
}
} as Activity;
});
}
function createMarketPrices() {
const previousClose = {
date: '1999-12-31',
price: '100'
};
return [
previousClose,
...Array.from({ length: 10000 }, (_, i) => i)
.filter((i) => {
const weekday = new Date(`${date(i)}T00:00:00Z`).getUTCDay();
return weekday !== 0 && weekday !== 6;
})
.map((i) => ({
date: date(i),
price: String(100 + (i % 17))
}))
];
}
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)(
'activity-matched benchmark pipeline profiling',
() => {
it('profiles the complete isolated pipeline', () => {
const rows = [];
const marketPrices = createMarketPrices();
for (const count of [500, 2000, 10000]) {
const activities = createActivities(count);
for (const chartLength of [100, 1000, 10000]) {
const valuationDates = Array.from({ length: chartLength }, (_, i) =>
date(Math.floor((i * 9999) / (chartLength - 1)))
);
const execute = () => {
const t0 = performance.now();
const funding = createActivityFunding({
activities,
currency: 'EUR'
});
const t1 = performance.now();
if (!funding.canSimulate) {
throw new Error('Invalid funding activities');
}
const prepared = prepareBenchmarkPrices({
executionDates: funding.flows.map(({ date }) => date),
prices: marketPrices
});
const t2 = performance.now();
const normalized = normalizeBenchmarkInput({
flows: funding.flows,
prices: prepared.prices,
valuationDates
});
const t3 = performance.now();
const points = simulateNormalizedBenchmark(normalized);
const t4 = performance.now();
const roi = evaluateRange(points, 'ROI', startDate, endDate);
const t5 = performance.now();
const roai = evaluateRange(points, 'ROAI', startDate, endDate);
const t6 = performance.now();
// Assertions are deliberately outside timed stages.
const expectedDates = points
.filter(
({ date, displayOnly }) =>
!displayOnly && date >= startDate && date <= endDate
)
.map(({ date }) => date);
expect(funding.events).toHaveLength(count);
expect(roi.map(({ date }) => date)).toEqual(expectedDates);
expect(roai.map(({ date }) => date)).toEqual(expectedDates);
expect(Number.isFinite(roai.at(-1).returnFraction.toNumber())).toBe(
true
);
return {
provider: t1 - t0,
adapter: t2 - t1,
normalize: t3 - t2,
simulate: t4 - t3,
roi: t5 - t4,
roai: t6 - t5,
total: t6 - t0,
points: points.length,
carriedForward: prepared.carriedForward.length
};
};
execute();
const samples = Array.from({ length: 7 }, execute);
const metrics = {};
for (const key of [
'provider',
'adapter',
'normalize',
'simulate',
'roi',
'roai',
'total'
] as const) {
metrics[key] = percentileMetrics(
samples.map((sample) => sample[key])
);
}
rows.push({
activities: count,
valuationDates: chartLength,
points: samples[0].points,
carriedForward: samples[0].carriedForward,
...metrics
});
}
}
console.log(
JSON.stringify({
label: process.env.PROFILE_LABEL ?? 'pipeline',
units: 'ms [median,p95]',
warmups: 1,
repeats: 7,
rows
})
);
}, 120000);
}
);

455
apps/api/src/services/benchmark/prototype/activity-matched-benchmark.spec.ts

@ -0,0 +1,455 @@
import { Big } from 'big.js';
import {
evaluateRange,
simulateBenchmark,
normalizeBenchmarkInput,
simulateNormalizedBenchmark
} from './activity-matched-benchmark';
const dates = ['2024-01-01', '2024-01-02', '2024-01-03'];
function run(
amounts: string[],
prices: string[] = ['10', '10', '12'],
chart = dates
) {
return simulateBenchmark({
flows: amounts.map((amount, index) => ({ date: dates[index], amount })),
prices: prices.map((price, index) => ({ date: dates[index], price })),
valuationDates: chart
});
}
function result(
points: ReturnType<typeof run>,
method: 'ROI' | 'ROAI',
start = dates[0]
) {
return evaluateRange(points, method, start, dates[2]).at(-1);
}
describe('isolated Activity investment-proxy benchmark', () => {
it.each([
[['100'], ['10', '10', '12'], 20, 100, 100, 0.2, 0.2],
[['100', '100'], ['10', '10', '12'], 40, 200, 500 / 3, 0.2, 0.24],
[['100', '-50'], ['10', '10', '12'], 10, 100, 200 / 3, 0.1, 0.15],
[['100', '-120'], ['10', '12', '12'], 20, 100, 100, 0.2, 0.2],
// Sale at a profit removes 50 cost, not 60 proceeds.
[['100', '-60'], ['10', '12', '14'], 30, 100, 200 / 3, 0.3, 0.45],
[['100', '-80'], ['10', '8', '8'], -20, 100, 100, -0.2, -0.2],
[
['100', '-120', '120'],
['10', '12', '12'],
20,
220,
110,
20 / 220,
20 / 110
]
])(
'calculates independent financial fixture %#',
(amounts, prices, gain, roiCapital, roaiCapital, roi, roai) => {
const points = run(amounts as string[], prices as string[]);
expect(points.at(-1).netPerformance.toNumber()).toBeCloseTo(
gain as number,
12
);
expect(result(points, 'ROI').capital.toNumber()).toBeCloseTo(
roiCapital as number,
12
);
expect(result(points, 'ROAI').capital.toNumber()).toBeCloseTo(
roaiCapital as number,
12
);
expect(result(points, 'ROI').returnFraction.toNumber()).toBeCloseTo(
roi as number,
12
);
expect(result(points, 'ROAI').returnFraction.toNumber()).toBeCloseTo(
roai as number,
12
);
}
);
it('keeps units, average cost, realized gains and cumulative funding separate', () => {
const point = run(['100', '-60'], ['10', '12', '14']).at(-1);
expect(
[
point.units,
point.costBasis,
point.realizedGain,
point.contributions,
point.withdrawals,
point.value
].map(String)
).toEqual(['5', '50', '10', '100', '60', '70']);
});
it('supports fractional units and clears complete withdrawals', () => {
const points = simulateBenchmark({
flows: [
{ date: dates[0], amount: '10' },
{ date: dates[1], kind: 'liquidate' }
],
prices: dates.map((date, i) => ({ date, price: ['3', '3.6', '4'][i] })),
valuationDates: dates
});
expect(points[0].units.toNumber()).toBeCloseTo(10 / 3, 14);
expect(points.at(-1).units.eq(0)).toBe(true);
expect(points.at(-1).costBasis.eq(0)).toBe(true);
});
it('nets same-day cost changes for ROI while retaining execution order', () => {
const points = simulateBenchmark({
flows: [
{ date: dates[0], amount: '100' },
{ date: dates[1], amount: '-120' },
{ date: dates[1], amount: '120' }
],
prices: dates.map((date, index) => ({
date,
price: index ? '12' : '10'
})),
valuationDates: dates
});
expect(result(points, 'ROI').capital.toString()).toBe('120');
expect(result(points, 'ROI').returnFraction.toNumber()).toBeCloseTo(
1 / 6,
14
);
});
it('normalizes selected ranges to opening value and subtracts prior gains', () => {
const points = run(['100'], ['10', '12', '13.2']);
for (const method of ['ROI', 'ROAI'] as const) {
const value = result(points, method, dates[1]);
expect(value.capital.toString()).toBe('120');
expect(value.netPerformance.toString()).toBe('12');
expect(value.returnFraction.toString()).toBe('0.1');
}
});
it('retains event dates between sparse chart dates', () => {
const dense = run(['100', '100']);
const sparse = run(
['100', '100'],
['10', '10', '12'],
[dates[0], dates[2]]
);
expect(sparse).toEqual(dense);
expect(result(sparse, 'ROAI').returnFraction.toString()).toBe('0.24');
});
it('matches upstream range weighting on irregular observations', () => {
const points = simulateBenchmark({
flows: [
{ date: dates[0], amount: '100' },
{ date: dates[2], amount: '100' }
],
prices: [
{ date: dates[0], price: '10' },
{ date: dates[2], price: '10' },
{ date: '2024-01-06', price: '12' }
],
valuationDates: ['2024-01-06']
});
const last = evaluateRange(points, 'ROAI', dates[0], '2024-01-06').at(-1);
// (100 * 2 + 200 * 3 + 200) / 6
expect(last.capital.toNumber()).toBeCloseTo(1000 / 6, 12);
expect(last.returnFraction.toNumber()).toBeCloseTo(0.24, 12);
});
it('handles empty, flat and single-point ranges', () => {
expect(evaluateRange([], 'ROI', dates[0], dates[2])).toEqual([]);
const empty = simulateBenchmark({
flows: [],
prices: [],
valuationDates: dates
});
expect(result(empty, 'ROAI').returnFraction.eq(0)).toBe(true);
expect(result(run(['100']), 'ROI', dates[2]).returnFraction.eq(0)).toBe(
true
);
});
it('rejects missing execution quotes, excess withdrawals and invalid dates/prices', () => {
expect(() => run(['100', '-101'])).toThrow('Insufficient capital');
expect(() =>
simulateBenchmark({
flows: [{ date: dates[1], amount: '1' }],
prices: [{ date: dates[0], price: '10' }],
valuationDates: dates
})
).toThrow('Missing execution');
expect(() => run(['100'], ['0'])).toThrow('positive');
expect(() =>
simulateBenchmark({
flows: [],
prices: [],
valuationDates: ['2024-02-30']
})
).toThrow('Invalid date');
expect(() =>
evaluateRange(run(['100']), 'ROI', dates[2], dates[0])
).toThrow('Reversed');
});
it('uses preceding prices for valuation without looking ahead', () => {
const points = simulateBenchmark({
flows: [{ date: dates[0], amount: '100' }],
prices: [
{ date: dates[0], price: '10' },
{ date: dates[2], price: '20' }
],
valuationDates: dates
});
expect(points[1].value.eq(new Big(100))).toBe(true);
});
});
describe('liquidation precision and financial timeline hardening', () => {
const input = (
flows: Parameters<typeof simulateBenchmark>[0]['flows'],
valuationDates = dates
) => ({
flows,
prices: dates.map((date) => ({ date, price: '1' })),
valuationDates
});
it.each([0, 2, 20, 40])(
'explicit liquidation closes fractional positions at Big.DP=%i',
(precision) => {
const saved = { DP: Big.DP, RM: Big.RM };
try {
Big.DP = precision;
Big.RM = 0;
const points = simulateBenchmark({
flows: [
{ date: dates[0], amount: '10' },
{ date: dates[1], kind: 'liquidate' }
],
prices: [
{ date: dates[0], price: '3' },
{ date: dates[1], price: '3.6' }
],
valuationDates: []
});
const last = points.at(-1);
const proceeds = points[0].units.mul('3.6');
expect(last.units.toString()).toBe('0');
expect(last.costBasis.toString()).toBe('0');
expect(last.withdrawals.eq(proceeds)).toBe(true);
expect(last.realizedGain.eq(proceeds.minus(10))).toBe(true);
expect(
last.netPerformance.eq(last.withdrawals.minus(last.contributions))
).toBe(true);
} finally {
Big.DP = saved.DP;
Big.RM = saved.RM;
}
}
);
it('preserves a small partial residual without treating it as a full close', () => {
const point = simulateBenchmark(
input([
{ date: dates[0], amount: '1' },
{ date: dates[1], amount: '-0.9999999999999999999' }
])
).at(-1);
expect(point.units.eq('1e-19')).toBe(true);
expect(point.costBasis.eq('1e-19')).toBe(true);
expect(point.withdrawals.eq('0.9999999999999999999')).toBe(true);
});
it.each(['-1.00000000000000000001', '-1.000000000000000001', '-1.01'])(
'strictly rejects overspending %s, including the former tolerance window',
(amount) => {
expect(() =>
simulateBenchmark(
input([
{ date: dates[0], amount: '1' },
{ date: dates[1], amount }
])
)
).toThrow('Insufficient capital');
}
);
it('requires explicit full-close intent when nominal proceeds exceed rounded units', () => {
expect(() => run(['10', '-12'], ['3', '3.6', '4'])).toThrow(
'Insufficient capital'
);
});
it.each([2, 20])(
'rejects a partial sale lost to division rounding at DP=%i',
(precision) => {
const saved = Big.DP;
try {
Big.DP = precision;
const amount = `-0.${'9'.repeat(precision + 2)}`;
expect(() =>
simulateBenchmark(
input([
{ date: dates[0], amount: '1' },
{ date: dates[1], amount }
])
)
).toThrow('Insufficient division precision');
} finally {
Big.DP = saved;
}
}
);
it('rejects contradictory liquidation instructions and permits closing an empty position', () => {
expect(() =>
simulateBenchmark(
input([{ date: dates[0], kind: 'liquidate', amount: '-1' } as never])
)
).toThrow('must not specify');
expect(
simulateBenchmark(input([{ date: dates[0], kind: 'liquidate' }]))
.at(-1)
.withdrawals.eq(0)
).toBe(true);
});
it('cannot silently lose a purchase at insufficient division precision', () => {
const saved = Big.DP;
try {
Big.DP = 0;
expect(() =>
simulateBenchmark({
flows: [{ date: dates[0], amount: '1' }],
prices: [{ date: dates[0], price: '100' }],
valuationDates: []
})
).toThrow('Insufficient division precision');
} finally {
Big.DP = saved;
}
});
it('uses canonical prices and events for identical sparse/dense selected ranges', () => {
const day = (n: number) => `2024-01-${String(n).padStart(2, '0')}`;
const flows = [
{ date: day(1), amount: '100' },
{ date: day(4), amount: '-40' },
{ date: day(4), amount: '20' },
{ date: day(8), amount: '60' }
];
const prices = [1, 4, 7, 8, 12].map((n) => ({
date: day(n),
price: String(10 + n)
}));
const dense = simulateBenchmark({
flows,
prices,
valuationDates: Array.from({ length: 12 }, (_, i) => day(i + 1))
});
const sparse = simulateBenchmark({
flows,
prices,
valuationDates: [day(1), day(12)]
});
expect(dense.filter((point) => !point.displayOnly)).toEqual(sparse);
expect(dense.at(-1).contributions.toString()).toBe('180');
expect(dense.at(-1).withdrawals.toString()).toBe('40');
for (const method of ['ROI', 'ROAI'] as const) {
for (const [start, end] of [
[1, 12],
[2, 11],
[5, 12],
[7, 7]
]) {
expect(evaluateRange(dense, method, day(start), day(end))).toEqual(
evaluateRange(sparse, method, day(start), day(end))
);
}
}
// First available financial observation in [Jan 5, Jan 12] is Jan 7.
expect(evaluateRange(dense, 'ROAI', day(5), day(12))[0].date).toBe(day(7));
});
it('retains irregular positive-investment days around full liquidation and reinvestment', () => {
const points = simulateBenchmark({
flows: [
{ date: '2024-01-01', amount: '100' },
{ date: '2024-01-04', kind: 'liquidate' },
{ date: '2024-01-10', amount: '200' }
],
prices: [
{ date: '2024-01-01', price: '10' },
{ date: '2024-01-04', price: '12' },
{ date: '2024-01-10', price: '10' },
{ date: '2024-01-12', price: '11' }
],
valuationDates: ['2024-01-06']
});
const last = evaluateRange(points, 'ROAI', '2024-01-01', '2024-01-12').at(
-1
);
// Three days at 100, two at 200 and one endpoint day at 200;
// six liquidated days are excluded: (300+400+200)/6 = 150.
expect(last.capital.toString()).toBe('150');
expect(last.netPerformance.toString()).toBe('40');
expect(last.returnFraction.toNumber()).toBeCloseTo(40 / 150, 14);
});
});
describe('normalization stage and precision boundaries', () => {
it('reuses normalized input without changing financial results or input order', () => {
const input = {
flows: [
{ date: dates[1], amount: '-1' },
{ date: dates[0], amount: '10' }
],
prices: [
{ date: dates[2], price: '4' },
{ date: dates[0], price: '3' },
{ date: dates[1], price: '3.6' }
],
valuationDates: [dates[2], dates[0]]
};
const original = JSON.stringify(input);
const normalized = normalizeBenchmarkInput(input);
const first = simulateNormalizedBenchmark(normalized);
expect(simulateNormalizedBenchmark(normalized)).toEqual(first);
expect(simulateBenchmark(input)).toEqual(first);
expect(JSON.stringify(input)).toBe(original);
});
it.each([0, 1, 2, 3] as const)(
'explicit close uses actual units under rounding mode %i',
(rounding) => {
const saved = { DP: Big.DP, RM: Big.RM };
try {
Big.DP = 2;
Big.RM = rounding;
const points = simulateBenchmark({
flows: [
{ date: dates[0], amount: '1' },
{ date: dates[1], kind: 'liquidate' }
],
prices: [
{ date: dates[0], price: '3' },
{ date: dates[1], price: '3.7' }
],
valuationDates: []
});
expect(points.at(-1).withdrawals.eq(points[0].units.mul('3.7'))).toBe(
true
);
expect(points.at(-1).units.eq(0)).toBe(true);
expect(points.at(-1).costBasis.eq(0)).toBe(true);
} finally {
Big.DP = saved.DP;
Big.RM = saved.RM;
}
}
);
});

340
apps/api/src/services/benchmark/prototype/activity-matched-benchmark.ts

@ -0,0 +1,340 @@
import { Big } from 'big.js';
import {
DEFAULT_MAX_PRICE_AGE_DAYS,
validateMaxPriceAgeDays
} from './benchmark-price-policy';
/** Signed investment proxies, never evidence of external deposits/withdrawals. */
export type InvestmentProxyFlow =
| { date: string; amount: string; kind?: 'amount' }
| { date: string; kind: 'liquidate'; amount?: never };
export interface BenchmarkPrice {
date: string;
price: string;
sourceDate?: string;
}
export type BenchmarkValuationStatus =
'CURRENT' | 'CARRIED_FORWARD' | 'STALE' | 'NOT_APPLICABLE';
export interface FinancialPoint {
date: string;
valuationStatus?: BenchmarkValuationStatus;
/** Carry-forward display rows never define financial range boundaries. */
displayOnly?: boolean;
units: Big;
costBasis: Big;
realizedGain: Big;
contributions: Big;
withdrawals: Big;
value: Big;
netPerformance: Big;
}
function day(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 date: ${date}`);
}
return time / 86400000;
}
/** Exact-date execution; latest preceding quote for valuation. Single currency,
* price-only, zero fees/distributions. Input order breaks same-day flow ties.
* Returns closing states at every supplied price/event date plus display dates.
* Display-only carry-forward rows do not participate in financial evaluation.
*/
export interface SimulationInput {
flows: InvestmentProxyFlow[];
maxPriceAgeDays?: number;
prices: BenchmarkPrice[];
valuationDates: string[];
}
export function normalizeBenchmarkInput({
flows,
maxPriceAgeDays = DEFAULT_MAX_PRICE_AGE_DAYS,
prices,
valuationDates
}: SimulationInput) {
validateMaxPriceAgeDays(maxPriceAgeDays);
const events = flows
.map((flow, sequence) => {
day(flow.date);
if (
flow.kind !== undefined &&
flow.kind !== 'amount' &&
flow.kind !== 'liquidate'
) {
throw new Error('Unsupported flow kind');
}
if (flow.kind === 'liquidate' && flow.amount !== undefined) {
throw new Error('Liquidation must not specify an amount');
}
return {
date: flow.date,
sequence,
kind: flow.kind,
amount: flow.kind === 'liquidate' ? new Big(0) : new Big(flow.amount)
};
})
.sort((a, b) => a.date.localeCompare(b.date) || a.sequence - b.sequence);
const quotes = prices
.map((quote) => {
day(quote.date);
const price = new Big(quote.price);
if (!price.gt(0)) {
throw new Error('Price must be positive');
}
if (quote.sourceDate !== undefined) {
day(quote.sourceDate);
if (quote.sourceDate > quote.date) {
throw new Error('Price source date cannot be in the future');
}
}
return {
date: quote.date,
price,
sourceDate: quote.sourceDate ?? quote.date,
sourceDay: day(quote.sourceDate ?? quote.date)
};
})
.sort((a, b) => a.date.localeCompare(b.date));
for (let i = 1; i < quotes.length; i++) {
if (quotes[i].date === quotes[i - 1].date) {
throw new Error('Duplicate price date');
}
}
valuationDates.forEach(day);
const financialDates = new Set([
...quotes.map(({ date }) => date),
...events.map(({ date }) => date)
]);
const dates = [...new Set([...valuationDates, ...financialDates])].sort();
const dateDays = dates.map(day);
return {
events,
quotes,
dates,
dateDays,
financialDates,
maxPriceAgeDays
};
}
export type NormalizedBenchmarkInput = ReturnType<
typeof normalizeBenchmarkInput
>;
/** Normalized input is reusable, read-only by convention; this stage never mutates it. */
export function simulateNormalizedBenchmark({
events,
quotes,
dates,
dateDays,
financialDates,
maxPriceAgeDays
}: NormalizedBenchmarkInput): FinancialPoint[] {
let units = new Big(0);
let costBasis = new Big(0);
let realizedGain = new Big(0);
let contributions = new Big(0);
let withdrawals = new Big(0);
let eventIndex = 0;
let quoteIndex = 0;
let quote:
| { date: string; price: Big; sourceDate: string; sourceDay: number }
| undefined;
const points: FinancialPoint[] = [];
for (let dateIndex = 0; dateIndex < dates.length; dateIndex++) {
const date = dates[dateIndex];
const currentDay = dateDays[dateIndex];
while (quoteIndex < quotes.length && quotes[quoteIndex].date <= date) {
quote = quotes[quoteIndex++];
}
while (eventIndex < events.length && events[eventIndex].date === date) {
const { amount, kind } = events[eventIndex++];
if (amount.eq(0) && kind !== 'liquidate') {
continue;
}
if (quote?.date !== date) {
throw new Error(`Missing execution price: ${date}`);
}
if (currentDay - quote.sourceDay > maxPriceAgeDays) {
throw new Error(`Stale execution price: ${date}`);
}
if (kind === 'liquidate') {
const proceeds = units.mul(quote.price);
realizedGain = realizedGain.plus(proceeds.minus(costBasis));
withdrawals = withdrawals.plus(proceeds);
units = new Big(0);
costBasis = new Big(0);
} else if (amount.gt(0)) {
const purchasedUnits = amount.div(quote.price);
if (!purchasedUnits.gt(0)) {
throw new Error('Insufficient division precision');
}
units = units.plus(purchasedUnits);
costBasis = costBasis.plus(amount);
contributions = contributions.plus(amount);
} else {
const proceeds = amount.neg();
const value = units.mul(quote.price);
if (proceeds.gt(value)) {
throw new Error(`Insufficient capital: ${date}`);
}
const soldUnits = proceeds.eq(value)
? units
: proceeds.div(quote.price);
if (proceeds.lt(value) && (!soldUnits.gt(0) || soldUnits.gte(units))) {
throw new Error('Insufficient division precision');
}
const removedBasis = soldUnits.eq(units)
? costBasis
: costBasis.mul(soldUnits).div(units);
if (
soldUnits.lt(units) &&
(removedBasis.lte(0) || removedBasis.gte(costBasis))
) {
throw new Error('Insufficient division precision');
}
units = units.minus(soldUnits);
costBasis = costBasis.minus(removedBasis);
realizedGain = realizedGain.plus(proceeds.minus(removedBasis));
withdrawals = withdrawals.plus(proceeds);
}
}
if (!quote && units.gt(0)) {
throw new Error(`Missing valuation price: ${date}`);
}
const hasPosition = units.gt(0);
const isFinancialDate = financialDates.has(date);
const priceAgeDays =
hasPosition && quote ? currentDay - quote.sourceDay : 0;
if (hasPosition && isFinancialDate && priceAgeDays > maxPriceAgeDays) {
throw new Error(`Stale valuation price: ${date}`);
}
const valuationStatus: BenchmarkValuationStatus = !hasPosition
? 'NOT_APPLICABLE'
: priceAgeDays === 0
? 'CURRENT'
: priceAgeDays <= maxPriceAgeDays
? 'CARRIED_FORWARD'
: 'STALE';
const value = units.mul(quote?.price ?? 0);
points.push({
valuationStatus,
date,
...(financialDates.size && !financialDates.has(date)
? { displayOnly: true }
: {}),
units,
costBasis,
realizedGain,
contributions,
withdrawals,
value,
netPerformance: value.minus(costBasis).plus(realizedGain)
});
}
return points;
}
export function simulateBenchmark(input: SimulationInput): FinancialPoint[] {
return simulateNormalizedBenchmark(normalizeBenchmarkInput(input));
}
/** Mirrors upstream getPerformance range normalization and historical ROI/ROAI
* denominators, NOT holding-level ROAI or overall snapshot aggregation.
* costBasis is upstream totalInvestment: sales remove average COST, not proceeds.
*/
export function evaluateRange(
points: FinancialPoint[],
method: 'ROI' | 'ROAI',
start: string,
end: string
) {
if (day(start) > day(end)) {
throw new Error('Reversed range');
}
if (method !== 'ROI' && method !== 'ROAI') {
throw new Error('Unsupported method');
}
const result: {
date: string;
capital: Big;
netPerformance: Big;
returnFraction: Big;
}[] = [];
let first: FinancialPoint | undefined;
let previous: FinancialPoint | undefined;
let previousDay = 0;
let openingGain = new Big(0);
let roiCapital = new Big(0);
let weighted = new Big(0);
let days = 0;
// Validate, select and evaluate in one pass. Do not compute ROAI during ROI
// evaluation (or ROI during ROAI). No filtered history allocation is needed.
for (let i = 0; i < points.length; i++) {
const point = points[i];
const currentDay = day(point.date);
if (i && point.date <= points[i - 1].date) {
throw new Error('Points must be strictly ordered');
}
if (point.displayOnly || point.date < start || point.date > end) {
continue;
}
if (!first) {
first = point;
openingGain = first.value.minus(first.costBasis);
roiCapital = first.value;
}
if (previous) {
if (method === 'ROI') {
const change = point.costBasis.minus(previous.costBasis);
if (change.gt(0)) {
roiCapital = roiCapital.plus(change);
}
} else if (previous.costBasis.gt(0)) {
const duration = currentDay - previousDay;
weighted = weighted.plus(
previous.costBasis.plus(openingGain).mul(duration)
);
days += duration;
}
}
const capital =
method === 'ROI'
? roiCapital
: point.costBasis.gt(0)
? weighted.plus(point.costBasis.plus(openingGain)).div(days + 1)
: days > 0
? weighted.div(days)
: new Big(0);
const netPerformance = point.netPerformance.minus(first.netPerformance);
result.push({
date: point.date,
capital,
netPerformance,
returnFraction: capital.gt(0) ? netPerformance.div(capital) : new Big(0)
});
previous = point;
previousDay = currentDay;
}
return result;
}

72
apps/api/src/services/benchmark/prototype/benchmark-fx-search.spec.ts

@ -0,0 +1,72 @@
import { findLatestFxQuote } from './benchmark-fx.adapter';
interface Quote {
day: number;
rate: string;
}
function linearSearch(quotes: Quote[], targetDay: number): Quote | undefined {
return [...quotes].reverse().find(({ day }) => day <= targetDay);
}
describe('Benchmark FX binary search', () => {
const quotes: Quote[] = [
{ day: 10, rate: '0.90' },
{ day: 12, rate: '0.92' },
{ day: 15, rate: '0.95' }
];
it('returns the exact quotation', () => {
expect(findLatestFxQuote(quotes, 12)).toEqual(quotes[1]);
});
it('returns the latest preceding quotation', () => {
expect(findLatestFxQuote(quotes, 14)).toEqual(quotes[1]);
});
it('never returns a future quotation', () => {
expect(findLatestFxQuote(quotes, 9)).toBeUndefined();
});
it('returns the last quotation after the final date', () => {
expect(findLatestFxQuote(quotes, 20)).toEqual(quotes[2]);
});
it('handles an empty series', () => {
expect(findLatestFxQuote([], 10)).toBeUndefined();
});
it('handles a single quotation', () => {
expect(findLatestFxQuote([quotes[0]], 10)).toEqual(quotes[0]);
expect(findLatestFxQuote([quotes[0]], 9)).toBeUndefined();
});
it('does not mutate the input', () => {
const original = quotes.map(({ day, rate }) => ({ day, rate }));
findLatestFxQuote(quotes, 14);
expect(quotes).toEqual(original);
});
it('matches the linear search over 10000 quotations', () => {
const longSeries: Quote[] = Array.from({ length: 10000 }, (_, index) => ({
day: index * 2,
rate: String(index + 1)
}));
for (let targetDay = -1; targetDay <= 20001; targetDay += 17) {
expect(findLatestFxQuote(longSeries, targetDay)).toEqual(
linearSearch(longSeries, targetDay)
);
}
});
it('matches the linear search for every boundary', () => {
for (let targetDay = 0; targetDay <= 20; targetDay++) {
expect(findLatestFxQuote(quotes, targetDay)).toEqual(
linearSearch(quotes, targetDay)
);
}
});
});

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

@ -0,0 +1,572 @@
import {
BenchmarkFxQuote,
convertBenchmarkPrices
} from './benchmark-fx.adapter';
const prices = [
{ date: '2025-01-10', price: '100' },
{ date: '2025-01-12', price: '110' }
];
const fxQuotes: BenchmarkFxQuote[] = [
{
currencyFrom: 'USD',
currencyTo: 'EUR',
date: '2025-01-10',
rate: '0.92'
}
];
describe('Benchmark historical FX adapter', () => {
it('preserves prices for identical currencies', () => {
const result = convertBenchmarkPrices({
prices,
currencyFrom: 'EUR',
currencyTo: 'EUR',
fxQuotes: []
});
expect(result.prices).toEqual(prices);
expect(result.conversions).toEqual([
{
date: '2025-01-10',
method: 'IDENTITY',
rate: '1',
components: []
},
{
date: '2025-01-12',
method: 'IDENTITY',
rate: '1',
components: []
}
]);
});
it('converts using a direct historical rate', () => {
const result = convertBenchmarkPrices({
prices: [prices[0]],
currencyFrom: 'USD',
currencyTo: 'EUR',
fxQuotes
});
expect(result.prices[0].price).toBe('92');
expect(result.conversions[0]).toEqual({
date: '2025-01-10',
method: 'DIRECT',
rate: '0.92',
components: [
{
pair: 'USDEUR',
sourceDate: '2025-01-10',
ageInDays: 0,
rate: '0.92',
kind: 'MARKET'
}
]
});
});
it('converts using the inverse historical rate', () => {
const result = convertBenchmarkPrices({
prices: [{ date: '2025-01-10', price: '92' }],
currencyFrom: 'EUR',
currencyTo: 'USD',
fxQuotes
});
expect(result.prices[0].price).toBe('100');
expect(result.conversions[0].components[0].pair).toBe('USDEUR');
expect(result.conversions[0].method).toBe('DIRECT');
});
it('uses the most recent preceding rate', () => {
const result = convertBenchmarkPrices({
prices: [prices[1]],
currencyFrom: 'USD',
currencyTo: 'EUR',
fxQuotes
});
expect(result.prices[0].price).toBe('101.2');
expect(result.conversions[0].components[0]).toMatchObject({
sourceDate: '2025-01-10',
ageInDays: 2
});
});
it('rejects a rate older than seven days', () => {
expect(() =>
convertBenchmarkPrices({
prices: [{ date: '2025-01-18', price: '100' }],
currencyFrom: 'USD',
currencyTo: 'EUR',
fxQuotes
})
).toThrow('Stale FX rate: USDEUR 2025-01-18');
});
it('never uses a future FX rate', () => {
expect(() =>
convertBenchmarkPrices({
prices: [{ date: '2025-01-09', price: '100' }],
currencyFrom: 'USD',
currencyTo: 'EUR',
fxQuotes
})
).toThrow('Missing FX rate: USDEUR 2025-01-09');
});
it('rejects duplicate rates for the same pair and date', () => {
expect(() =>
convertBenchmarkPrices({
prices: [prices[0]],
currencyFrom: 'USD',
currencyTo: 'EUR',
fxQuotes: [...fxQuotes, ...fxQuotes]
})
).toThrow('Duplicate FX rate: USDEUR 2025-01-10');
});
it('prefers a direct pair over an inverse pair', () => {
const result = convertBenchmarkPrices({
prices: [prices[0]],
currencyFrom: 'USD',
currencyTo: 'EUR',
fxQuotes: [
...fxQuotes,
{
currencyFrom: 'EUR',
currencyTo: 'USD',
date: '2025-01-10',
rate: '1.1'
}
]
});
expect(result.prices[0].price).toBe('92');
expect(result.conversions[0].components[0].pair).toBe('USDEUR');
});
it.each(['0', '-1', 'NaN', 'Infinity', '-Infinity'])(
'rejects invalid FX rate %s',
(rate) => {
expect(() =>
convertBenchmarkPrices({
prices: [prices[0]],
currencyFrom: 'USD',
currencyTo: 'EUR',
fxQuotes: [{ ...fxQuotes[0], rate }]
})
).toThrow('Invalid FX rate');
}
);
it('rejects a stale direct rate without falling back to an inverse rate', () => {
expect(() =>
convertBenchmarkPrices({
prices: [{ date: '2025-01-18', price: '100' }],
currencyFrom: 'USD',
currencyTo: 'EUR',
fxQuotes: [
...fxQuotes,
{
currencyFrom: 'EUR',
currencyTo: 'USD',
date: '2025-01-18',
rate: '1.1'
}
]
})
).toThrow('Stale FX rate: USDEUR 2025-01-18');
});
it('converts indirectly from GBP to EUR through USD', () => {
const result = convertBenchmarkPrices({
prices: [{ date: '2025-01-10', price: '80' }],
currencyFrom: 'GBP',
currencyTo: 'EUR',
fxQuotes: [
{
currencyFrom: 'USD',
currencyTo: 'GBP',
date: '2025-01-10',
rate: '0.8'
},
{
currencyFrom: 'USD',
currencyTo: 'EUR',
date: '2025-01-10',
rate: '0.92'
}
]
});
expect(result.prices[0].price).toBe('92');
expect(result.conversions[0].method).toBe('INDIRECT');
expect(result.conversions[0].components).toHaveLength(2);
});
it('preserves independent source dates for indirect FX components', () => {
const result = convertBenchmarkPrices({
prices: [{ date: '2025-01-12', price: '80' }],
currencyFrom: 'GBP',
currencyTo: 'EUR',
fxQuotes: [
{
currencyFrom: 'USD',
currencyTo: 'GBP',
date: '2025-01-10',
rate: '0.8'
},
{
currencyFrom: 'USD',
currencyTo: 'EUR',
date: '2025-01-09',
rate: '0.92'
}
]
});
expect(result.conversions[0].components).toEqual([
{
pair: 'USDGBP',
sourceDate: '2025-01-10',
ageInDays: 2,
rate: '0.8',
kind: 'MARKET'
},
{
pair: 'USDEUR',
sourceDate: '2025-01-09',
ageInDays: 3,
rate: '0.92',
kind: 'MARKET'
}
]);
});
it('rejects an indirect conversion with one stale component', () => {
expect(() =>
convertBenchmarkPrices({
prices: [{ date: '2025-01-18', price: '80' }],
currencyFrom: 'GBP',
currencyTo: 'EUR',
fxQuotes: [
{
currencyFrom: 'USD',
currencyTo: 'GBP',
date: '2025-01-10',
rate: '0.8'
},
{
currencyFrom: 'USD',
currencyTo: 'EUR',
date: '2025-01-17',
rate: '0.92'
}
]
})
).toThrow('Stale FX rate: USDGBP 2025-01-18');
});
it('converts a derived currency using its fixed factor', () => {
const result = convertBenchmarkPrices({
prices: [{ date: '2025-01-10', price: '125' }],
currencyFrom: 'GBp',
currencyTo: 'GBP',
fxQuotes: []
});
expect(result.prices[0].price).toBe('1.25');
expect(result.conversions[0].method).toBe('DERIVED');
expect(result.conversions[0].components).toEqual([
{
pair: 'GBpGBP',
rate: '0.01',
kind: 'FIXED'
}
]);
});
it('converts a derived currency through a market FX rate', () => {
const result = convertBenchmarkPrices({
prices: [{ date: '2025-01-10', price: '8000' }],
currencyFrom: 'GBp',
currencyTo: 'EUR',
fxQuotes: [
{
currencyFrom: 'GBP',
currencyTo: 'EUR',
date: '2025-01-10',
rate: '1.15'
}
]
});
expect(result.prices[0].price).toBe('92');
expect(result.conversions[0].method).toBe('DERIVED');
expect(result.conversions[0].components).toEqual([
{
pair: 'GBpGBP',
rate: '0.01',
kind: 'FIXED'
},
{
pair: 'GBPEUR',
sourceDate: '2025-01-10',
ageInDays: 0,
rate: '1.15',
kind: 'MARKET'
}
]);
});
it('converts indirectly using an inverse USD leg', () => {
const result = convertBenchmarkPrices({
prices: [{ date: '2025-01-10', price: '80' }],
currencyFrom: 'GBP',
currencyTo: 'EUR',
fxQuotes: [
{
currencyFrom: 'GBP',
currencyTo: 'USD',
date: '2025-01-10',
rate: '1.25'
},
{
currencyFrom: 'USD',
currencyTo: 'EUR',
date: '2025-01-10',
rate: '0.92'
}
]
});
expect(result.prices[0].price).toBe('92');
expect(result.conversions[0].method).toBe('INDIRECT');
expect(result.conversions[0].components.map(({ pair }) => pair)).toEqual([
'GBPUSD',
'USDEUR'
]);
});
it('converts from a root currency to its derived currency', () => {
const result = convertBenchmarkPrices({
prices: [{ date: '2025-01-10', price: '1.25' }],
currencyFrom: 'GBP',
currencyTo: 'GBp',
fxQuotes: []
});
expect(result.prices[0].price).toBe('125');
expect(result.conversions[0].method).toBe('DERIVED');
expect(result.conversions[0].components).toEqual([
{
pair: 'GBPGBp',
rate: '100',
kind: 'FIXED'
}
]);
});
it('converts through a market rate into a derived currency', () => {
const result = convertBenchmarkPrices({
prices: [{ date: '2025-01-10', price: '1' }],
currencyFrom: 'EUR',
currencyTo: 'GBp',
fxQuotes: [
{
currencyFrom: 'EUR',
currencyTo: 'GBP',
date: '2025-01-10',
rate: '0.8'
}
]
});
expect(result.prices[0].price).toBe('80');
expect(result.conversions[0].method).toBe('DERIVED');
expect(result.conversions[0].components).toEqual([
{
pair: 'EURGBP',
sourceDate: '2025-01-10',
ageInDays: 0,
rate: '0.8',
kind: 'MARKET'
},
{
pair: 'GBPGBp',
rate: '100',
kind: 'FIXED'
}
]);
});
it('preserves identical currencies despite unrelated FX quotes', () => {
const input = {
prices: [{ date: '2025-01-10', price: '123.456789' }],
currencyFrom: 'EUR',
currencyTo: 'EUR',
fxQuotes: [
{
currencyFrom: 'USD',
currencyTo: 'GBP',
date: '2025-01-10',
rate: '0.8'
}
]
};
const result = convertBenchmarkPrices(input);
expect(result.prices).toEqual(input.prices);
expect(result.conversions[0].method).toBe('IDENTITY');
expect(result.conversions[0].rate).toBe('1');
});
it('preserves an identical derived currency', () => {
const result = convertBenchmarkPrices({
prices: [{ date: '2025-01-10', price: '125' }],
currencyFrom: 'GBp',
currencyTo: 'GBp',
fxQuotes: []
});
expect(result.prices[0].price).toBe('125');
expect(result.conversions[0].rate).toBe('1');
});
it('converts between derived currencies through their roots', () => {
const result = convertBenchmarkPrices({
prices: [{ date: '2025-01-10', price: '100' }],
currencyFrom: 'GBp',
currencyTo: 'ZAc',
fxQuotes: [
{
currencyFrom: 'GBP',
currencyTo: 'ZAR',
date: '2025-01-10',
rate: '24'
}
]
});
expect(result.prices[0].price).toBe('2400');
expect(result.conversions[0].method).toBe('DERIVED');
expect(result.conversions[0].components.map(({ kind }) => kind)).toEqual([
'FIXED',
'MARKET',
'FIXED'
]);
});
it('avoids a rounded reciprocal in indirect conversion', () => {
const result = convertBenchmarkPrices({
prices: [{ date: '2025-01-10', price: '92' }],
currencyFrom: 'EUR',
currencyTo: 'GBP',
fxQuotes: [
{
currencyFrom: 'USD',
currencyTo: 'EUR',
date: '2025-01-10',
rate: '0.92'
},
{
currencyFrom: 'USD',
currencyTo: 'GBP',
date: '2025-01-10',
rate: '0.8'
}
]
});
expect(result.prices[0].price).toBe('80');
expect(result.conversions[0].method).toBe('INDIRECT');
});
it.each(['0', '-1', 'NaN', 'Infinity', '-Infinity'])(
'rejects invalid benchmark price %s',
(price) => {
expect(() =>
convertBenchmarkPrices({
prices: [{ date: '2025-01-10', price }],
currencyFrom: 'USD',
currencyTo: 'EUR',
fxQuotes
})
).toThrow('Invalid benchmark price');
}
);
it.each(['2025-02-30', 'invalid', '2025-13-01'])(
'rejects invalid benchmark date %s',
(date) => {
expect(() =>
convertBenchmarkPrices({
prices: [{ date, price: '100' }],
currencyFrom: 'USD',
currencyTo: 'EUR',
fxQuotes
})
).toThrow('Invalid FX date');
}
);
it.each(['2025-02-30', 'invalid', '2025-13-01'])(
'rejects invalid FX quotation date %s',
(date) => {
expect(() =>
convertBenchmarkPrices({
prices: [prices[0]],
currencyFrom: 'USD',
currencyTo: 'EUR',
fxQuotes: [{ ...fxQuotes[0], date }]
})
).toThrow('Invalid FX date');
}
);
it.each([-1, 1.5, NaN, Infinity])(
'rejects invalid FX age limit %s',
(maxFxAgeDays) => {
expect(() =>
convertBenchmarkPrices({
prices: [prices[0]],
currencyFrom: 'USD',
currencyTo: 'EUR',
fxQuotes,
maxFxAgeDays
})
).toThrow('Invalid maximum price age');
}
);
it('is independent of FX quote input order', () => {
const quotes = [
...fxQuotes,
{
currencyFrom: 'USD',
currencyTo: 'EUR',
date: '2025-01-09',
rate: '0.91'
}
];
const input = {
prices,
currencyFrom: 'USD',
currencyTo: 'EUR',
fxQuotes: quotes
};
expect(convertBenchmarkPrices(input)).toEqual(
convertBenchmarkPrices({
...input,
fxQuotes: [...quotes].reverse()
})
);
});
});

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

@ -0,0 +1,368 @@
import {
DERIVED_CURRENCIES,
DEFAULT_CURRENCY
} from '@ghostfolio/common/config';
import { Big } from 'big.js';
import { BenchmarkPrice } from './activity-matched-benchmark';
import {
DEFAULT_MAX_PRICE_AGE_DAYS,
validateMaxPriceAgeDays
} from './benchmark-price-policy';
export interface BenchmarkFxQuote {
currencyFrom: string;
currencyTo: string;
date: string;
rate: string;
}
export type BenchmarkFxConversionMethod =
'IDENTITY' | 'DIRECT' | 'INDIRECT' | 'DERIVED';
export interface BenchmarkFxComponent {
pair: string;
sourceDate?: string;
ageInDays?: number;
rate: string;
kind: 'MARKET' | 'FIXED';
}
export interface BenchmarkFxConversion {
date: string;
method: BenchmarkFxConversionMethod;
rate: string;
components: BenchmarkFxComponent[];
}
export interface BenchmarkFxResult {
prices: BenchmarkPrice[];
conversions: BenchmarkFxConversion[];
}
export interface BenchmarkFxInput {
prices: BenchmarkPrice[];
currencyFrom: string;
currencyTo: string;
fxQuotes: BenchmarkFxQuote[];
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 FX date: ${date}`);
}
return time / 86400000;
}
type ResolvedQuote = BenchmarkFxQuote & {
day: number;
rateValue: Big;
};
interface FxLeg {
pair: string;
inverse: boolean;
quotes: ResolvedQuote[];
}
function resolveLeg(
currencyFrom: string,
currencyTo: string,
quotes: ResolvedQuote[]
): FxLeg | undefined {
const direct = quotes.filter(
(quote) =>
quote.currencyFrom === currencyFrom && quote.currencyTo === currencyTo
);
if (direct.length > 0) {
return {
pair: `${currencyFrom}${currencyTo}`,
inverse: false,
quotes: direct
};
}
const inverse = quotes.filter(
(quote) =>
quote.currencyFrom === currencyTo && quote.currencyTo === currencyFrom
);
if (inverse.length > 0) {
return {
pair: `${currencyTo}${currencyFrom}`,
inverse: true,
quotes: inverse
};
}
return undefined;
}
export function findLatestFxQuote<T extends { day: number }>(
quotes: T[],
targetDay: number
): T | undefined {
let low = 0;
let high = quotes.length - 1;
let result: T | 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;
}
function selectRate({
leg,
date,
day,
maxAge
}: {
leg: FxLeg;
date: string;
day: number;
maxAge: number;
}): {
quote: ResolvedQuote;
component: BenchmarkFxComponent;
} {
const quote = findLatestFxQuote(leg.quotes, day);
if (!quote) {
throw new Error(`Missing FX rate: ${leg.pair} ${date}`);
}
const ageInDays = day - quote.day;
if (ageInDays > maxAge) {
throw new Error(`Stale FX rate: ${leg.pair} ${date}`);
}
return {
quote,
component: {
pair: leg.pair,
sourceDate: quote.date,
ageInDays,
rate: quote.rateValue.toString(),
kind: 'MARKET'
}
};
}
export function convertBenchmarkPrices({
prices,
currencyFrom,
currencyTo,
fxQuotes,
maxFxAgeDays = DEFAULT_MAX_PRICE_AGE_DAYS
}: BenchmarkFxInput): BenchmarkFxResult {
validateMaxPriceAgeDays(maxFxAgeDays);
const quotes = fxQuotes
.map((quote): ResolvedQuote => {
const day = calendarDay(quote.date);
let rateValue: Big;
try {
rateValue = new Big(quote.rate);
} catch {
throw new Error(`Invalid FX rate: ${quote.date}`);
}
if (!rateValue.gt(0)) {
throw new Error(`Invalid FX rate: ${quote.date}`);
}
return { ...quote, day, rateValue };
})
.sort((a, b) => a.day - b.day);
const seen = new Set<string>();
for (const quote of quotes) {
const key = `${quote.currencyFrom}|${quote.currencyTo}|${quote.date}`;
if (seen.has(key)) {
throw new Error(
`Duplicate FX rate: ${quote.currencyFrom}${quote.currencyTo} ${quote.date}`
);
}
seen.add(key);
}
const derivedFrom = DERIVED_CURRENCIES.find(
({ currency }) => currency === currencyFrom
);
const derivedTo = DERIVED_CURRENCIES.find(
({ currency }) => currency === currencyTo
);
const rootFrom = derivedFrom?.rootCurrency ?? currencyFrom;
const rootTo = derivedTo?.rootCurrency ?? currencyTo;
const fixedFactor = derivedFrom
? new Big(1).div(derivedFrom.factor)
: new Big(1);
const fixedComponent: BenchmarkFxComponent | undefined = derivedFrom
? {
pair: `${currencyFrom}${rootFrom}`,
rate: fixedFactor.toString(),
kind: 'FIXED'
}
: undefined;
const targetFixedComponent: BenchmarkFxComponent | undefined = derivedTo
? {
pair: `${rootTo}${currencyTo}`,
rate: new Big(derivedTo.factor).toString(),
kind: 'FIXED'
}
: undefined;
const directLeg =
rootFrom === rootTo ? undefined : resolveLeg(rootFrom, rootTo, quotes);
const indirectFrom =
rootFrom === DEFAULT_CURRENCY
? undefined
: resolveLeg(DEFAULT_CURRENCY, rootFrom, quotes);
const indirectTo =
rootTo === DEFAULT_CURRENCY
? undefined
: resolveLeg(DEFAULT_CURRENCY, rootTo, quotes);
const useIndirect =
rootFrom !== rootTo &&
!directLeg &&
(rootFrom === DEFAULT_CURRENCY || !!indirectFrom) &&
(rootTo === DEFAULT_CURRENCY || !!indirectTo);
const conversions: BenchmarkFxConversion[] = [];
const convertedPrices: BenchmarkPrice[] = [];
for (const price of prices) {
const priceDay = calendarDay(price.date);
let amount: Big;
try {
amount = new Big(price.price);
} catch {
throw new Error(`Invalid benchmark price: ${price.date}`);
}
if (!amount.gt(0)) {
throw new Error(`Invalid benchmark price: ${price.date}`);
}
const components: BenchmarkFxComponent[] = [];
let converted = amount.mul(fixedFactor);
let method: BenchmarkFxConversionMethod =
derivedFrom || derivedTo ? 'DERIVED' : 'IDENTITY';
if (fixedComponent) {
components.push(fixedComponent);
}
if (rootFrom !== rootTo) {
if (directLeg) {
const { quote, component } = selectRate({
leg: directLeg,
date: price.date,
day: priceDay,
maxAge: maxFxAgeDays
});
converted = directLeg.inverse
? converted.div(quote.rateValue)
: converted.mul(quote.rateValue);
components.push(component);
if (!derivedFrom && !derivedTo) {
method = 'DIRECT';
}
} else if (useIndirect) {
if (indirectFrom) {
const { quote, component } = selectRate({
leg: indirectFrom,
date: price.date,
day: priceDay,
maxAge: maxFxAgeDays
});
converted = indirectFrom.inverse
? converted.mul(quote.rateValue)
: converted.div(quote.rateValue);
components.push(component);
}
if (indirectTo) {
const { quote, component } = selectRate({
leg: indirectTo,
date: price.date,
day: priceDay,
maxAge: maxFxAgeDays
});
converted = indirectTo.inverse
? converted.div(quote.rateValue)
: converted.mul(quote.rateValue);
components.push(component);
}
if (!derivedFrom && !derivedTo) {
method = 'INDIRECT';
}
} else {
throw new Error(`Missing FX rate: ${rootFrom}${rootTo} ${price.date}`);
}
}
if (targetFixedComponent) {
converted = converted.mul(derivedTo.factor);
components.push(targetFixedComponent);
}
convertedPrices.push({
...price,
price: converted.toString()
});
conversions.push({
date: price.date,
method,
rate: converted.div(amount).toString(),
components
});
}
return {
prices: convertedPrices,
conversions
};
}

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

@ -0,0 +1,175 @@
import { MarketData } from '@prisma/client';
import { adaptBenchmarkMarketData } from './benchmark-market-data.adapter';
function marketData({
date,
price = 100,
carriedForward = false,
state = 'CLOSE'
}: {
date: string;
price?: number;
carriedForward?: boolean;
state?: 'CLOSE' | 'INTRADAY';
}): 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 MarketData adapter', () => {
it('keeps original CLOSE prices in chronological order', () => {
const result = adaptBenchmarkMarketData({
marketData: [
marketData({ date: '2025-01-13', price: 102 }),
marketData({ date: '2025-01-10', price: 100 })
]
});
expect(result.prices).toEqual([
{ date: '2025-01-10', price: '100' },
{ date: '2025-01-13', price: '102' }
]);
expect(result.excludedCarriedForward).toBe(0);
expect(result.excludedIntraday).toBe(0);
});
it('excludes carried-forward records', () => {
const result = adaptBenchmarkMarketData({
marketData: [
marketData({ date: '2025-01-10', price: 100 }),
marketData({
date: '2025-01-11',
price: 100,
carriedForward: true
}),
marketData({
date: '2025-01-12',
price: 100,
carriedForward: true
})
]
});
expect(result.prices).toEqual([{ date: '2025-01-10', price: '100' }]);
expect(result.excludedCarriedForward).toBe(2);
});
it('excludes INTRADAY quotations', () => {
const result = adaptBenchmarkMarketData({
marketData: [
marketData({ date: '2025-01-10' }),
marketData({
date: '2025-01-13',
price: 110,
state: 'INTRADAY'
})
]
});
expect(result.prices).toHaveLength(1);
expect(result.excludedIntraday).toBe(1);
});
it('preserves unchanged genuine CLOSE prices', () => {
const result = adaptBenchmarkMarketData({
marketData: [
marketData({ date: '2025-01-10', price: 100 }),
marketData({ date: '2025-01-13', price: 100 })
]
});
expect(result.prices).toHaveLength(2);
});
it.each([0, -1, NaN, Infinity, -Infinity])(
'rejects invalid original price %s',
(price) => {
expect(() =>
adaptBenchmarkMarketData({
marketData: [marketData({ date: '2025-01-10', price })]
})
).toThrow('Invalid benchmark market price');
}
);
it('rejects an invalid Date object', () => {
const record = marketData({ date: '2025-01-10' });
record.date = new Date(NaN);
expect(() => adaptBenchmarkMarketData({ marketData: [record] })).toThrow(
'Invalid benchmark market date'
);
});
it('rejects a non-Date value', () => {
const record = marketData({ date: '2025-01-10' });
const invalidRecord = {
...record,
date: '2025-01-10'
} as unknown as MarketData;
expect(() =>
adaptBenchmarkMarketData({ marketData: [invalidRecord] })
).toThrow('Invalid benchmark market date');
});
it('rejects duplicate original dates', () => {
expect(() =>
adaptBenchmarkMarketData({
marketData: [
marketData({ date: '2025-01-10', price: 100 }),
marketData({ date: '2025-01-10', price: 101 })
]
})
).toThrow('Duplicate benchmark price');
});
it('returns no original prices when all records are carried forward', () => {
const result = adaptBenchmarkMarketData({
marketData: [
marketData({
date: '2025-01-11',
carriedForward: true
}),
marketData({
date: '2025-01-12',
carriedForward: true
})
]
});
expect(result.prices).toEqual([]);
expect(result.excludedCarriedForward).toBe(2);
});
it('does not mutate input records or their order', () => {
const records = [
marketData({ date: '2025-01-13', price: 102 }),
marketData({ date: '2025-01-10', price: 100 })
];
const original = records.map(({ date, marketPrice }) => ({
date: date.toISOString(),
marketPrice
}));
adaptBenchmarkMarketData({ marketData: records });
expect(
records.map(({ date, marketPrice }) => ({
date: date.toISOString(),
marketPrice
}))
).toEqual(original);
});
});

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

@ -0,0 +1,64 @@
import { MarketData } from '@prisma/client';
import { Big } from 'big.js';
import { format } from 'date-fns';
import { BenchmarkPrice } from './activity-matched-benchmark';
export interface BenchmarkMarketDataResult {
prices: BenchmarkPrice[];
excludedCarriedForward: number;
excludedIntraday: number;
}
export function adaptBenchmarkMarketData({
marketData
}: {
marketData: MarketData[];
}): BenchmarkMarketDataResult {
const prices: BenchmarkPrice[] = [];
let excludedCarriedForward = 0;
let excludedIntraday = 0;
for (const item of marketData) {
if (item.isCarriedForward) {
excludedCarriedForward += 1;
continue;
}
if (item.state !== 'CLOSE') {
excludedIntraday += 1;
continue;
}
if (!(item.date instanceof Date) || !Number.isFinite(item.date.getTime())) {
throw new Error('Invalid benchmark market date');
}
if (!Number.isFinite(item.marketPrice) || item.marketPrice <= 0) {
throw new Error(
`Invalid benchmark market price: ${format(item.date, 'yyyy-MM-dd')}`
);
}
const price = new Big(item.marketPrice);
prices.push({
date: format(item.date, 'yyyy-MM-dd'),
price: price.toString()
});
}
prices.sort((a, b) => a.date.localeCompare(b.date));
for (let i = 1; i < prices.length; i++) {
if (prices[i].date === prices[i - 1].date) {
throw new Error(`Duplicate benchmark price: ${prices[i].date}`);
}
}
return {
prices,
excludedCarriedForward,
excludedIntraday
};
}

100
apps/api/src/services/benchmark/prototype/benchmark-market-data.integration.spec.ts

@ -0,0 +1,100 @@
import { MarketData } from '@prisma/client';
import { adaptBenchmarkMarketData } from './benchmark-market-data.adapter';
import { prepareBenchmarkPrices } from './benchmark-price.adapter';
function quote({
date,
price = 100,
carriedForward = false
}: {
date: string;
price?: number;
carriedForward?: boolean;
}): 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: 'CLOSE'
};
}
describe('Benchmark MarketData provenance integration', () => {
it('preserves Friday as the source of a Sunday execution', () => {
const adapted = adaptBenchmarkMarketData({
marketData: [
quote({ date: '2025-01-10' }),
quote({
date: '2025-01-11',
carriedForward: true
}),
quote({
date: '2025-01-12',
carriedForward: true
})
]
});
expect(adapted.prices).toEqual([{ date: '2025-01-10', price: '100' }]);
const prepared = prepareBenchmarkPrices({
executionDates: ['2025-01-12'],
prices: adapted.prices
});
expect(prepared.carriedForward).toEqual([
{
date: '2025-01-12',
sourceDate: '2025-01-10',
ageInDays: 2
}
]);
expect(prepared.prices).toContainEqual({
date: '2025-01-12',
price: '100',
sourceDate: '2025-01-10'
});
});
it('rejects an execution eight days after the last original quote', () => {
const adapted = adaptBenchmarkMarketData({
marketData: [
quote({ date: '2025-01-10' }),
...Array.from({ length: 8 }, (_, index) =>
quote({
date: `2025-01-${String(index + 11).padStart(2, '0')}`,
carriedForward: true
})
)
]
});
expect(adapted.excludedCarriedForward).toBe(8);
expect(() =>
prepareBenchmarkPrices({
executionDates: ['2025-01-18'],
prices: adapted.prices
})
).toThrow('Stale execution price: 2025-01-18');
});
it('never uses a future original quote for an earlier execution', () => {
const adapted = adaptBenchmarkMarketData({
marketData: [quote({ date: '2025-01-13', price: 105 })]
});
expect(() =>
prepareBenchmarkPrices({
executionDates: ['2025-01-12'],
prices: adapted.prices
})
).toThrow('Missing historical price: 2025-01-12');
});
});

106
apps/api/src/services/benchmark/prototype/benchmark-price-policy.spec.ts

@ -0,0 +1,106 @@
import { simulateBenchmark } from './activity-matched-benchmark';
import {
DEFAULT_MAX_PRICE_AGE_DAYS,
validateMaxPriceAgeDays
} from './benchmark-price-policy';
import { prepareBenchmarkPrices } from './benchmark-price.adapter';
const firstDate = '2025-01-10';
function dateAfter(days: number): string {
const date = new Date('2025-01-10T00:00:00Z');
date.setUTCDate(date.getUTCDate() + days);
return date.toISOString().slice(0, 10);
}
describe('Benchmark price age policy', () => {
it('defaults to seven calendar days', () => {
expect(DEFAULT_MAX_PRICE_AGE_DAYS).toBe(7);
});
it.each([
[0, 0, true],
[0, 1, false],
[3, 2, true],
[3, 4, false],
[7, 7, true],
[7, 8, false],
[10, 8, true]
])('adapter: limit %i, age %i, accepted %s', (limit, age, accepted) => {
const execute = () =>
prepareBenchmarkPrices({
executionDates: [dateAfter(age)],
maxExecutionAgeDays: limit,
prices: [{ date: firstDate, price: '10' }]
});
if (accepted) {
expect(execute).not.toThrow();
} else {
expect(execute).toThrow('Stale execution price');
}
});
it.each([
[0, 0, true],
[0, 1, false],
[3, 2, true],
[3, 4, false],
[7, 7, true],
[7, 8, false],
[10, 8, true]
])('simulator: limit %i, age %i, accepted %s', (limit, age, accepted) => {
const executionDate = dateAfter(age);
const execute = () =>
simulateBenchmark({
flows: [{ date: executionDate, amount: '100' }],
maxPriceAgeDays: limit,
prices: [
{ date: firstDate, price: '10' },
...(age > 0
? [
{
date: executionDate,
price: '10',
sourceDate: firstDate
}
]
: [])
],
valuationDates: [executionDate]
});
if (accepted) {
expect(execute).not.toThrow();
} else {
expect(execute).toThrow('Stale execution price');
}
});
it.each([-1, 1.5, NaN, Infinity, -Infinity])(
'rejects invalid limit %s in both components',
(limit) => {
expect(() => validateMaxPriceAgeDays(limit)).toThrow(
'Invalid maximum price age'
);
expect(() =>
prepareBenchmarkPrices({
executionDates: [],
maxExecutionAgeDays: limit,
prices: []
})
).toThrow('Invalid maximum price age');
expect(() =>
simulateBenchmark({
flows: [],
maxPriceAgeDays: limit,
prices: [],
valuationDates: []
})
).toThrow('Invalid maximum price age');
}
);
});

9
apps/api/src/services/benchmark/prototype/benchmark-price-policy.ts

@ -0,0 +1,9 @@
export const DEFAULT_MAX_PRICE_AGE_DAYS = 7;
export function validateMaxPriceAgeDays(value: number): number {
if (!Number.isInteger(value) || value < 0) {
throw new Error('Invalid maximum price age');
}
return value;
}

152
apps/api/src/services/benchmark/prototype/benchmark-price-staleness.spec.ts

@ -0,0 +1,152 @@
import { evaluateRange, simulateBenchmark } from './activity-matched-benchmark';
import { prepareBenchmarkPrices } from './benchmark-price.adapter';
const friday = '2025-01-10';
const sunday = '2025-01-12';
const nextFriday = '2025-01-17';
const nextSaturday = '2025-01-18';
function simulate({
flows,
prices,
valuationDates
}: {
flows: { date: string; amount: string }[];
prices: { date: string; price: string; sourceDate?: string }[];
valuationDates: string[];
}) {
return simulateBenchmark({ flows, prices, valuationDates });
}
describe('Benchmark price staleness', () => {
it('accepts a seven-day-old valuation price', () => {
const points = simulate({
flows: [{ date: friday, amount: '100' }],
prices: [{ date: friday, price: '10' }],
valuationDates: [friday, nextFriday]
});
expect(points.at(-1).value.toString()).toBe('100');
});
it('rejects an eight-day-old price on a financial date', () => {
expect(() =>
simulate({
flows: [
{ date: friday, amount: '100' },
{ date: nextSaturday, amount: '10' }
],
prices: [
{ date: friday, price: '10' },
{
date: nextSaturday,
price: '10',
sourceDate: friday
}
],
valuationDates: [friday, nextSaturday]
})
).toThrow('Stale execution price: 2025-01-18');
});
it('never resets quote age through synthetic execution prices', () => {
expect(() =>
prepareBenchmarkPrices({
executionDates: [sunday, nextSaturday],
prices: [{ date: friday, price: '10' }]
})
).toThrow('Stale execution price: 2025-01-18');
});
it('rejects stale execution prices even when selling all units', () => {
expect(() =>
simulate({
flows: [
{ date: friday, amount: '100' },
{ date: nextSaturday, amount: '-100' }
],
prices: [
{ date: friday, price: '10' },
{
date: nextSaturday,
price: '10',
sourceDate: friday
}
],
valuationDates: [friday, nextSaturday]
})
).toThrow('Stale execution price: 2025-01-18');
});
it('rejects stale valuation without a new execution', () => {
expect(() =>
simulate({
flows: [{ date: friday, amount: '100' }],
prices: [
{ date: friday, price: '10' },
{
date: nextSaturday,
price: '10',
sourceDate: friday
}
],
valuationDates: [friday, nextSaturday]
})
).toThrow('Stale valuation price: 2025-01-18');
});
it('does not require a fresh valuation after full liquidation', () => {
const points = simulate({
flows: [
{ date: friday, amount: '100' },
{ date: sunday, amount: '-100' }
],
prices: [
{ date: friday, price: '10' },
{ date: sunday, price: '10', sourceDate: friday }
],
valuationDates: [friday, sunday, nextSaturday]
});
expect(points.at(-1).units.toString()).toBe('0');
expect(points.at(-1).value.toString()).toBe('0');
});
it('does not change financial returns when adding display dates', () => {
const input = {
flows: [{ date: friday, amount: '100' }],
prices: [
{ date: friday, price: '10' },
{ date: nextFriday, price: '12' }
]
};
const sparse = simulate({
...input,
valuationDates: [friday, nextFriday]
});
const dense = simulate({
...input,
valuationDates: [
friday,
sunday,
'2025-01-13',
'2025-01-14',
'2025-01-15',
'2025-01-16',
nextFriday
]
});
for (const method of ['ROI', 'ROAI'] as const) {
const sparseResult = evaluateRange(sparse, method, friday, nextFriday);
const denseResult = evaluateRange(dense, method, friday, nextFriday);
expect(denseResult.at(-1).returnFraction.toString()).toBe(
sparseResult.at(-1).returnFraction.toString()
);
}
});
});

105
apps/api/src/services/benchmark/prototype/benchmark-price.adapter.spec.ts

@ -0,0 +1,105 @@
import { prepareBenchmarkPrices } from './benchmark-price.adapter';
describe('Benchmark price adapter', () => {
it('preserves exact execution prices', () => {
const result = prepareBenchmarkPrices({
executionDates: ['2025-01-10'],
prices: [{ date: '2025-01-10', price: '100' }]
});
expect(result.prices).toEqual([{ date: '2025-01-10', price: '100' }]);
expect(result.carriedForward).toEqual([]);
});
it('uses Friday close for a Sunday execution', () => {
const result = prepareBenchmarkPrices({
executionDates: ['2025-01-12'],
prices: [
{ date: '2025-01-10', price: '100' },
{ date: '2025-01-13', price: '110' }
]
});
expect(result.prices).toEqual([
{ date: '2025-01-10', price: '100' },
{
date: '2025-01-12',
price: '100',
sourceDate: '2025-01-10'
},
{ date: '2025-01-13', price: '110' }
]);
expect(result.carriedForward).toEqual([
{
date: '2025-01-12',
sourceDate: '2025-01-10',
ageInDays: 2
}
]);
});
it('accepts the maximum price age of seven days', () => {
const result = prepareBenchmarkPrices({
executionDates: ['2025-01-17'],
prices: [{ date: '2025-01-10', price: '100' }]
});
expect(result.carriedForward[0].ageInDays).toBe(7);
});
it('rejects prices older than seven days', () => {
expect(() =>
prepareBenchmarkPrices({
executionDates: ['2025-01-18'],
prices: [{ date: '2025-01-10', price: '100' }]
})
).toThrow('Stale execution price: 2025-01-18');
});
it('never uses a future price', () => {
expect(() =>
prepareBenchmarkPrices({
executionDates: ['2025-01-12'],
prices: [{ date: '2025-01-13', price: '110' }]
})
).toThrow('Missing historical price: 2025-01-12');
});
it('rejects duplicate price dates', () => {
expect(() =>
prepareBenchmarkPrices({
executionDates: [],
prices: [
{ date: '2025-01-10', price: '100' },
{ date: '2025-01-10', price: '101' }
]
})
).toThrow('Duplicate benchmark price: 2025-01-10');
});
it.each(['0', '-1', 'invalid'])('rejects invalid price %s', (price) => {
expect(() =>
prepareBenchmarkPrices({
executionDates: [],
prices: [{ date: '2025-01-10', price }]
})
).toThrow();
});
it('does not mutate the original inputs', () => {
const prices = [
{ date: '2025-01-13', price: '110' },
{ date: '2025-01-10', price: '100' }
];
const executionDates = ['2025-01-12'];
const originalPrices = structuredClone(prices);
const originalDates = [...executionDates];
prepareBenchmarkPrices({ executionDates, prices });
expect(prices).toEqual(originalPrices);
expect(executionDates).toEqual(originalDates);
});
});

116
apps/api/src/services/benchmark/prototype/benchmark-price.adapter.ts

@ -0,0 +1,116 @@
import { Big } from 'big.js';
import { BenchmarkPrice } from './activity-matched-benchmark';
import {
DEFAULT_MAX_PRICE_AGE_DAYS,
validateMaxPriceAgeDays
} from './benchmark-price-policy';
export interface PreparedBenchmarkPrice extends BenchmarkPrice {
sourceDate?: string;
}
export interface BenchmarkPriceAdapterResult {
prices: PreparedBenchmarkPrice[];
carriedForward: {
date: string;
sourceDate: string;
ageInDays: 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 date: ${date}`);
}
return time / 86400000;
}
export function prepareBenchmarkPrices({
executionDates,
maxExecutionAgeDays = DEFAULT_MAX_PRICE_AGE_DAYS,
prices
}: {
executionDates: string[];
maxExecutionAgeDays?: number;
prices: BenchmarkPrice[];
}): BenchmarkPriceAdapterResult {
validateMaxPriceAgeDays(maxExecutionAgeDays);
const quotes = prices
.map(({ date, price }) => {
const day = calendarDay(date);
const amount = new Big(price);
if (!amount.gt(0)) {
throw new Error(`Invalid benchmark price: ${date}`);
}
return { date, day, price: amount.toString() };
})
.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 executions = [...new Set(executionDates)]
.map((date) => ({ date, day: calendarDay(date) }))
.sort((a, b) => a.day - b.day);
const synthetic: PreparedBenchmarkPrice[] = [];
const carriedForward: BenchmarkPriceAdapterResult['carriedForward'] = [];
let quoteIndex = 0;
let previous: (typeof quotes)[number] | undefined;
for (const execution of executions) {
while (
quoteIndex < quotes.length &&
quotes[quoteIndex].day <= execution.day
) {
previous = quotes[quoteIndex++];
}
if (!previous) {
throw new Error(`Missing historical price: ${execution.date}`);
}
const ageInDays = execution.day - previous.day;
if (ageInDays > maxExecutionAgeDays) {
throw new Error(`Stale execution price: ${execution.date}`);
}
if (previous.day !== execution.day) {
synthetic.push({
date: execution.date,
price: previous.price,
sourceDate: previous.date
});
carriedForward.push({
date: execution.date,
sourceDate: previous.date,
ageInDays
});
}
}
return {
prices: [
...quotes.map(({ date, price }) => ({ date, price })),
...synthetic
].sort((a, b) => a.date.localeCompare(b.date)),
carriedForward
};
}

108
apps/api/src/services/benchmark/prototype/benchmark-valuation-status.spec.ts

@ -0,0 +1,108 @@
import { evaluateRange, simulateBenchmark } from './activity-matched-benchmark';
import { prepareBenchmarkPrices } from './benchmark-price.adapter';
const friday = '2025-01-10';
const sunday = '2025-01-12';
const nextFriday = '2025-01-17';
const nextSaturday = '2025-01-18';
describe('Benchmark valuation status', () => {
it('marks a real same-day quotation as CURRENT', () => {
const points = simulateBenchmark({
flows: [{ date: friday, amount: '100' }],
prices: [{ date: friday, price: '10' }],
valuationDates: [friday]
});
expect(points[0].valuationStatus).toBe('CURRENT');
});
it('marks a recent weekend carry-forward as CARRIED_FORWARD', () => {
const prepared = prepareBenchmarkPrices({
executionDates: [sunday],
prices: [{ date: friday, price: '10' }]
});
const points = simulateBenchmark({
flows: [{ date: sunday, amount: '100' }],
prices: prepared.prices,
valuationDates: [sunday]
});
expect(points.at(-1).valuationStatus).toBe('CARRIED_FORWARD');
});
it('marks a stale display-only valuation without changing financial points', () => {
const points = simulateBenchmark({
flows: [{ date: friday, amount: '100' }],
prices: [
{ date: friday, price: '10' },
{ date: '2025-01-20', price: '12' }
],
valuationDates: [friday, nextSaturday, '2025-01-20']
});
const stale = points.find(({ date }) => date === nextSaturday);
expect(stale.displayOnly).toBe(true);
expect(stale.valuationStatus).toBe('STALE');
expect(stale.value.toString()).toBe('100');
});
it('marks fully liquidated positions as NOT_APPLICABLE', () => {
const prepared = prepareBenchmarkPrices({
executionDates: [friday, sunday],
prices: [{ date: friday, price: '10' }]
});
const points = simulateBenchmark({
flows: [
{ date: friday, amount: '100' },
{ date: sunday, amount: '-100' }
],
prices: prepared.prices,
valuationDates: [friday, sunday, nextSaturday]
});
expect(points.at(-1).units.toString()).toBe('0');
expect(points.at(-1).valuationStatus).toBe('NOT_APPLICABLE');
});
it('preserves ROI and ROAI when display-only dates are added', () => {
const input = {
flows: [{ date: friday, amount: '100' }],
prices: [
{ date: friday, price: '10' },
{ date: '2025-01-20', price: '12' }
]
};
const sparse = simulateBenchmark({
...input,
valuationDates: [friday, '2025-01-20']
});
const dense = simulateBenchmark({
...input,
valuationDates: [friday, sunday, nextFriday, nextSaturday, '2025-01-20']
});
for (const method of ['ROI', 'ROAI'] as const) {
const sparseReturns = evaluateRange(sparse, method, friday, '2025-01-20');
const denseReturns = evaluateRange(dense, method, friday, '2025-01-20');
expect(
denseReturns.map(({ date, returnFraction }) => ({
date,
returnFraction: returnFraction.toString()
}))
).toEqual(
sparseReturns.map(({ date, returnFraction }) => ({
date,
returnFraction: returnFraction.toString()
}))
);
}
});
});

178
apps/api/src/services/benchmark/prototype/upstream-realized-gain.characterization.spec.ts

@ -0,0 +1,178 @@
import {
activityDummyData,
assetProfileDummyData,
userDummyData
} from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator-test-utils';
import { PortfolioCalculatorFactory } from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator.factory';
import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service';
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service';
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service';
import { PortfolioSnapshotService } from '@ghostfolio/api/services/queues/portfolio-snapshot/portfolio-snapshot.service';
import { PortfolioSnapshotServiceMock } from '@ghostfolio/api/services/queues/portfolio-snapshot/portfolio-snapshot.service.mock';
import { RedisCacheService } from '@ghostfolio/api/services/redis-cache/redis-cache.service';
import { RedisCacheServiceMock } from '@ghostfolio/api/services/redis-cache/redis-cache.service.mock';
import { parseDate } from '@ghostfolio/common/helper';
import { Activity } from '@ghostfolio/common/interfaces';
import { PerformanceCalculationType } from '@ghostfolio/common/types/performance-calculation-type.type';
import { simulateBenchmark } from './activity-matched-benchmark';
jest.mock(
'@ghostfolio/api/services/queues/portfolio-snapshot/portfolio-snapshot.service',
() => ({
PortfolioSnapshotService: jest
.fn()
.mockImplementation(() => PortfolioSnapshotServiceMock)
})
);
jest.mock('@ghostfolio/api/services/redis-cache/redis-cache.service', () => ({
RedisCacheService: jest.fn().mockImplementation(() => RedisCacheServiceMock)
}));
describe('upstream realized-gain characterization', () => {
beforeEach(() => {
jest.useFakeTimers().setSystemTime(parseDate('2025-12-15').getTime());
PortfolioSnapshotServiceMock.reset();
RedisCacheServiceMock.reset();
});
afterEach(() => {
jest.useRealTimers();
});
it.each([PerformanceCalculationType.ROI, PerformanceCalculationType.ROAI])(
'characterizes %s accounting',
async (calculationType) => {
const dates = ['2025-12-11', '2025-12-12', '2025-12-13', '2025-12-14'];
const operations = [
{ type: 'BUY', quantity: 10, unitPrice: 10 },
{ type: 'SELL', quantity: 5, unitPrice: 12 },
{ type: 'BUY', quantity: 5, unitPrice: 20 },
{ type: 'SELL', quantity: 5, unitPrice: 20 }
] as const;
const activities = operations.map((operation, index) => ({
...activityDummyData,
id: `characterization-${index}`,
userId: userDummyData.id,
date: parseDate(dates[index]),
type: operation.type,
quantity: operation.quantity,
unitPrice: operation.unitPrice,
unitPriceInAssetProfileCurrency: operation.unitPrice,
fee: 0,
feeInAssetProfileCurrency: 0,
feeInBaseCurrency: 0,
currency: 'USD',
value: operation.quantity * operation.unitPrice,
valueInBaseCurrency: operation.quantity * operation.unitPrice,
assetProfile: {
...assetProfileDummyData,
currency: 'USD',
dataSource: 'YAHOO',
name: 'JNUG',
symbol: 'JNUG'
}
})) as Activity[];
const currentRateService = {
getValues: jest.fn().mockImplementation(async () => ({
dataProviderInfos: [],
errors: [],
values: [...dates, '2025-12-15'].map((date, index) => ({
date: parseDate(date),
dataSource: 'YAHOO',
symbol: 'JNUG',
marketPrice: [10, 12, 20, 20, 20][index]
}))
}))
} as unknown as CurrentRateService;
const exchangeRateDataService = {
getExchangeRatesByCurrency: jest.fn().mockResolvedValue({
USDUSD: Object.fromEntries(dates.map((date) => [date, 1]))
})
} as unknown as ExchangeRateDataService;
const factory = new PortfolioCalculatorFactory(
new ConfigurationService(),
currentRateService,
exchangeRateDataService,
new PortfolioSnapshotService(null, null),
new RedisCacheService(null, null)
);
const calculator = factory.createCalculator({
activities,
calculationType,
currency: 'USD',
usePortfolioSnapshotCache: false,
userId: userDummyData.id
});
const snapshot = await calculator.getSnapshot();
const prototype = simulateBenchmark({
flows: [
{ date: dates[0], amount: '100' },
{ date: dates[1], amount: '-60' },
{ date: dates[2], amount: '100' },
{ date: dates[3], amount: '-100' }
],
prices: dates.map((date, index) => ({
date,
price: String([10, 12, 20, 20][index])
})),
valuationDates: dates
});
const upstreamLast = snapshot.historicalData.at(-1);
const prototypeLast = prototype.at(-1);
console.log(
JSON.stringify(
{
method: calculationType,
upstream: {
activitiesCount: snapshot.activitiesCount,
hasErrors: snapshot.hasErrors,
errors: snapshot.errors,
positionsCount: snapshot.positions.length,
positions: snapshot.positions.map((position) => ({
symbol: position.symbol,
quantity: position.quantity?.toString(),
investment: position.investment?.toString(),
grossPerformance: position.grossPerformance?.toString(),
netPerformance: position.netPerformance?.toString()
})),
historicalData: snapshot.historicalData.map((point) => ({
date: point.date,
value: point.value,
totalInvestment: point.totalInvestment,
netPerformance: point.netPerformance
})),
totalInvestment: snapshot.totalInvestment.toString(),
grossPerformance:
snapshot.positions[0]?.grossPerformance?.toString(),
netPerformance: upstreamLast?.netPerformance,
value: upstreamLast?.value
},
prototype: {
costBasis: prototypeLast.costBasis.toString(),
realizedGain: prototypeLast.realizedGain.toString(),
netPerformance: prototypeLast.netPerformance.toString(),
value: prototypeLast.value.toString()
}
},
null,
2
)
);
expect(snapshot.totalInvestment.toNumber()).toBeCloseTo(75, 10);
expect(prototypeLast.netPerformance.toNumber()).toBeCloseTo(60, 10);
}
);
});
Loading…
Cancel
Save