Browse Source

Merge be612b4863 into 618e6c9d27

pull/8220/merge
PJ 17 hours ago
committed by GitHub
parent
commit
da8b8d8867
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 8
      apps/api/src/app/portfolio/calculator/portfolio-calculator.ts
  2. 580
      apps/api/src/app/portfolio/calculator/roi/portfolio-calculator-same-day-round-trip.spec.ts
  3. 283
      apps/api/src/app/portfolio/calculator/roi/portfolio-calculator.ts
  4. 11
      libs/common/src/lib/models/portfolio-snapshot.ts

8
apps/api/src/app/portfolio/calculator/portfolio-calculator.ts

@ -959,6 +959,10 @@ export abstract class PortfolioCalculator {
return this.holdingBalancesByDate;
}
protected getBaseCurrency() {
return this.currency;
}
protected abstract getHoldingPerformance({
chartDates,
dataSource,
@ -1974,6 +1978,10 @@ export abstract class PortfolioCalculator {
return this.snapshot;
}
protected getCurrentSnapshot() {
return this.snapshot;
}
public getStartDate() {
let firstAccountBalanceDate: Date;
let firstActivityDate: Date;

580
apps/api/src/app/portfolio/calculator/roi/portfolio-calculator-same-day-round-trip.spec.ts

@ -0,0 +1,580 @@
import {
activityDummyData,
assetProfileDummyData,
getPerformanceByDateRange,
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 { CurrentRateServiceMock } from '@ghostfolio/api/app/portfolio/current-rate.service.mock';
import { RedisCacheService } from '@ghostfolio/api/app/redis-cache/redis-cache.service';
import { RedisCacheServiceMock } from '@ghostfolio/api/app/redis-cache/redis-cache.service.mock';
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 { parseDate } from '@ghostfolio/common/helper';
import { Activity } from '@ghostfolio/common/interfaces';
import { PerformanceCalculationType } from '@ghostfolio/common/types/performance-calculation-type.type';
import { Big } from 'big.js';
jest.mock('@ghostfolio/api/app/portfolio/current-rate.service', () => {
return {
CurrentRateService: jest.fn().mockImplementation(() => {
return CurrentRateServiceMock;
})
};
});
jest.mock(
'@ghostfolio/api/services/queues/portfolio-snapshot/portfolio-snapshot.service',
() => {
return {
PortfolioSnapshotService: jest.fn().mockImplementation(() => {
return PortfolioSnapshotServiceMock;
})
};
}
);
jest.mock('@ghostfolio/api/app/redis-cache/redis-cache.service', () => {
return {
RedisCacheService: jest.fn().mockImplementation(() => {
return RedisCacheServiceMock;
})
};
});
describe('PortfolioCalculator (ROI)', () => {
let configurationService: ConfigurationService;
let currentRateService: CurrentRateService;
let exchangeRateDataService: ExchangeRateDataService;
let portfolioCalculatorFactory: PortfolioCalculatorFactory;
let portfolioSnapshotService: PortfolioSnapshotService;
let redisCacheService: RedisCacheService;
beforeEach(() => {
PortfolioSnapshotServiceMock.reset();
RedisCacheServiceMock.reset();
configurationService = new ConfigurationService();
currentRateService = new CurrentRateService(null, null, null);
exchangeRateDataService = new ExchangeRateDataService(
null,
null,
null,
null
);
portfolioSnapshotService = new PortfolioSnapshotService(null, null);
redisCacheService = new RedisCacheService(null, null);
portfolioCalculatorFactory = new PortfolioCalculatorFactory(
configurationService,
currentRateService,
exchangeRateDataService,
portfolioSnapshotService,
redisCacheService
);
});
it('counts invested capital for a buy and full sell on the same day', async () => {
jest.useFakeTimers().setSystemTime(parseDate('2021-12-18').getTime());
const assetProfile = {
...assetProfileDummyData,
currency: 'CHF',
dataSource: 'YAHOO' as const,
name: 'Bâloise Holding AG',
symbol: 'BALN.SW'
};
const activities: Activity[] = [
{
...activityDummyData,
assetProfile,
date: new Date('2021-11-30'),
feeInAssetProfileCurrency: 0,
feeInBaseCurrency: 0,
quantity: 10,
type: 'BUY',
unitPriceInAssetProfileCurrency: 100
},
{
...activityDummyData,
assetProfile,
date: new Date('2021-11-30'),
feeInAssetProfileCurrency: 0,
feeInBaseCurrency: 0,
quantity: 10,
type: 'SELL',
unitPriceInAssetProfileCurrency: 110
}
];
const portfolioCalculator = portfolioCalculatorFactory.createCalculator({
activities,
calculationType: PerformanceCalculationType.ROI,
currency: 'CHF',
usePortfolioSnapshotCache: false,
userId: userDummyData.id
});
const portfolioSnapshot = await portfolioCalculator.computeSnapshot();
const performanceByDateRange = await getPerformanceByDateRange({
portfolioCalculator,
dateRanges: ['max']
});
expect(portfolioSnapshot.positions[0]).toMatchObject({
averageInvestment: new Big('1000'),
grossPerformance: new Big('100'),
investment: new Big('0'),
quantity: new Big('0')
});
expect(performanceByDateRange.max).toMatchObject({
netPerformance: 100,
netPerformanceInPercentage: 0.1,
netPerformanceInPercentageWithCurrencyEffect: 0.1,
netPerformanceWithCurrencyEffect: 100
});
expect(portfolioSnapshot.historicalData.at(-1)).toMatchObject(
expect.objectContaining({
netPerformance: 100,
netPerformanceInPercentage: 0.1,
netPerformanceInPercentageWithCurrencyEffect: 0.1,
netPerformanceWithCurrencyEffect: 100,
totalInvestment: 0,
totalInvestmentValueWithCurrencyEffect: 0
})
);
});
it('counts same-day round-trip capital in addition to existing invested capital', async () => {
jest.useFakeTimers().setSystemTime(parseDate('2021-12-18').getTime());
const existingAssetProfile = {
...assetProfileDummyData,
currency: 'CHF',
dataSource: 'YAHOO' as const,
name: 'Bâloise Holding AG',
symbol: 'BALN.SW'
};
const roundTripAssetProfile = {
...assetProfileDummyData,
currency: 'CHF',
dataSource: 'EOD_HISTORICAL_DATA' as const,
name: 'Bâloise Holding AG',
symbol: 'BALN.SW'
};
const activities: Activity[] = [
{
...activityDummyData,
assetProfile: existingAssetProfile,
date: new Date('2021-11-22'),
feeInAssetProfileCurrency: 0,
feeInBaseCurrency: 0,
quantity: 2,
type: 'BUY',
unitPriceInAssetProfileCurrency: 142.9
},
{
...activityDummyData,
assetProfile: roundTripAssetProfile,
date: new Date('2021-11-30'),
feeInAssetProfileCurrency: 0,
feeInBaseCurrency: 0,
quantity: 2,
type: 'BUY',
unitPriceInAssetProfileCurrency: 100
},
{
...activityDummyData,
assetProfile: roundTripAssetProfile,
date: new Date('2021-11-30'),
feeInAssetProfileCurrency: 0,
feeInBaseCurrency: 0,
quantity: 2,
type: 'SELL',
unitPriceInAssetProfileCurrency: 110
}
];
const portfolioCalculator = portfolioCalculatorFactory.createCalculator({
activities,
calculationType: PerformanceCalculationType.ROI,
currency: 'CHF',
usePortfolioSnapshotCache: false,
userId: userDummyData.id
});
const portfolioSnapshot = await portfolioCalculator.computeSnapshot();
expect(portfolioSnapshot.historicalData.at(-1)).toMatchObject(
expect.objectContaining({
netPerformance: 32,
netPerformanceWithCurrencyEffect: 32,
totalInvestment: 285.8,
totalInvestmentValueWithCurrencyEffect: 285.8
})
);
expect(
portfolioSnapshot.historicalData.at(-1).netPerformanceInPercentage
).toBeCloseTo(32 / 485.8, 14);
expect(
portfolioSnapshot.historicalData.at(-1)
.netPerformanceInPercentageWithCurrencyEffect
).toBeCloseTo(32 / 485.8, 14);
});
it('reuses capital released by a sell for another buy on the same day', async () => {
jest.useFakeTimers().setSystemTime(parseDate('2021-12-18').getTime());
const firstAssetProfile = {
...assetProfileDummyData,
currency: 'CHF',
dataSource: 'YAHOO' as const,
name: 'Bâloise Holding AG',
symbol: 'BALN.SW'
};
const secondAssetProfile = {
...assetProfileDummyData,
currency: 'CHF',
dataSource: 'EOD_HISTORICAL_DATA' as const,
name: 'Bâloise Holding AG',
symbol: 'BALN.SW'
};
const activities: Activity[] = [
{
...activityDummyData,
assetProfile: firstAssetProfile,
date: new Date('2021-11-30'),
feeInAssetProfileCurrency: 0,
feeInBaseCurrency: 0,
quantity: 10,
type: 'BUY',
unitPriceInAssetProfileCurrency: 100
},
{
...activityDummyData,
assetProfile: firstAssetProfile,
date: new Date('2021-11-30'),
feeInAssetProfileCurrency: 0,
feeInBaseCurrency: 0,
quantity: 10,
type: 'SELL',
unitPriceInAssetProfileCurrency: 110
},
{
...activityDummyData,
assetProfile: secondAssetProfile,
date: new Date('2021-11-30'),
feeInAssetProfileCurrency: 0,
feeInBaseCurrency: 0,
quantity: 10,
type: 'BUY',
unitPriceInAssetProfileCurrency: 110
},
{
...activityDummyData,
assetProfile: secondAssetProfile,
date: new Date('2021-11-30'),
feeInAssetProfileCurrency: 0,
feeInBaseCurrency: 0,
quantity: 10,
type: 'SELL',
unitPriceInAssetProfileCurrency: 110
}
];
const portfolioCalculator = portfolioCalculatorFactory.createCalculator({
activities,
calculationType: PerformanceCalculationType.ROI,
currency: 'CHF',
usePortfolioSnapshotCache: false,
userId: userDummyData.id
});
const portfolioSnapshot = await portfolioCalculator.computeSnapshot();
const performanceByDateRange = await getPerformanceByDateRange({
portfolioCalculator,
dateRanges: ['max']
});
expect(portfolioSnapshot.historicalData.at(-1)).toMatchObject(
expect.objectContaining({
netPerformance: 100,
netPerformanceWithCurrencyEffect: 100,
totalInvestment: 0,
totalInvestmentValueWithCurrencyEffect: 0
})
);
expect(
portfolioSnapshot.historicalData.at(-1).netPerformanceInPercentage
).toBeCloseTo(100 / 1100, 14);
expect(
portfolioSnapshot.historicalData.at(-1)
.netPerformanceInPercentageWithCurrencyEffect
).toBeCloseTo(100 / 1100, 14);
expect(performanceByDateRange.max.netPerformance).toBe(100);
expect(performanceByDateRange.max.netPerformanceWithCurrencyEffect).toBe(
100
);
expect(performanceByDateRange.max.netPerformanceInPercentage).toBeCloseTo(
100 / 1100,
14
);
expect(
performanceByDateRange.max.netPerformanceInPercentageWithCurrencyEffect
).toBeCloseTo(100 / 1100, 14);
});
it('combines the end-of-day investment increase with hidden same-day capital', async () => {
jest.useFakeTimers().setSystemTime(parseDate('2021-12-18').getTime());
const roundTripAssetProfile = {
...assetProfileDummyData,
currency: 'CHF',
dataSource: 'YAHOO' as const,
name: 'Bâloise Holding AG',
symbol: 'BALN.SW'
};
const remainingAssetProfile = {
...assetProfileDummyData,
currency: 'CHF',
dataSource: 'EOD_HISTORICAL_DATA' as const,
name: 'Bâloise Holding AG',
symbol: 'BALN.SW'
};
const activities: Activity[] = [
{
...activityDummyData,
assetProfile: roundTripAssetProfile,
date: new Date('2021-11-30'),
feeInAssetProfileCurrency: 0,
feeInBaseCurrency: 0,
quantity: 10,
type: 'BUY',
unitPriceInAssetProfileCurrency: 100
},
{
...activityDummyData,
assetProfile: roundTripAssetProfile,
date: new Date('2021-11-30'),
feeInAssetProfileCurrency: 0,
feeInBaseCurrency: 0,
quantity: 10,
type: 'SELL',
unitPriceInAssetProfileCurrency: 110
},
{
...activityDummyData,
assetProfile: remainingAssetProfile,
date: new Date('2021-11-30'),
feeInAssetProfileCurrency: 0,
feeInBaseCurrency: 0,
quantity: 9,
type: 'BUY',
unitPriceInAssetProfileCurrency: 100
}
];
const portfolioCalculator = portfolioCalculatorFactory.createCalculator({
activities,
calculationType: PerformanceCalculationType.ROI,
currency: 'CHF',
usePortfolioSnapshotCache: false,
userId: userDummyData.id
});
const portfolioSnapshot = await portfolioCalculator.computeSnapshot();
const performanceByDateRange = await getPerformanceByDateRange({
portfolioCalculator,
dateRanges: ['max']
});
expect(
portfolioSnapshot.calculationMetadata?.roi
?.investedCapitalAdjustmentsByDate['2021-11-30']
).toEqual({
investedCapital: 100,
investedCapitalWithCurrencyEffect: 100
});
const lastHistoricalDataItem = portfolioSnapshot.historicalData.at(-1);
expect(lastHistoricalDataItem).toMatchObject(
expect.objectContaining({
totalInvestment: 900,
totalInvestmentValueWithCurrencyEffect: 900
})
);
expect(lastHistoricalDataItem.netPerformanceInPercentage).toBeCloseTo(
lastHistoricalDataItem.netPerformance / 1000,
14
);
expect(
lastHistoricalDataItem.netPerformanceInPercentageWithCurrencyEffect
).toBeCloseTo(
lastHistoricalDataItem.netPerformanceWithCurrencyEffect / 1000,
14
);
expect(performanceByDateRange.max.netPerformance).toBe(
lastHistoricalDataItem.netPerformance
);
expect(performanceByDateRange.max.netPerformanceWithCurrencyEffect).toBe(
lastHistoricalDataItem.netPerformanceWithCurrencyEffect
);
expect(performanceByDateRange.max.netPerformanceInPercentage).toBeCloseTo(
lastHistoricalDataItem.netPerformance / 1000,
14
);
expect(
performanceByDateRange.max.netPerformanceInPercentageWithCurrencyEffect
).toBeCloseTo(
lastHistoricalDataItem.netPerformanceWithCurrencyEffect / 1000,
14
);
});
it('preserves same-day invested capital after a snapshot cache round-trip', async () => {
jest.useFakeTimers().setSystemTime(parseDate('2021-12-18').getTime());
const assetProfile = {
...assetProfileDummyData,
currency: 'CHF',
dataSource: 'YAHOO' as const,
name: 'Bâloise Holding AG',
symbol: 'BALN.SW'
};
const activities: Activity[] = [
{
...activityDummyData,
assetProfile,
date: new Date('2021-11-30'),
feeInAssetProfileCurrency: 0,
feeInBaseCurrency: 0,
quantity: 10,
type: 'BUY',
unitPriceInAssetProfileCurrency: 100
},
{
...activityDummyData,
assetProfile,
date: new Date('2021-11-30'),
feeInAssetProfileCurrency: 0,
feeInBaseCurrency: 0,
quantity: 10,
type: 'SELL',
unitPriceInAssetProfileCurrency: 110
}
];
const sourcePortfolioCalculator =
portfolioCalculatorFactory.createCalculator({
activities,
calculationType: PerformanceCalculationType.ROI,
currency: 'CHF',
usePortfolioSnapshotCache: false,
userId: userDummyData.id
});
const portfolioSnapshot = await sourcePortfolioCalculator.computeSnapshot();
expect(
portfolioSnapshot.calculationMetadata?.roi
?.investedCapitalAdjustmentsByDate['2021-11-30']
).toEqual({
investedCapital: 1000,
investedCapitalWithCurrencyEffect: 1000
});
expect(portfolioSnapshot.historicalData.at(-1)).not.toHaveProperty(
'investedCapitalAdjustment'
);
expect(portfolioSnapshot.historicalData.at(-1)).not.toHaveProperty(
'investedCapitalWithCurrencyEffectAdjustment'
);
expect(portfolioSnapshot.historicalData.at(-1)).not.toHaveProperty(
'calculationMetadata'
);
const portfolioSnapshotKey = RedisCacheServiceMock.getPortfolioSnapshotKey({
calculationType: PerformanceCalculationType.ROI,
userId: userDummyData.id
});
await RedisCacheServiceMock.set(
portfolioSnapshotKey,
JSON.stringify({
expiration: Date.now() + 60_000,
portfolioSnapshot
})
);
const cachedPortfolioCalculator =
portfolioCalculatorFactory.createCalculator({
activities,
calculationType: PerformanceCalculationType.ROI,
currency: 'CHF',
userId: userDummyData.id
});
const cachedSnapshot = await cachedPortfolioCalculator.getSnapshot();
expect(
cachedSnapshot.calculationMetadata?.roi?.investedCapitalAdjustmentsByDate[
'2021-11-30'
]
).toEqual({
investedCapital: 1000,
investedCapitalWithCurrencyEffect: 1000
});
const performanceByDateRange = await getPerformanceByDateRange({
portfolioCalculator: cachedPortfolioCalculator,
dateRanges: ['max']
});
expect(performanceByDateRange.max).toMatchObject({
netPerformance: 100,
netPerformanceInPercentage: 0.1,
netPerformanceInPercentageWithCurrencyEffect: 0.1,
netPerformanceWithCurrencyEffect: 100
});
expect(cachedSnapshot.historicalData.at(-1)).not.toHaveProperty(
'investedCapitalAdjustment'
);
expect(cachedSnapshot.historicalData.at(-1)).not.toHaveProperty(
'investedCapitalWithCurrencyEffectAdjustment'
);
expect(cachedSnapshot.historicalData.at(-1)).not.toHaveProperty(
'calculationMetadata'
);
});
});

283
apps/api/src/app/portfolio/calculator/roi/portfolio-calculator.ts

@ -4,6 +4,7 @@ import { HoldingPerformance } from '@ghostfolio/api/app/portfolio/interfaces/hol
import { InvestedCapital } from '@ghostfolio/api/app/portfolio/interfaces/invested-capital.interface';
import { PortfolioCalculatorHolding } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-calculator-holding.interface';
import { PerformancePercentages } from '@ghostfolio/api/app/portfolio/types/performance-percentages.type';
import { getAssetProfileIdentifier } from '@ghostfolio/common/helper';
import {
AssetProfileIdentifier,
HistoricalDataItem
@ -12,9 +13,16 @@ import { PortfolioSnapshot } from '@ghostfolio/common/models';
import { DateRange } from '@ghostfolio/common/types';
import { PerformanceCalculationType } from '@ghostfolio/common/types/performance-calculation-type.type';
import { AssetSubClass } from '@prisma/client';
import { Big } from 'big.js';
import { mapValues, sortedLastIndex } from 'lodash-es';
interface TransactionInvestment {
date: string;
transactionInvestment: Big;
transactionInvestmentWithCurrencyEffect: Big;
}
/**
* Return on Investment (ROI): the gain divided by the invested capital, without
* time weighting.
@ -36,6 +44,10 @@ import { mapValues, sortedLastIndex } from 'lodash-es';
* another on different dates counts two times.
*/
export class RoiPortfolioCalculator extends PortfolioCalculator {
private transactionInvestmentsByAssetProfileIdentifier: {
[assetProfileIdentifier: string]: TransactionInvestment[];
} = {};
protected calculateOverallPerformance({
accumulatedValuesByDate,
positions
@ -43,20 +55,61 @@ export class RoiPortfolioCalculator extends PortfolioCalculator {
accumulatedValuesByDate: { [date: string]: AccumulatedValues };
positions: PortfolioCalculatorHolding[];
}): PortfolioSnapshot {
const investedCapitalByDate = this.getInvestedCapitalByDate({
accumulatedValuesByDate
});
// The invested capital of the portfolio at the last date
const { investedCapital, investedCapitalWithCurrencyEffect } =
Object.values(
this.getInvestedCapitalByDate({ accumulatedValuesByDate })
).at(-1) ?? {
Object.values(investedCapitalByDate).at(-1) ?? {
investedCapital: new Big(0),
investedCapitalWithCurrencyEffect: new Big(0)
};
return this.getOverallPerformance({
investedCapital,
investedCapitalWithCurrencyEffect,
positions
});
const investedCapitalAdjustmentsByDate = Object.fromEntries(
Object.entries(investedCapitalByDate)
.filter(([, item]) => {
return (
!item.investedCapitalAdjustment.eq(0) ||
!item.investedCapitalWithCurrencyEffectAdjustment.eq(0)
);
})
.map(
([
date,
{
investedCapitalAdjustment,
investedCapitalWithCurrencyEffectAdjustment
}
]) => {
return [
date,
{
investedCapital: investedCapitalAdjustment.toNumber(),
investedCapitalWithCurrencyEffect:
investedCapitalWithCurrencyEffectAdjustment.toNumber()
}
];
}
)
);
return {
...this.getOverallPerformance({
investedCapital,
investedCapitalWithCurrencyEffect,
positions
}),
...(Object.keys(investedCapitalAdjustmentsByDate).length > 0
? {
calculationMetadata: {
roi: {
investedCapitalAdjustmentsByDate
}
}
}
: {})
};
}
protected calculatePerformancePercentages({
@ -69,9 +122,13 @@ export class RoiPortfolioCalculator extends PortfolioCalculator {
});
return mapValues(accumulatedValuesByDate, (accumulatedValues, date) => {
const { investedCapital, investedCapitalWithCurrencyEffect } =
investedCapitalByDate[date];
return this.getPerformancePercentagesOfAccumulatedValues({
accumulatedValues,
...investedCapitalByDate[date]
investedCapital,
investedCapitalWithCurrencyEffect
});
});
}
@ -84,6 +141,10 @@ export class RoiPortfolioCalculator extends PortfolioCalculator {
let investedCapital = 0;
let investedCapitalWithCurrencyEffect = 0;
const investedCapitalAdjustmentsByDate =
this.getCurrentSnapshot().calculationMetadata?.roi
?.investedCapitalAdjustmentsByDate ?? {};
const performancePercentagesByDate: {
[date: string]: PerformancePercentages;
} = {};
@ -115,6 +176,17 @@ export class RoiPortfolioCalculator extends PortfolioCalculator {
investedCapitalWithCurrencyEffect +=
investmentChangeWithCurrencyEffect;
}
// End-of-day investment values cannot expose capital which was both
// invested and released within the same day. The snapshot stores only
// this additional intraday amount, so the existing date-range
// semantics stay unchanged.
const investedCapitalAdjustment =
investedCapitalAdjustmentsByDate[historicalDataItem.date];
investedCapital += investedCapitalAdjustment?.investedCapital ?? 0;
investedCapitalWithCurrencyEffect +=
investedCapitalAdjustment?.investedCapitalWithCurrencyEffect ?? 0;
}
performancePercentagesByDate[historicalDataItem.date] =
@ -145,6 +217,15 @@ export class RoiPortfolioCalculator extends PortfolioCalculator {
};
start: Date;
} & AssetProfileIdentifier): HoldingPerformance {
const assetProfileIdentifier = getAssetProfileIdentifier({
dataSource,
symbol
});
delete this.transactionInvestmentsByAssetProfileIdentifier[
assetProfileIdentifier
];
const { holdingPerformance, valuation } =
this.getMethodIndependentHoldingPerformance({
chartDates,
@ -161,6 +242,7 @@ export class RoiPortfolioCalculator extends PortfolioCalculator {
}
const {
activities,
currentValuesWithCurrencyEffect,
dateRanges,
daysInMarket,
@ -169,6 +251,29 @@ export class RoiPortfolioCalculator extends PortfolioCalculator {
items
} = valuation;
const transactionInvestments: TransactionInvestment[] = [];
for (const [index, activity] of activities.entries()) {
if (
activity.itemType ||
!['BUY', 'SELL'].includes(activity.type) ||
!items[index]
) {
continue;
}
transactionInvestments.push({
date: activity.date,
transactionInvestment: items[index].transactionInvestment,
transactionInvestmentWithCurrencyEffect:
items[index].transactionInvestmentWithCurrencyEffect
});
}
this.transactionInvestmentsByAssetProfileIdentifier[
assetProfileIdentifier
] = transactionInvestments;
let investedCapital = new Big(0);
let investedCapitalWithCurrencyEffect = new Big(0);
@ -244,9 +349,141 @@ export class RoiPortfolioCalculator extends PortfolioCalculator {
return PerformanceCalculationType.ROI;
}
/**
* Returns the invested capital which is hidden by end-of-day aggregation.
*
* The existing ROI calculation uses positive changes of the end-of-day
* remaining cost basis. For each day, this method replays the already
* calculated transaction investment changes in portfolio activity order and
* returns only the part of the intraday peak which is above both the opening
* and closing cost basis.
*/
private getIntradayInvestedCapitalAdjustmentsByDate() {
const adjustmentsByDate: { [date: string]: InvestedCapital } = {};
const transactionIndexesByAssetProfileIdentifier: {
[assetProfileIdentifier: string]: number;
} = {};
let currentDate: string;
let currentInvestment = new Big(0);
let currentInvestmentWithCurrencyEffect = new Big(0);
let openingInvestment = new Big(0);
let openingInvestmentWithCurrencyEffect = new Big(0);
let peakInvestment = new Big(0);
let peakInvestmentWithCurrencyEffect = new Big(0);
const finalizeDate = () => {
if (!currentDate) {
return;
}
const referenceInvestment = openingInvestment.gt(currentInvestment)
? openingInvestment
: currentInvestment;
const referenceInvestmentWithCurrencyEffect =
openingInvestmentWithCurrencyEffect.gt(
currentInvestmentWithCurrencyEffect
)
? openingInvestmentWithCurrencyEffect
: currentInvestmentWithCurrencyEffect;
const investedCapital = peakInvestment.minus(referenceInvestment);
const investedCapitalWithCurrencyEffect =
peakInvestmentWithCurrencyEffect.minus(
referenceInvestmentWithCurrencyEffect
);
adjustmentsByDate[currentDate] = {
investedCapital: investedCapital.gt(0) ? investedCapital : new Big(0),
investedCapitalWithCurrencyEffect: investedCapitalWithCurrencyEffect.gt(
0
)
? investedCapitalWithCurrencyEffect
: new Big(0)
};
};
const baseCurrency = this.getBaseCurrency();
for (const activity of this.activities) {
if (!['BUY', 'SELL'].includes(activity.type)) {
continue;
}
// Base-currency cash is excluded from the portfolio performance
// calculation and therefore must not affect the ROI invested capital.
if (
activity.assetProfile.assetSubClass === AssetSubClass.CASH &&
activity.assetProfile.currency === baseCurrency &&
activity.assetProfile.symbol === baseCurrency
) {
continue;
}
const assetProfileIdentifier = getAssetProfileIdentifier(
activity.assetProfile
);
const transactionInvestments =
this.transactionInvestmentsByAssetProfileIdentifier[
assetProfileIdentifier
];
const transactionIndex =
transactionIndexesByAssetProfileIdentifier[assetProfileIdentifier] ?? 0;
const transactionInvestment = transactionInvestments?.[transactionIndex];
// If valuation was not available for any activity, keep the previous
// end-of-day behavior rather than deriving a partial intraday result.
if (transactionInvestment?.date !== activity.date) {
return {};
}
transactionIndexesByAssetProfileIdentifier[assetProfileIdentifier] =
transactionIndex + 1;
if (currentDate !== activity.date) {
finalizeDate();
currentDate = activity.date;
openingInvestment = currentInvestment;
openingInvestmentWithCurrencyEffect =
currentInvestmentWithCurrencyEffect;
peakInvestment = currentInvestment;
peakInvestmentWithCurrencyEffect = currentInvestmentWithCurrencyEffect;
}
currentInvestment = currentInvestment.plus(
transactionInvestment.transactionInvestment
);
currentInvestmentWithCurrencyEffect =
currentInvestmentWithCurrencyEffect.plus(
transactionInvestment.transactionInvestmentWithCurrencyEffect
);
if (currentInvestment.gt(peakInvestment)) {
peakInvestment = currentInvestment;
}
if (
currentInvestmentWithCurrencyEffect.gt(peakInvestmentWithCurrencyEffect)
) {
peakInvestmentWithCurrencyEffect = currentInvestmentWithCurrencyEffect;
}
}
finalizeDate();
return adjustmentsByDate;
}
/**
* Returns the invested capital of the portfolio per date: the sum of the
* positive net investment changes up to the date
* positive net investment changes up to the date plus capital which is
* invested and released within a single day.
*/
private getInvestedCapitalByDate({
accumulatedValuesByDate
@ -258,7 +495,15 @@ export class RoiPortfolioCalculator extends PortfolioCalculator {
let previousTotalInvestmentValue = new Big(0);
let previousTotalInvestmentValueWithCurrencyEffect = new Big(0);
const investedCapitalByDate: { [date: string]: InvestedCapital } = {};
const intradayInvestedCapitalAdjustmentsByDate =
this.getIntradayInvestedCapitalAdjustmentsByDate();
const investedCapitalByDate: {
[date: string]: InvestedCapital & {
investedCapitalAdjustment: Big;
investedCapitalWithCurrencyEffectAdjustment: Big;
};
} = {};
// The dates are in chronological order
for (const [
@ -290,12 +535,26 @@ export class RoiPortfolioCalculator extends PortfolioCalculator {
previousTotalInvestmentValue = totalInvestmentValue;
const {
investedCapital: investedCapitalAdjustment = new Big(0),
investedCapitalWithCurrencyEffect:
investedCapitalWithCurrencyEffectAdjustment = new Big(0)
} = intradayInvestedCapitalAdjustmentsByDate[date] ?? {};
investedCapital = investedCapital.plus(investedCapitalAdjustment);
investedCapitalWithCurrencyEffect =
investedCapitalWithCurrencyEffect.plus(
investedCapitalWithCurrencyEffectAdjustment
);
previousTotalInvestmentValueWithCurrencyEffect =
totalInvestmentValueWithCurrencyEffect;
investedCapitalByDate[date] = {
investedCapital,
investedCapitalWithCurrencyEffect
investedCapitalAdjustment,
investedCapitalWithCurrencyEffect,
investedCapitalWithCurrencyEffectAdjustment
};
}

11
libs/common/src/lib/models/portfolio-snapshot.ts

@ -31,6 +31,17 @@ export class PortfolioSnapshot {
historicalData: HistoricalDataItem[];
calculationMetadata?: {
roi?: {
investedCapitalAdjustmentsByDate: {
[date: string]: {
investedCapital: number;
investedCapitalWithCurrencyEffect: number;
};
};
};
};
@Type(() => PortfolioSnapshotHolding)
positions: PortfolioSnapshotHolding[];

Loading…
Cancel
Save