diff --git a/CHANGELOG.md b/CHANGELOG.md index 07dec9f69..488d1f116 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fixed the cash positions being included in the by continent, by country and by sector charts on the allocations page and the public page - Fixed the allocations in percentage exceeding 100% in the restricted view +- Fixed the portfolio calculation for holdings with activities before the first known historical market price by falling back to the unit price of the activity ## 3.64.0 - 2026-08-30 diff --git a/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator-btcusd-buy-before-first-market-price.spec.ts b/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator-btcusd-buy-before-first-market-price.spec.ts new file mode 100644 index 000000000..cebb3de94 --- /dev/null +++ b/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator-btcusd-buy-before-first-market-price.spec.ts @@ -0,0 +1,160 @@ +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 { 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'; + +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', () => { + 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, 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 + ); + }); + + describe('get current positions', () => { + it('with BTCUSD buy before the first known market price', async () => { + jest.useFakeTimers().setSystemTime(parseDate('2022-01-14').getTime()); + + const activities: Activity[] = [ + { + ...activityDummyData, + assetProfile: { + ...assetProfileDummyData, + currency: 'USD', + dataSource: 'YAHOO', + name: 'Bitcoin', + symbol: 'BTCUSD' + }, + date: parseDate('2014-06-01'), + feeInAssetProfileCurrency: 0, + feeInBaseCurrency: 0, + quantity: 1, + type: 'BUY', + unitPriceInAssetProfileCurrency: 500 + } + ]; + + const portfolioCalculator = portfolioCalculatorFactory.createCalculator({ + activities, + calculationType: PerformanceCalculationType.ROAI, + currency: 'USD', + userId: userDummyData.id + }); + + const portfolioSnapshot = await portfolioCalculator.computeSnapshot(); + + const historicalDataByDate = Object.fromEntries( + portfolioSnapshot.historicalData.map((historicalDataItem) => { + return [historicalDataItem.date, historicalDataItem]; + }) + ); + + /** + * The first known market price of BTCUSD is on 2015-01-01. The chart + * dates before it must not be valued with a future price, hence they use + * the unit price of the activity: 500 + */ + expect(historicalDataByDate['2014-06-01']).toMatchObject({ + netPerformance: 0, // 1 * (500 - 500) = 0 + netPerformanceInPercentage: 0, + totalInvestment: 500, + value: 500 // 1 * 500 = 500 + }); + + expect(historicalDataByDate['2014-12-31']).toMatchObject({ + netPerformance: 0, // 1 * (500 - 500) = 0 + netPerformanceInPercentage: 0, + totalInvestment: 500, + value: 500 // 1 * 500 = 500 + }); + + /** + * Closing price on 2015-01-01: 314.25 + */ + expect(historicalDataByDate['2015-01-01']).toMatchObject({ + netPerformance: -185.75, // 1 * (314.25 - 500) = -185.75 + netPerformanceInPercentage: -0.3715, // -185.75 ÷ 500 = -0.3715 + totalInvestment: 500, + value: 314.25 // 1 * 314.25 = 314.25 + }); + + /** + * Closing price on 2022-01-14: 43099.7 + */ + expect(portfolioSnapshot.historicalData.at(-1)).toMatchObject({ + date: '2022-01-14', + netPerformance: 42599.7, // 1 * (43099.7 - 500) = 42599.7 + totalInvestment: 500, + value: 43099.7 // 1 * 43099.7 = 43099.7 + }); + }); + }); +}); diff --git a/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator-manual-buy-before-first-market-price.spec.ts b/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator-manual-buy-before-first-market-price.spec.ts new file mode 100644 index 000000000..70b401627 --- /dev/null +++ b/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator-manual-buy-before-first-market-price.spec.ts @@ -0,0 +1,151 @@ +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 { 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'; + +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', () => { + 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, 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 + ); + }); + + describe('get current positions', () => { + it('with MANUAL buy before the first known market price', async () => { + jest.useFakeTimers().setSystemTime(parseDate('2022-01-31').getTime()); + + const activities: Activity[] = [ + { + ...activityDummyData, + assetProfile: { + ...assetProfileDummyData, + currency: 'USD', + dataSource: 'MANUAL', + name: 'Private Investment', + symbol: '55196015-1365-4560-aa60-8751ae6d18f8' + }, + date: parseDate('2021-01-01'), + feeInAssetProfileCurrency: 0, + feeInBaseCurrency: 0, + quantity: 1, + type: 'BUY', + unitPriceInAssetProfileCurrency: 100 + } + ]; + + const portfolioCalculator = portfolioCalculatorFactory.createCalculator({ + activities, + calculationType: PerformanceCalculationType.ROAI, + currency: 'USD', + userId: userDummyData.id + }); + + const portfolioSnapshot = await portfolioCalculator.computeSnapshot(); + + const historicalDataByDate = Object.fromEntries( + portfolioSnapshot.historicalData.map((historicalDataItem) => { + return [historicalDataItem.date, historicalDataItem]; + }) + ); + + /** + * The only known market price is on 2022-01-31. The chart dates before it + * must not be valued with a future price, hence they use the unit price + * of the activity: 100 + */ + expect(historicalDataByDate['2021-01-01']).toMatchObject({ + netPerformance: 0, // 1 * (100 - 100) = 0 + netPerformanceInPercentage: 0, + totalInvestment: 100, + value: 100 // 1 * 100 = 100 + }); + + expect(historicalDataByDate['2022-01-30']).toMatchObject({ + netPerformance: 0, // 1 * (100 - 100) = 0 + netPerformanceInPercentage: 0, + totalInvestment: 100, + value: 100 // 1 * 100 = 100 + }); + + /** + * Closing price on 2022-01-31: 3000 + */ + expect(portfolioSnapshot.historicalData.at(-1)).toMatchObject({ + date: '2022-01-31', + netPerformance: 2900, // 1 * (3000 - 100) = 2900 + netPerformanceInPercentage: 29, // 2900 ÷ 100 = 29 + totalInvestment: 100, + value: 3000 // 1 * 3000 = 3000 + }); + }); + }); +}); diff --git a/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator-novn-buy-and-sell.spec.ts b/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator-novn-buy-and-sell.spec.ts index 364d173e1..f491b5025 100644 --- a/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator-novn-buy-and-sell.spec.ts +++ b/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator-novn-buy-and-sell.spec.ts @@ -153,22 +153,22 @@ describe('PortfolioCalculator', () => { }); /** - * Closing price on 2022-03-07 is unknown, - * hence it uses the last unit price (2022-04-11): 87.8 + * Closing price on 2022-03-07 is unknown and there is no earlier market + * price, hence it uses the unit price of the activity: 75.8 */ expect(portfolioSnapshot.historicalData[1]).toEqual({ date: '2022-03-07', investmentValueWithCurrencyEffect: 151.6, - netPerformance: 24, // 2 * (87.8 - 75.8) = 24 - netPerformanceInPercentage: 0.158311345646438, // 24 ÷ 151.6 = 0.158311345646438 - netPerformanceInPercentageWithCurrencyEffect: 0.158311345646438, // 24 ÷ 151.6 = 0.158311345646438 - netPerformanceWithCurrencyEffect: 24, - netWorth: 175.6, // 2 * 87.8 = 175.6 + netPerformance: 0, // 2 * (75.8 - 75.8) = 0 + netPerformanceInPercentage: 0, // 0 ÷ 151.6 = 0 + netPerformanceInPercentageWithCurrencyEffect: 0, // 0 ÷ 151.6 = 0 + netPerformanceWithCurrencyEffect: 0, + netWorth: 151.6, // 2 * 75.8 = 151.6 totalCashInBaseCurrency: 0, totalInvestment: 151.6, totalInvestmentValueWithCurrencyEffect: 151.6, - value: 175.6, // 2 * 87.8 = 175.6 - valueWithCurrencyEffect: 175.6 + value: 151.6, // 2 * 75.8 = 151.6 + valueWithCurrencyEffect: 151.6 }); expect( diff --git a/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator.ts b/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator.ts index ed9c264c1..51a7e8068 100644 --- a/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator.ts +++ b/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator.ts @@ -381,9 +381,10 @@ export class RoaiPortfolioCalculator extends PortfolioCalculator { unitPrice: unitPriceAtEndDate }); - // Fall back to the unit price at the end date for the chart dates before - // the first known market price of the symbol - let lastUnitPrice = unitPriceAtEndDate; + // Fall back to the unit price of the most recent BUY / SELL activity for + // the chart dates before the first known market price of the symbol + let lastActivityUnitPrice: Big | undefined; + let lastMarketPrice: Big | undefined; const ordersByDate: { [date: string]: PortfolioOrderItem[] } = {}; @@ -403,11 +404,26 @@ export class RoaiPortfolioCalculator extends PortfolioCalculator { break; } + const ordersOfDate = ordersByDate[dateString]; + + if (!lastMarketPrice && ordersOfDate?.length > 0) { + for (const { itemType, type, unitPrice } of ordersOfDate) { + if (!itemType && ['BUY', 'SELL'].includes(type)) { + lastActivityUnitPrice = unitPrice; + } + } + } + + const marketPrice = marketSymbolMap[dateString]?.[assetProfileIdentifier]; + const unitPrice = - marketSymbolMap[dateString]?.[assetProfileIdentifier] ?? lastUnitPrice; + marketPrice ?? + lastMarketPrice ?? + lastActivityUnitPrice ?? + unitPriceAtEndDate; - if (ordersByDate[dateString]?.length > 0) { - for (const order of ordersByDate[dateString]) { + if (ordersOfDate?.length > 0) { + for (const order of ordersOfDate) { order.unitPriceFromMarketData = unitPrice; } } else if (dateString >= dateStringOfFirstActivity) { @@ -423,7 +439,9 @@ export class RoaiPortfolioCalculator extends PortfolioCalculator { }); } - lastUnitPrice = unitPrice; + if (marketPrice) { + lastMarketPrice = marketPrice; + } } // Sort orders so that the start and end placeholder order are at the correct