Skip to content

Open Source Wealth Management Software. Angular + NestJS + Prisma + Nx + TypeScript 🤍

Feature/integrate dividend into transaction point concept (#3092)

Thomas Kaul07661d9262a6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1dce287c13..5da3b143bc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## Unreleased
+
+### Changed
+
+- Integrated dividend into the transaction point concept in the portfolio service
+
## 2.61.1 - 2024-03-06
### Fixed
diff --git a/apps/api/jest.config.ts b/apps/api/jest.config.ts
index 8152c3f2a3..b87f91a791 100644
--- a/apps/api/jest.config.ts
+++ b/apps/api/jest.config.ts
@@ -13,7 +13,6 @@ export default {
},
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: '../../coverage/apps/api',
- testTimeout: 10000,
testEnvironment: 'node',
preset: '../../jest.preset.js'
};
diff --git a/apps/api/src/app/order/order.service.ts b/apps/api/src/app/order/order.service.ts
index d200ee024c..c97243929d 100644
--- a/apps/api/src/app/order/order.service.ts
+++ b/apps/api/src/app/order/order.service.ts
@@ -340,11 +340,13 @@ export class OrderService {
return {
...order,
value,
+ // TODO: Use exchange rate of date
feeInBaseCurrency: this.exchangeRateDataService.toCurrency(
order.fee,
order.SymbolProfile.currency,
userCurrency
),
+ // TODO: Use exchange rate of date
valueInBaseCurrency: this.exchangeRateDataService.toCurrency(
value,
order.SymbolProfile.currency,
diff --git a/apps/api/src/app/portfolio/current-rate.service.mock.ts b/apps/api/src/app/portfolio/current-rate.service.mock.ts
index 76e7aae09c..8f8d061120 100644
--- a/apps/api/src/app/portfolio/current-rate.service.mock.ts
+++ b/apps/api/src/app/portfolio/current-rate.service.mock.ts
@@ -43,6 +43,15 @@ function mockGetValue(symbol: string, date: Date) {
return { marketPrice: 0 };
+ case 'MSFT':
+ if (isSameDay(parseDate('2021-09-16'), date)) {
+ return { marketPrice: 89.12 };
+ } else if (isSameDay(parseDate('2023-07-10'), date)) {
+ return { marketPrice: 331.83 };
+ }
+
+ return { marketPrice: 0 };
+
case 'NOVN.SW':
if (isSameDay(parseDate('2022-04-11'), date)) {
return { marketPrice: 87.8 };
diff --git a/apps/api/src/app/portfolio/interfaces/transaction-point-symbol.interface.ts b/apps/api/src/app/portfolio/interfaces/transaction-point-symbol.interface.ts
index 5350adccce..fb2f0a389c 100644
--- a/apps/api/src/app/portfolio/interfaces/transaction-point-symbol.interface.ts
+++ b/apps/api/src/app/portfolio/interfaces/transaction-point-symbol.interface.ts
@@ -2,8 +2,10 @@ import { DataSource, Tag } from '@prisma/client';
import Big from 'big.js';
export interface TransactionPointSymbol {
+ averagePrice: Big;
currency: string;
dataSource: DataSource;
+ dividend: Big;
fee: Big;
firstBuyDate: string;
investment: Big;
diff --git a/apps/api/src/app/portfolio/portfolio-calculator-baln-buy-and-sell.spec.ts b/apps/api/src/app/portfolio/portfolio-calculator-baln-buy-and-sell.spec.ts
index d81393719e..9831e5b009 100644
--- a/apps/api/src/app/portfolio/portfolio-calculator-baln-buy-and-sell.spec.ts
+++ b/apps/api/src/app/portfolio/portfolio-calculator-baln-buy-and-sell.spec.ts
@@ -107,6 +107,8 @@ describe('PortfolioCalculator', () => {
averagePrice: new Big('0'),
currency: 'CHF',
dataSource: 'YAHOO',
+ dividend: new Big('0'),
+ dividendInBaseCurrency: new Big('0'),
fee: new Big('3.2'),
firstBuyDate: '2021-11-22',
grossPerformance: new Big('-12.6'),
diff --git a/apps/api/src/app/portfolio/portfolio-calculator-baln-buy.spec.ts b/apps/api/src/app/portfolio/portfolio-calculator-baln-buy.spec.ts
index e77335ab8a..bb59860598 100644
--- a/apps/api/src/app/portfolio/portfolio-calculator-baln-buy.spec.ts
+++ b/apps/api/src/app/portfolio/portfolio-calculator-baln-buy.spec.ts
@@ -96,6 +96,8 @@ describe('PortfolioCalculator', () => {
averagePrice: new Big('136.6'),
currency: 'CHF',
dataSource: 'YAHOO',
+ dividend: new Big('0'),
+ dividendInBaseCurrency: new Big('0'),
fee: new Big('1.55'),
firstBuyDate: '2021-11-30',
grossPerformance: new Big('24.6'),
diff --git a/apps/api/src/app/portfolio/portfolio-calculator-btcusd-buy-and-sell-partially.spec.ts b/apps/api/src/app/portfolio/portfolio-calculator-btcusd-buy-and-sell-partially.spec.ts
index 8f55739284..6126311c31 100644
--- a/apps/api/src/app/portfolio/portfolio-calculator-btcusd-buy-and-sell-partially.spec.ts
+++ b/apps/api/src/app/portfolio/portfolio-calculator-btcusd-buy-and-sell-partially.spec.ts
@@ -120,6 +120,8 @@ describe('PortfolioCalculator', () => {
averagePrice: new Big('320.43'),
currency: 'USD',
dataSource: 'YAHOO',
+ dividend: new Big('0'),
+ dividendInBaseCurrency: new Big('0'),
fee: new Big('0'),
firstBuyDate: '2015-01-01',
grossPerformance: new Big('27172.74'),
diff --git a/apps/api/src/app/portfolio/portfolio-calculator-googl-buy.spec.ts b/apps/api/src/app/portfolio/portfolio-calculator-googl-buy.spec.ts
index 5022483887..d294982925 100644
--- a/apps/api/src/app/portfolio/portfolio-calculator-googl-buy.spec.ts
+++ b/apps/api/src/app/portfolio/portfolio-calculator-googl-buy.spec.ts
@@ -109,6 +109,8 @@ describe('PortfolioCalculator', () => {
averagePrice: new Big('89.12'),
currency: 'USD',
dataSource: 'YAHOO',
+ dividend: new Big('0'),
+ dividendInBaseCurrency: new Big('0'),
fee: new Big('1'),
firstBuyDate: '2023-01-03',
grossPerformance: new Big('27.33'),
diff --git a/apps/api/src/app/portfolio/portfolio-calculator-msft-buy-with-dividend.spec.ts b/apps/api/src/app/portfolio/portfolio-calculator-msft-buy-with-dividend.spec.ts
new file mode 100644
index 0000000000..de63bced1f
--- /dev/null
+++ b/apps/api/src/app/portfolio/portfolio-calculator-msft-buy-with-dividend.spec.ts
@@ -0,0 +1,118 @@
+import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service';
+import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service';
+import { ExchangeRateDataServiceMock } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service.mock';
+import { parseDate } from '@ghostfolio/common/helper';
+
+import Big from 'big.js';
+
+import { CurrentRateServiceMock } from './current-rate.service.mock';
+import { PortfolioCalculator } from './portfolio-calculator';
+
+jest.mock('@ghostfolio/api/app/portfolio/current-rate.service', () => {
+ return {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ CurrentRateService: jest.fn().mockImplementation(() => {
+ return CurrentRateServiceMock;
+ })
+ };
+});
+
+jest.mock(
+ '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service',
+ () => {
+ return {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ ExchangeRateDataService: jest.fn().mockImplementation(() => {
+ return ExchangeRateDataServiceMock;
+ })
+ };
+ }
+);
+
+describe('PortfolioCalculator', () => {
+ let currentRateService: CurrentRateService;
+ let exchangeRateDataService: ExchangeRateDataService;
+
+ beforeEach(() => {
+ currentRateService = new CurrentRateService(null, null, null, null);
+
+ exchangeRateDataService = new ExchangeRateDataService(
+ null,
+ null,
+ null,
+ null
+ );
+ });
+
+ describe('get current positions', () => {
+ it.only('with MSFT buy', async () => {
+ const portfolioCalculator = new PortfolioCalculator({
+ currentRateService,
+ exchangeRateDataService,
+ currency: 'USD',
+ orders: [
+ {
+ currency: 'USD',
+ date: '2021-09-16',
+ dataSource: 'YAHOO',
+ fee: new Big(19),
+ name: 'Microsoft Inc.',
+ quantity: new Big(1),
+ symbol: 'MSFT',
+ type: 'BUY',
+ unitPrice: new Big(298.58)
+ },
+ {
+ currency: 'USD',
+ date: '2021-11-16',
+ dataSource: 'YAHOO',
+ fee: new Big(0),
+ name: 'Microsoft Inc.',
+ quantity: new Big(1),
+ symbol: 'MSFT',
+ type: 'DIVIDEND',
+ unitPrice: new Big(0.62)
+ }
+ ]
+ });
+
+ portfolioCalculator.computeTransactionPoints();
+
+ const spy = jest
+ .spyOn(Date, 'now')
+ .mockImplementation(() => parseDate('2023-07-10').getTime());
+
+ const currentPositions = await portfolioCalculator.getCurrentPositions(
+ parseDate('2023-07-10')
+ );
+
+ spy.mockRestore();
+
+ expect(currentPositions).toMatchObject({
+ errors: [],
+ hasErrors: false,
+ positions: [
+ {
+ averagePrice: new Big('298.58'),
+ currency: 'USD',
+ dataSource: 'YAHOO',
+ dividend: new Big('0.62'),
+ dividendInBaseCurrency: new Big('0.62'),
+ fee: new Big('19'),
+ firstBuyDate: '2021-09-16',
+ investment: new Big('298.58'),
+ investmentWithCurrencyEffect: new Big('298.58'),
+ marketPrice: 331.83,
+ marketPriceInBaseCurrency: 331.83,
+ quantity: new Big('1'),
+ symbol: 'MSFT',
+ tags: undefined,
+ transactionCount: 2
+ }
+ ],
+ totalInvestment: new Big('298.58'),
+ totalInvestmentWithCurrencyEffect: new Big('298.58')
+ });
+ });
+ });
+});
diff --git a/apps/api/src/app/portfolio/portfolio-calculator-novn-buy-and-sell-partially.spec.ts b/apps/api/src/app/portfolio/portfolio-calculator-novn-buy-and-sell-partially.spec.ts
index c46fd54d25..afddc54231 100644
--- a/apps/api/src/app/portfolio/portfolio-calculator-novn-buy-and-sell-partially.spec.ts
+++ b/apps/api/src/app/portfolio/portfolio-calculator-novn-buy-and-sell-partially.spec.ts
@@ -107,6 +107,8 @@ describe('PortfolioCalculator', () => {
averagePrice: new Big('75.80'),
currency: 'CHF',
dataSource: 'YAHOO',
+ dividend: new Big('0'),
+ dividendInBaseCurrency: new Big('0'),
fee: new Big('4.25'),
firstBuyDate: '2022-03-07',
grossPerformance: new Big('21.93'),
diff --git a/apps/api/src/app/portfolio/portfolio-calculator-novn-buy-and-sell.spec.ts b/apps/api/src/app/portfolio/portfolio-calculator-novn-buy-and-sell.spec.ts
index fa3ebac9b1..4b7750a634 100644
--- a/apps/api/src/app/portfolio/portfolio-calculator-novn-buy-and-sell.spec.ts
+++ b/apps/api/src/app/portfolio/portfolio-calculator-novn-buy-and-sell.spec.ts
@@ -133,6 +133,8 @@ describe('PortfolioCalculator', () => {
averagePrice: new Big('0'),
currency: 'CHF',
dataSource: 'YAHOO',
+ dividend: new Big('0'),
+ dividendInBaseCurrency: new Big('0'),
fee: new Big('0'),
firstBuyDate: '2022-03-07',
grossPerformance: new Big('19.86'),
diff --git a/apps/api/src/app/portfolio/portfolio-calculator.ts b/apps/api/src/app/portfolio/portfolio-calculator.ts
index 27a5a278b7..f0551f3b82 100644
--- a/apps/api/src/app/portfolio/portfolio-calculator.ts
+++ b/apps/api/src/app/portfolio/portfolio-calculator.ts
@@ -70,6 +70,7 @@ export class PortfolioCalculator {
let lastDate: string = null;
let lastTransactionPoint: TransactionPoint = null;
+
for (const order of this.orders) {
const currentDate = order.date;
@@ -77,33 +78,32 @@ export class PortfolioCalculator {
const oldAccumulatedSymbol = symbols[order.symbol];
const factor = getFactor(order.type);
- const unitPrice = new Big(order.unitPrice);
+
if (oldAccumulatedSymbol) {
+ let investment = oldAccumulatedSymbol.investment;
+
const newQuantity = order.quantity
.mul(factor)
.plus(oldAccumulatedSymbol.quantity);
- let investment = new Big(0);
-
- if (newQuantity.gt(0)) {
- if (order.type === 'BUY') {
- investment = oldAccumulatedSymbol.investment.plus(
- order.quantity.mul(unitPrice)
- );
- } else if (order.type === 'SELL') {
- const averagePrice = oldAccumulatedSymbol.investment.div(
- oldAccumulatedSymbol.quantity
- );
- investment = oldAccumulatedSymbol.investment.minus(
- order.quantity.mul(averagePrice)
- );
- }
+ if (order.type === 'BUY') {
+ investment = oldAccumulatedSymbol.investment.plus(
+ order.quantity.mul(order.unitPrice)
+ );
+ } else if (order.type === 'SELL') {
+ investment = oldAccumulatedSymbol.investment.minus(
+ order.quantity.mul(oldAccumulatedSymbol.averagePrice)
+ );
}
currentTransactionPointItem = {
investment,
+ averagePrice: newQuantity.gt(0)
+ ? investment.div(newQuantity)
+ : new Big(0),
currency: order.currency,
dataSource: order.dataSource,
+ dividend: new Big(0),
fee: order.fee.plus(oldAccumulatedSymbol.fee),
firstBuyDate: oldAccumulatedSymbol.firstBuyDate,
quantity: newQuantity,
@@ -113,11 +113,13 @@ export class PortfolioCalculator {
};
} else {
currentTransactionPointItem = {
+ averagePrice: order.unitPrice,
currency: order.currency,
dataSource: order.dataSource,
+ dividend: new Big(0),
fee: order.fee,
firstBuyDate: order.date,
- investment: unitPrice.mul(order.quantity).mul(factor),
+ investment: order.unitPrice.mul(order.quantity).mul(factor),
quantity: order.quantity.mul(factor),
symbol: order.symbol,
tags: order.tags,
@@ -128,22 +130,28 @@ export class PortfolioCalculator {
symbols[order.symbol] = currentTransactionPointItem;
const items = lastTransactionPoint?.items ?? [];
+
const newItems = items.filter(
(transactionPointItem) => transactionPointItem.symbol !== order.symbol
);
+
newItems.push(currentTransactionPointItem);
+
newItems.sort((a, b) => {
return a.symbol?.localeCompare(b.symbol);
});
+
if (lastDate !== currentDate || lastTransactionPoint === null) {
lastTransactionPoint = {
date: currentDate,
items: newItems
};
+
this.transactionPoints.push(lastTransactionPoint);
} else {
lastTransactionPoint.items = newItems;
}
+
lastDate = currentDate;
}
}
@@ -583,6 +591,8 @@ export class PortfolioCalculator {
);
const {
+ dividend,
+ dividendInBaseCurrency,
grossPerformance,
grossPerformancePercentage,
grossPerformancePercentageWithCurrencyEffect,
@@ -608,11 +618,11 @@ export class PortfolioCalculator {
hasAnySymbolMetricsErrors = hasAnySymbolMetricsErrors || hasErrors;
positions.push({
+ dividend,
+ dividendInBaseCurrency,
timeWeightedInvestment,
timeWeightedInvestmentWithCurrencyEffect,
- averagePrice: item.quantity.eq(0)
- ? new Big(0)
- : item.investment.div(item.quantity),
+ averagePrice: item.averagePrice,
currency: item.currency,
dataSource: item.dataSource,
fee: item.fee,
@@ -842,6 +852,8 @@ export class PortfolioCalculator {
const currentExchangeRate = exchangeRates[format(new Date(), DATE_FORMAT)];
const currentValues: { [date: string]: Big } = {};
const currentValuesWithCurrencyEffect: { [date: string]: Big } = {};
+ let dividend = new Big(0);
+ let dividendInBaseCurrency = new Big(0);
let fees = new Big(0);
let feesAtStartDate = new Big(0);
let feesAtStartDateWithCurrencyEffect = new Big(0);
@@ -894,6 +906,8 @@ export class PortfolioCalculator {
return {
currentValues: {},
currentValuesWithCurrencyEffect: {},
+ dividend: new Big(0),
+ dividendInBaseCurrency: new Big(0),
grossPerformance: new Big(0),
grossPerformancePercentage: new Big(0),
grossPerformancePercentageWithCurrencyEffect: new Big(0),
@@ -934,6 +948,8 @@ export class PortfolioCalculator {
return {
currentValues: {},
currentValuesWithCurrencyEffect: {},
+ dividend: new Big(0),
+ dividendInBaseCurrency: new Big(0),
grossPerformance: new Big(0),
grossPerformancePercentage: new Big(0),
grossPerformancePercentageWithCurrencyEffect: new Big(0),
@@ -1108,29 +1124,29 @@ export class PortfolioCalculator {
valueOfInvestmentBeforeTransactionWithCurrencyEffect;
}
- const transactionInvestment =
- order.type === 'BUY'
- ? order.quantity
- .mul(order.unitPriceInBaseCurrency)
- .mul(getFactor(order.type))
- : totalUnits.gt(0)
- ? totalInvestment
- .div(totalUnits)
- .mul(order.quantity)
- .mul(getFactor(order.type))
- : new Big(0);
-
- const transactionInvestmentWithCurrencyEffect =
- order.type === 'BUY'
- ? order.quantity
- .mul(order.unitPriceInBaseCurrencyWithCurrencyEffect)
- .mul(getFactor(order.type))
- : totalUnits.gt(0)
- ? totalInvestmentWithCurrencyEffect
- .div(totalUnits)
- .mul(order.quantity)
- .mul(getFactor(order.type))
- : new Big(0);
+ let transactionInvestment = new Big(0);
+ let transactionInvestmentWithCurrencyEffect = new Big(0);
+
+ if (order.type === 'BUY') {
+ transactionInvestment = order.quantity
+ .mul(order.unitPriceInBaseCurrency)
+ .mul(getFactor(order.type));
+ transactionInvestmentWithCurrencyEffect = order.quantity
+ .mul(order.unitPriceInBaseCurrencyWithCurrencyEffect)
+ .mul(getFactor(order.type));
+ } else if (order.type === 'SELL') {
+ if (totalUnits.gt(0)) {
+ transactionInvestment = totalInvestment
+ .div(totalUnits)
+ .mul(order.quantity)
+ .mul(getFactor(order.type));
+ transactionInvestmentWithCurrencyEffect =
+ totalInvestmentWithCurrencyEffect
+ .div(totalUnits)
+ .mul(order.quantity)
+ .mul(getFactor(order.type));
+ }
+ }
if (PortfolioCalculator.ENABLE_LOGGING) {
console.log('totalInvestment', totalInvestment.toNumber());
@@ -1186,6 +1202,13 @@ export class PortfolioCalculator {
totalUnits = totalUnits.plus(order.quantity.mul(getFactor(order.type)));
+ if (order.type === 'DIVIDEND') {
+ dividend = dividend.plus(order.quantity.mul(order.unitPrice));
+ dividendInBaseCurrency = dividendInBaseCurrency.plus(
+ dividend.mul(exchangeRateAtOrderDate ?? 1)
+ );
+ }
+
const valueOfInvestment = totalUnits.mul(order.unitPriceInBaseCurrency);
const valueOfInvestmentWithCurrencyEffect = totalUnits.mul(
@@ -1277,7 +1300,7 @@ export class PortfolioCalculator {
grossPerformanceWithCurrencyEffect;
}
- if (i > indexOfStartOrder) {
+ if (i > indexOfStartOrder && ['BUY', 'SELL'].includes(order.type)) {
// Only consider periods with an investment for the calculation of
// the time weighted investment
if (valueOfInvestmentBeforeTransaction.gt(0)) {
@@ -1471,6 +1494,7 @@ export class PortfolioCalculator {
Time weighted investment with currency effect: ${timeWeightedAverageInvestmentBetweenStartAndEndDateWithCurrencyEffect.toFixed(
2
)}
+ Total dividend: ${dividend.toFixed(2)}
Gross performance: ${totalGrossPerformance.toFixed(
2
)} / ${grossPerformancePercentage.mul(100).toFixed(2)}%
@@ -1495,6 +1519,8 @@ export class PortfolioCalculator {
return {
currentValues,
currentValuesWithCurrencyEffect,
+ dividend,
+ dividendInBaseCurrency,
grossPerformancePercentage,
grossPerformancePercentageWithCurrencyEffect,
initialValue,
diff --git a/apps/api/src/app/portfolio/portfolio.controller.ts b/apps/api/src/app/portfolio/portfolio.controller.ts
index e513215610..63e26e5121 100644
--- a/apps/api/src/app/portfolio/portfolio.controller.ts
+++ b/apps/api/src/app/portfolio/portfolio.controller.ts
@@ -1,4 +1,5 @@
import { AccessService } from '@ghostfolio/api/app/access/access.service';
+import { OrderService } from '@ghostfolio/api/app/order/order.service';
import { UserService } from '@ghostfolio/api/app/user/user.service';
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard';
import {
@@ -11,6 +12,7 @@ import { TransformDataSourceInResponseInterceptor } from '@ghostfolio/api/interc
import { ApiService } from '@ghostfolio/api/services/api/api.service';
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service';
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service';
+import { ImpersonationService } from '@ghostfolio/api/services/impersonation/impersonation.service';
import {
DEFAULT_CURRENCY,
HEADER_KEY_IMPERSONATION
@@ -57,6 +59,8 @@ export class PortfolioController {
private readonly apiService: ApiService,
private readonly configurationService: ConfigurationService,
private readonly exchangeRateDataService: ExchangeRateDataService,
+ private readonly impersonationService: ImpersonationService,
+ private readonly orderService: OrderService,
private readonly portfolioService: PortfolioService,
@Inject(REQUEST) private readonly request: RequestWithUser,
private readonly userService: UserService
@@ -161,7 +165,7 @@ export class PortfolioController {
'currentNetPerformance',
'currentNetPerformanceWithCurrencyEffect',
'currentValue',
- 'dividend',
+ 'dividendInBaseCurrency',
'emergencyFund',
'excludedAccountsAndActivities',
'fees',
@@ -231,11 +235,21 @@ export class PortfolioController {
filterByTags
});
+ const impersonationUserId =
+ await this.impersonationService.validateImpersonationId(impersonationId);
+ const userCurrency = this.request.user.Settings.settings.baseCurrency;
+
+ const { activities } = await this.orderService.getOrders({
+ filters,
+ userCurrency,
+ userId: impersonationUserId || this.request.user.id,
+ types: ['DIVIDEND']
+ });
+
let dividends = await this.portfolioService.getDividends({
+ activities,
dateRange,
- filters,
- groupBy,
- impersonationId
+ groupBy
});
if (
diff --git a/apps/api/src/app/portfolio/portfolio.service.ts b/apps/api/src/app/portfolio/portfolio.service.ts
index 0d14e35dfe..d55b3d647c 100644
--- a/apps/api/src/app/portfolio/portfolio.service.ts
+++ b/apps/api/src/app/portfolio/portfolio.service.ts
@@ -218,27 +218,14 @@ export class PortfolioService {
}
public async getDividends({
- dateRange,
- filters,
- groupBy,
- impersonationId
+ activities,
+ dateRange = 'max',
+ groupBy
}: {
- dateRange: DateRange;
- filters?: Filter[];
+ activities: Activity[];
+ dateRange?: DateRange;
groupBy?: GroupBy;
- impersonationId: string;
}): Promise<InvestmentItem[]> {
- const userId = await this.getUserId(impersonationId, this.request.user.id);
- const user = await this.userService.user({ id: userId });
- const userCurrency = this.getUserCurrency(user);
-
- const { activities } = await this.orderService.getOrders({
- filters,
- userCurrency,
- userId,
- types: ['DIVIDEND']
- });
-
let dividends = activities.map(({ date, valueInBaseCurrency }) => {
return {
date: format(date, DATE_FORMAT),
@@ -441,6 +428,7 @@ export class PortfolioService {
for (const {
currency,
+ dividend,
firstBuyDate,
grossPerformance,
grossPerformanceWithCurrencyEffect,
@@ -553,6 +541,7 @@ export class PortfolioService {
countries: symbolProfile.countries,
dataSource: symbolProfile.dataSource,
dateOfFirstActivity: parseDate(firstBuyDate),
+ dividend: dividend?.toNumber() ?? 0,
grossPerformance: grossPerformance?.toNumber() ?? 0,
grossPerformancePercent: grossPerformancePercentage?.toNumber() ?? 0,
grossPerformancePercentWithCurrencyEffect:
@@ -723,7 +712,7 @@ export class PortfolioService {
.filter((order) => {
tags = tags.concat(order.tags);
- return ['BUY', 'ITEM', 'SELL'].includes(order.type);
+ return ['BUY', 'DIVIDEND', 'ITEM', 'SELL'].includes(order.type);
})
.map((order) => ({
currency: order.SymbolProfile.currency,
@@ -764,6 +753,7 @@ export class PortfolioService {
averagePrice,
currency,
dataSource,
+ dividendInBaseCurrency,
fee,
firstBuyDate,
marketPrice,
@@ -780,16 +770,6 @@ export class PortfolioService {
return Account;
});
- const dividendInBaseCurrency = getSum(
- orders
- .filter(({ type }) => {
- return type === 'DIVIDEND';
- })
- .map(({ valueInBaseCurrency }) => {
- return new Big(valueInBaseCurrency);
- })
- );
-
const historicalData = await this.dataProviderService.getHistorical(
[{ dataSource, symbol: aSymbol }],
'day',
@@ -823,9 +803,7 @@ export class PortfolioService {
);
if (currentSymbol) {
- currentAveragePrice = currentSymbol.quantity.eq(0)
- ? 0
- : currentSymbol.investment.div(currentSymbol.quantity).toNumber();
+ currentAveragePrice = currentSymbol.averagePrice.toNumber();
currentQuantity = currentSymbol.quantity.toNumber();
}
@@ -1636,6 +1614,7 @@ export class PortfolioService {
countries: [],
dataSource: undefined,
dateOfFirstActivity: undefined,
+ dividend: 0,
grossPerformance: 0,
grossPerformancePercent: 0,
grossPerformancePercentWithCurrencyEffect: 0,
@@ -1765,11 +1744,16 @@ export class PortfolioService {
}
}
- const dividend = this.getSumOfActivityType({
- activities,
- userCurrency,
- activityType: 'DIVIDEND'
- }).toNumber();
+ const dividendInBaseCurrency = (
+ await this.getDividends({
+ activities: activities.filter(({ type }) => {
+ return type === 'DIVIDEND';
+ })
+ })
+ ).reduce(
+ (previous, current) => new Big(previous).plus(current.investment),
+ new Big(0)
+ );
const emergencyFund = new Big(
Math.max(
@@ -1904,7 +1888,6 @@ export class PortfolioService {
annualizedPerformancePercent,
annualizedPerformancePercentWithCurrencyEffect,
cash,
- dividend,
excludedAccountsAndActivities,
fees,
firstOrderDate,
@@ -1915,6 +1898,7 @@ export class PortfolioService {
totalBuy,
totalSell,
committedFunds: committedFunds.toNumber(),
+ dividendInBaseCurrency: dividendInBaseCurrency.toNumber(),
emergencyFund: {
assets: emergencyFundPositionsValueInBaseCurrency,
cash: emergencyFund
@@ -1967,7 +1951,7 @@ export class PortfolioService {
private async getTransactionPoints({
filters,
includeDrafts = false,
- types = ['BUY', 'ITEM', 'LIABILITY', 'SELL'],
+ types = ['BUY', 'DIVIDEND', 'ITEM', 'LIABILITY', 'SELL'],
userId,
withExcludedAccounts = false
}: {
@@ -2144,14 +2128,11 @@ export class PortfolioService {
type
} of ordersByAccount) {
let currentValueOfSymbolInBaseCurrency =
+ getFactor(type) *
quantity *
(portfolioItemsNow[SymbolProfile.symbol]?.marketPriceInBaseCurrency ??
0);
- if (['LIABILITY', 'SELL'].includes(type)) {
- currentValueOfSymbolInBaseCurrency *= getFactor(type);
- }
-
if (accounts[Account?.id || UNKNOWN_KEY]?.valueInBaseCurrency) {
accounts[Account?.id || UNKNOWN_KEY].valueInBaseCurrency +=
currentValueOfSymbolInBaseCurrency;
diff --git a/apps/api/src/services/exchange-rate-data/exchange-rate-data.service.mock.ts b/apps/api/src/services/exchange-rate-data/exchange-rate-data.service.mock.ts
index e32af51d35..a25f3a3569 100644
--- a/apps/api/src/services/exchange-rate-data/exchange-rate-data.service.mock.ts
+++ b/apps/api/src/services/exchange-rate-data/exchange-rate-data.service.mock.ts
@@ -22,6 +22,13 @@ export const ExchangeRateDataServiceMock = {
'2023-07-10': 0.8854
}
});
+ } else if (targetCurrency === 'USD') {
+ return Promise.resolve({
+ USDUSD: {
+ '2018-01-01': 1,
+ '2023-07-10': 1
+ }
+ });
}
return Promise.resolve({});
diff --git a/apps/client/src/app/components/portfolio-summary/portfolio-summary.component.html b/apps/client/src/app/components/portfolio-summary/portfolio-summary.component.html
index c4aea8891f..0962719264 100644
--- a/apps/client/src/app/components/portfolio-summary/portfolio-summary.component.html
+++ b/apps/client/src/app/components/portfolio-summary/portfolio-summary.component.html
@@ -328,7 +328,7 @@
[isCurrency]="true"
[locale]="locale"
[unit]="baseCurrency"
- [value]="isLoading ? undefined : summary?.dividend"
+ [value]="isLoading ? undefined : summary?.dividendInBaseCurrency"
/>
</div>
</div>
diff --git a/libs/common/src/lib/interfaces/portfolio-position.interface.ts b/libs/common/src/lib/interfaces/portfolio-position.interface.ts
index 87db0117d2..2e5772ef71 100644
--- a/libs/common/src/lib/interfaces/portfolio-position.interface.ts
+++ b/libs/common/src/lib/interfaces/portfolio-position.interface.ts
@@ -14,6 +14,7 @@ export interface PortfolioPosition {
currency: string;
dataSource: DataSource;
dateOfFirstActivity: Date;
+ dividend: number;
exchange?: string;
grossPerformance: number;
grossPerformancePercent: number;
diff --git a/libs/common/src/lib/interfaces/portfolio-summary.interface.ts b/libs/common/src/lib/interfaces/portfolio-summary.interface.ts
index f0bb4c3b1c..aaf80c0cd5 100644
--- a/libs/common/src/lib/interfaces/portfolio-summary.interface.ts
+++ b/libs/common/src/lib/interfaces/portfolio-summary.interface.ts
@@ -5,7 +5,7 @@ export interface PortfolioSummary extends PortfolioPerformance {
annualizedPerformancePercentWithCurrencyEffect: number;
cash: number;
committedFunds: number;
- dividend: number;
+ dividendInBaseCurrency: number;
emergencyFund: {
assets: number;
cash: number;
diff --git a/libs/common/src/lib/interfaces/symbol-metrics.interface.ts b/libs/common/src/lib/interfaces/symbol-metrics.interface.ts
index e7cbf74602..c269810d81 100644
--- a/libs/common/src/lib/interfaces/symbol-metrics.interface.ts
+++ b/libs/common/src/lib/interfaces/symbol-metrics.interface.ts
@@ -7,6 +7,8 @@ export interface SymbolMetrics {
currentValuesWithCurrencyEffect: {
[date: string]: Big;
};
+ dividend: Big;
+ dividendInBaseCurrency: Big;
grossPerformance: Big;
grossPerformancePercentage: Big;
grossPerformancePercentageWithCurrencyEffect: Big;
diff --git a/libs/common/src/lib/interfaces/timeline-position.interface.ts b/libs/common/src/lib/interfaces/timeline-position.interface.ts
index 220a0aa8f0..831c29b31d 100644
--- a/libs/common/src/lib/interfaces/timeline-position.interface.ts
+++ b/libs/common/src/lib/interfaces/timeline-position.interface.ts
@@ -5,6 +5,8 @@ export interface TimelinePosition {
averagePrice: Big;
currency: string;
dataSource: DataSource;
+ dividend: Big;
+ dividendInBaseCurrency: Big;
fee: Big;
firstBuyDate: string;
grossPerformance: Big;