Browse Source

Merge branch 'main' into fix/sell-activity-fee-cash-balance

pull/6862/head
Thomas Kaul 1 week ago
committed by GitHub
parent
commit
b361ae03f4
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 3
      CHANGELOG.md
  2. 4
      apps/api/src/app/endpoints/public/public.controller.ts
  3. 21
      apps/api/src/app/portfolio/current-rate.service.ts
  4. 34
      apps/api/src/app/portfolio/portfolio.service.ts
  5. 8
      apps/api/src/models/rule.ts
  6. 3
      apps/api/src/models/rules/asset-class-cluster-risk/equity.ts
  7. 3
      apps/api/src/models/rules/asset-class-cluster-risk/fixed-income.ts
  8. 2
      apps/api/src/models/rules/currency-cluster-risk/base-currency-current-investment.ts
  9. 2
      apps/api/src/models/rules/currency-cluster-risk/current-investment.ts
  10. 4
      apps/api/src/services/data-provider/data-provider.service.ts
  11. 52
      apps/client/src/app/components/investment-chart/investment-chart.component.ts
  12. 14
      libs/common/src/lib/helper.ts
  13. 16
      libs/ui/src/lib/treemap-chart/treemap-chart.component.ts

3
CHANGELOG.md

@ -9,7 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed ### Fixed
- Fixed the cash balance computation for `SELL` activities to subtract the fee instead of adding it (the previous logic inflated the account's cash balance by twice the fee) - Resolved an issue with the cash balance calculation of an account for `SELL` activities to ensure fees are correctly subtracted
- Resolved an exception in the portfolio details endpoint when an asset profile is unmatched
## 3.3.0 - 2026-05-14 ## 3.3.0 - 2026-05-14

4
apps/api/src/app/endpoints/public/public.controller.ts

@ -151,11 +151,11 @@ export class PublicController {
}; };
const totalValue = getSum( const totalValue = getSum(
Object.values(holdings).map(({ currency, marketPrice, quantity }) => { Object.values(holdings).map(({ assetProfile, marketPrice, quantity }) => {
return new Big( return new Big(
this.exchangeRateDataService.toCurrency( this.exchangeRateDataService.toCurrency(
quantity * marketPrice, quantity * marketPrice,
currency, assetProfile.currency,
this.request.user?.settings?.settings.baseCurrency ?? this.request.user?.settings?.settings.baseCurrency ??
DEFAULT_CURRENCY DEFAULT_CURRENCY
) )

21
apps/api/src/app/portfolio/current-rate.service.ts

@ -2,7 +2,10 @@ import { ActivitiesService } from '@ghostfolio/api/app/activities/activities.ser
import { LogPerformance } from '@ghostfolio/api/interceptors/performance-logging/performance-logging.interceptor'; import { LogPerformance } from '@ghostfolio/api/interceptors/performance-logging/performance-logging.interceptor';
import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service'; import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service';
import { MarketDataService } from '@ghostfolio/api/services/market-data/market-data.service'; import { MarketDataService } from '@ghostfolio/api/services/market-data/market-data.service';
import { resetHours } from '@ghostfolio/common/helper'; import {
getAssetProfileIdentifier,
resetHours
} from '@ghostfolio/common/helper';
import { import {
AssetProfileIdentifier, AssetProfileIdentifier,
DataProviderInfo, DataProviderInfo,
@ -114,8 +117,8 @@ export class CurrentRateService {
errors: quoteErrors.map(({ dataSource, symbol }) => { errors: quoteErrors.map(({ dataSource, symbol }) => {
return { dataSource, symbol }; return { dataSource, symbol };
}), }),
values: uniqBy(values, ({ date, symbol }) => { values: uniqBy(values, ({ dataSource, date, symbol }) => {
return `${date}-${symbol}`; return `${date}-${getAssetProfileIdentifier({ dataSource, symbol })}`;
}) })
}; };
@ -124,7 +127,11 @@ export class CurrentRateService {
try { try {
// If missing quote, fallback to the latest available historical market price // If missing quote, fallback to the latest available historical market price
let value: GetValueObject = response.values.find((currentValue) => { let value: GetValueObject = response.values.find((currentValue) => {
return currentValue.symbol === symbol && isToday(currentValue.date); return (
currentValue.dataSource === dataSource &&
currentValue.symbol === symbol &&
isToday(currentValue.date)
);
}); });
if (!value) { if (!value) {
@ -147,7 +154,11 @@ export class CurrentRateService {
const [latestValue] = response.values const [latestValue] = response.values
.filter((currentValue) => { .filter((currentValue) => {
return currentValue.symbol === symbol && currentValue.marketPrice; return (
currentValue.dataSource === dataSource &&
currentValue.marketPrice &&
currentValue.symbol === symbol
);
}) })
.sort((a, b) => { .sort((a, b) => {
if (a.date < b.date) { if (a.date < b.date) {

34
apps/api/src/app/portfolio/portfolio.service.ts

@ -36,7 +36,12 @@ import {
TAG_ID_EXCLUDE_FROM_ANALYSIS, TAG_ID_EXCLUDE_FROM_ANALYSIS,
UNKNOWN_KEY UNKNOWN_KEY
} from '@ghostfolio/common/config'; } from '@ghostfolio/common/config';
import { DATE_FORMAT, getSum, parseDate } from '@ghostfolio/common/helper'; import {
DATE_FORMAT,
getAssetProfileIdentifier,
getSum,
parseDate
} from '@ghostfolio/common/helper';
import { import {
AccountsResponse, AccountsResponse,
Activity, Activity,
@ -64,7 +69,7 @@ import {
} from '@ghostfolio/common/types'; } from '@ghostfolio/common/types';
import { PerformanceCalculationType } from '@ghostfolio/common/types/performance-calculation-type.type'; import { PerformanceCalculationType } from '@ghostfolio/common/types/performance-calculation-type.type';
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable, Logger } from '@nestjs/common';
import { REQUEST } from '@nestjs/core'; import { REQUEST } from '@nestjs/core';
import { import {
Account, Account,
@ -558,9 +563,17 @@ export class PortfolioService {
const cashSymbolProfiles = this.getCashSymbolProfiles(cashDetails); const cashSymbolProfiles = this.getCashSymbolProfiles(cashDetails);
symbolProfiles.push(...cashSymbolProfiles); symbolProfiles.push(...cashSymbolProfiles);
const symbolProfileMap: { [symbol: string]: EnhancedSymbolProfile } = {}; const symbolProfileMap: {
[assetProfileIdentifier: string]: EnhancedSymbolProfile;
} = {};
for (const symbolProfile of symbolProfiles) { for (const symbolProfile of symbolProfiles) {
symbolProfileMap[symbolProfile.symbol] = symbolProfile; symbolProfileMap[
getAssetProfileIdentifier({
dataSource: symbolProfile.dataSource,
symbol: symbolProfile.symbol
})
] = symbolProfile;
} }
const portfolioItemsNow: { [symbol: string]: TimelinePosition } = {}; const portfolioItemsNow: { [symbol: string]: TimelinePosition } = {};
@ -571,6 +584,7 @@ export class PortfolioService {
for (const { for (const {
activitiesCount, activitiesCount,
currency, currency,
dataSource,
dateOfFirstActivity, dateOfFirstActivity,
dividend, dividend,
grossPerformance, grossPerformance,
@ -600,7 +614,17 @@ export class PortfolioService {
} }
} }
const assetProfile = symbolProfileMap[symbol]; const assetProfile =
symbolProfileMap[getAssetProfileIdentifier({ dataSource, symbol })];
if (!assetProfile) {
Logger.warn(
`Asset profile not found for ${symbol} (${dataSource})`,
'PortfolioService'
);
continue;
}
let markets: PortfolioPosition['markets']; let markets: PortfolioPosition['markets'];
let marketsAdvanced: PortfolioPosition['marketsAdvanced']; let marketsAdvanced: PortfolioPosition['marketsAdvanced'];

8
apps/api/src/models/rule.ts

@ -1,6 +1,5 @@
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service';
import { DEFAULT_LANGUAGE_CODE } from '@ghostfolio/common/config'; import { DEFAULT_LANGUAGE_CODE } from '@ghostfolio/common/config';
import { groupBy } from '@ghostfolio/common/helper';
import { import {
PortfolioPosition, PortfolioPosition,
PortfolioReportRule, PortfolioReportRule,
@ -9,6 +8,7 @@ import {
} from '@ghostfolio/common/interfaces'; } from '@ghostfolio/common/interfaces';
import { Big } from 'big.js'; import { Big } from 'big.js';
import { groupBy } from 'lodash';
import { EvaluationResult } from './interfaces/evaluation-result.interface'; import { EvaluationResult } from './interfaces/evaluation-result.interface';
import { RuleInterface } from './interfaces/rule.interface'; import { RuleInterface } from './interfaces/rule.interface';
@ -41,10 +41,10 @@ export abstract class Rule<T extends RuleSettings> implements RuleInterface<T> {
public groupCurrentHoldingsByAttribute( public groupCurrentHoldingsByAttribute(
holdings: PortfolioPosition[], holdings: PortfolioPosition[],
attribute: keyof PortfolioPosition, attribute: `assetProfile.${Extract<keyof PortfolioPosition['assetProfile'], string>}`,
baseCurrency: string baseCurrency: string
) { ) {
return Array.from(groupBy(attribute, holdings).entries()).map( return Object.entries(groupBy(holdings, attribute)).map(
([attributeValue, objs]) => ({ ([attributeValue, objs]) => ({
groupKey: attributeValue, groupKey: attributeValue,
investment: objs.reduce( investment: objs.reduce(
@ -59,7 +59,7 @@ export abstract class Rule<T extends RuleSettings> implements RuleInterface<T> {
new Big(currentValue.quantity) new Big(currentValue.quantity)
.mul(currentValue.marketPrice ?? 0) .mul(currentValue.marketPrice ?? 0)
.toNumber(), .toNumber(),
currentValue.currency, currentValue.assetProfile.currency,
baseCurrency baseCurrency
), ),
0 0

3
apps/api/src/models/rules/asset-class-cluster-risk/equity.ts

@ -27,9 +27,10 @@ export class AssetClassClusterRiskEquity extends Rule<Settings> {
public evaluate(ruleSettings: Settings) { public evaluate(ruleSettings: Settings) {
const holdingsGroupedByAssetClass = this.groupCurrentHoldingsByAttribute( const holdingsGroupedByAssetClass = this.groupCurrentHoldingsByAttribute(
this.holdings, this.holdings,
'assetClass', 'assetProfile.assetClass',
ruleSettings.baseCurrency ruleSettings.baseCurrency
); );
let totalValue = 0; let totalValue = 0;
const equityValueInBaseCurrency = const equityValueInBaseCurrency =

3
apps/api/src/models/rules/asset-class-cluster-risk/fixed-income.ts

@ -27,9 +27,10 @@ export class AssetClassClusterRiskFixedIncome extends Rule<Settings> {
public evaluate(ruleSettings: Settings) { public evaluate(ruleSettings: Settings) {
const holdingsGroupedByAssetClass = this.groupCurrentHoldingsByAttribute( const holdingsGroupedByAssetClass = this.groupCurrentHoldingsByAttribute(
this.holdings, this.holdings,
'assetClass', 'assetProfile.assetClass',
ruleSettings.baseCurrency ruleSettings.baseCurrency
); );
let totalValue = 0; let totalValue = 0;
const fixedIncomeValueInBaseCurrency = const fixedIncomeValueInBaseCurrency =

2
apps/api/src/models/rules/currency-cluster-risk/base-currency-current-investment.ts

@ -27,7 +27,7 @@ export class CurrencyClusterRiskBaseCurrencyCurrentInvestment extends Rule<Setti
public evaluate(ruleSettings: Settings) { public evaluate(ruleSettings: Settings) {
const holdingsGroupedByCurrency = this.groupCurrentHoldingsByAttribute( const holdingsGroupedByCurrency = this.groupCurrentHoldingsByAttribute(
this.holdings, this.holdings,
'currency', 'assetProfile.currency',
ruleSettings.baseCurrency ruleSettings.baseCurrency
); );

2
apps/api/src/models/rules/currency-cluster-risk/current-investment.ts

@ -27,7 +27,7 @@ export class CurrencyClusterRiskCurrentInvestment extends Rule<Settings> {
public evaluate(ruleSettings: Settings) { public evaluate(ruleSettings: Settings) {
const holdingsGroupedByCurrency = this.groupCurrentHoldingsByAttribute( const holdingsGroupedByCurrency = this.groupCurrentHoldingsByAttribute(
this.holdings, this.holdings,
'currency', 'assetProfile.currency',
ruleSettings.baseCurrency ruleSettings.baseCurrency
); );

4
apps/api/src/services/data-provider/data-provider.service.ts

@ -82,6 +82,7 @@ export class DataProviderService implements OnModuleInit {
return false; return false;
} }
// TODO: Change symbol in response to assetProfileIdentifier
public async getAssetProfiles(items: AssetProfileIdentifier[]): Promise<{ public async getAssetProfiles(items: AssetProfileIdentifier[]): Promise<{
[symbol: string]: Partial<SymbolProfile>; [symbol: string]: Partial<SymbolProfile>;
}> { }> {
@ -330,6 +331,7 @@ export class DataProviderService implements OnModuleInit {
}); });
} }
// TODO: Change symbol in response to assetProfileIdentifier
public async getHistorical( public async getHistorical(
aItems: AssetProfileIdentifier[], aItems: AssetProfileIdentifier[],
aGranularity: Granularity = 'month', aGranularity: Granularity = 'month',
@ -395,6 +397,7 @@ export class DataProviderService implements OnModuleInit {
} }
} }
// TODO: Change symbol in response to assetProfileIdentifier
public async getHistoricalRaw({ public async getHistoricalRaw({
assetProfileIdentifiers, assetProfileIdentifiers,
from, from,
@ -508,6 +511,7 @@ export class DataProviderService implements OnModuleInit {
return result; return result;
} }
// TODO: Change symbol in response to assetProfileIdentifier
public async getQuotes({ public async getQuotes({
items, items,
requestTimeout, requestTimeout,

52
apps/client/src/app/components/investment-chart/investment-chart.component.ts

@ -24,7 +24,7 @@ import {
Input, Input,
OnChanges, OnChanges,
OnDestroy, OnDestroy,
ViewChild viewChild
} from '@angular/core'; } from '@angular/core';
import { import {
BarController, BarController,
@ -55,20 +55,21 @@ import { NgxSkeletonLoaderModule } from 'ngx-skeleton-loader';
templateUrl: './investment-chart.component.html' templateUrl: './investment-chart.component.html'
}) })
export class GfInvestmentChartComponent implements OnChanges, OnDestroy { export class GfInvestmentChartComponent implements OnChanges, OnDestroy {
@Input() benchmarkDataItems: InvestmentItem[] = []; @Input() public readonly benchmarkDataItems: InvestmentItem[] = [];
@Input() benchmarkDataLabel = ''; @Input() public readonly benchmarkDataLabel = '';
@Input() colorScheme: ColorScheme; @Input() public readonly colorScheme: ColorScheme;
@Input() currency: string; @Input() public readonly currency: string;
@Input() groupBy: GroupBy; @Input() public readonly groupBy: GroupBy;
@Input() historicalDataItems: LineChartItem[] = []; @Input() public readonly historicalDataItems: LineChartItem[] = [];
@Input() isInPercentage = false; @Input() public readonly isInPercentage = false;
@Input() isLoading = false; @Input() public readonly isLoading = false;
@Input() locale = getLocale(); @Input() public readonly locale = getLocale();
@Input() savingsRate = 0; @Input() public readonly savingsRate = 0;
@ViewChild('chartCanvas') chartCanvas: ElementRef<HTMLCanvasElement>; private readonly chartCanvas =
viewChild.required<ElementRef<HTMLCanvasElement>>('chartCanvas');
public chart: Chart<'bar' | 'line'>; private chart: Chart<'bar' | 'line'>;
private investments: InvestmentItem[]; private investments: InvestmentItem[];
private values: LineChartItem[]; private values: LineChartItem[];
@ -118,7 +119,7 @@ export class GfInvestmentChartComponent implements OnChanges, OnDestroy {
borderWidth: this.groupBy ? 0 : 1, borderWidth: this.groupBy ? 0 : 1,
data: this.investments.map(({ date, investment }) => { data: this.investments.map(({ date, investment }) => {
return { return {
x: parseDate(date).getTime(), x: parseDate(date)?.getTime() ?? null,
y: this.isInPercentage ? investment * 100 : investment y: this.isInPercentage ? investment * 100 : investment
}; };
}), }),
@ -138,7 +139,7 @@ export class GfInvestmentChartComponent implements OnChanges, OnDestroy {
borderWidth: 2, borderWidth: 2,
data: this.values.map(({ date, value }) => { data: this.values.map(({ date, value }) => {
return { return {
x: parseDate(date).getTime(), x: parseDate(date)?.getTime() ?? null,
y: this.isInPercentage ? value * 100 : value y: this.isInPercentage ? value * 100 : value
}; };
}), }),
@ -165,14 +166,16 @@ export class GfInvestmentChartComponent implements OnChanges, OnDestroy {
this.getTooltipPluginConfiguration(); this.getTooltipPluginConfiguration();
const annotations = this.chart.options.plugins.annotation const annotations = this.chart.options.plugins.annotation
.annotations as Record<string, AnnotationOptions<'line'>>; ?.annotations as Record<string, AnnotationOptions<'line'>>;
if (this.savingsRate && annotations.savingsRate) { if (this.savingsRate && annotations.savingsRate) {
annotations.savingsRate.value = this.savingsRate; annotations.savingsRate.value = this.savingsRate;
} }
this.chart.update(); this.chart.update();
} else { } else {
this.chart = new Chart(this.chartCanvas.nativeElement, { this.chart = new Chart<'bar' | 'line'>(
this.chartCanvas().nativeElement,
{
data: chartData, data: chartData,
options: { options: {
animation: false, animation: false,
@ -278,10 +281,11 @@ export class GfInvestmentChartComponent implements OnChanges, OnDestroy {
} }
}, },
plugins: [ plugins: [
getVerticalHoverLinePlugin(this.chartCanvas, this.colorScheme) getVerticalHoverLinePlugin(this.chartCanvas(), this.colorScheme)
], ],
type: this.groupBy ? 'bar' : 'line' type: this.groupBy ? 'bar' : 'line'
}); }
);
} }
} }
} }
@ -305,8 +309,12 @@ export class GfInvestmentChartComponent implements OnChanges, OnDestroy {
} }
private isInFuture<T>(aContext: ScriptableLineSegmentContext, aValue: T) { private isInFuture<T>(aContext: ScriptableLineSegmentContext, aValue: T) {
return isAfter(new Date(aContext?.p1?.parsed?.x), new Date()) const xValue = aContext?.p1?.parsed?.x;
? aValue
: undefined; if (xValue == null) {
return undefined;
}
return isAfter(new Date(xValue), new Date()) ? aValue : undefined;
} }
} }

14
libs/common/src/lib/helper.ts

@ -342,20 +342,6 @@ export function getYesterday() {
return subDays(new Date(Date.UTC(year, month, day)), 1); return subDays(new Date(Date.UTC(year, month, day)), 1);
} }
export function groupBy<T, K extends keyof T>(
key: K,
arr: T[]
): Map<T[K], T[]> {
const map = new Map<T[K], T[]>();
arr.forEach((t) => {
if (!map.has(t[key])) {
map.set(t[key], []);
}
map.get(t[key])!.push(t);
});
return map;
}
export function interpolate(template: string, context: any) { export function interpolate(template: string, context: any) {
return template?.replace(/[$]{([^}]+)}/g, (_, objectPath) => { return template?.replace(/[$]{([^}]+)}/g, (_, objectPath) => {
const properties = objectPath.split('.'); const properties = objectPath.split('.');

16
libs/ui/src/lib/treemap-chart/treemap-chart.component.ts

@ -280,8 +280,8 @@ export class GfTreemapChartComponent
); );
} }
const name = raw._data.name; const name = raw._data.assetProfile.name;
const symbol = raw._data.symbol; const symbol = raw._data.assetProfile.symbol;
return [ return [
isUUID(symbol) ? (name ?? symbol) : symbol, isUUID(symbol) ? (name ?? symbol) : symbol,
@ -322,8 +322,10 @@ export class GfTreemapChartComponent
['desc'] ['desc']
) as PortfolioPosition[]; ) as PortfolioPosition[];
const dataSource: DataSource = dataset[dataIndex].dataSource; const dataSource: DataSource =
const symbol: string = dataset[dataIndex].symbol; dataset[dataIndex].assetProfile.dataSource;
const symbol: string = dataset[dataIndex].assetProfile.symbol;
this.treemapChartClicked.emit({ dataSource, symbol }); this.treemapChartClicked.emit({ dataSource, symbol });
} catch {} } catch {}
@ -357,10 +359,12 @@ export class GfTreemapChartComponent
callbacks: { callbacks: {
label: ({ raw }: GfTreemapTooltipItem) => { label: ({ raw }: GfTreemapTooltipItem) => {
const allocationInPercentage = `${(raw._data.allocationInPercentage * 100).toFixed(2)}%`; const allocationInPercentage = `${(raw._data.allocationInPercentage * 100).toFixed(2)}%`;
const name = raw._data.name; const name = raw._data.assetProfile.name;
const sign = const sign =
raw._data.netPerformancePercentWithCurrencyEffect > 0 ? '+' : ''; raw._data.netPerformancePercentWithCurrencyEffect > 0 ? '+' : '';
const symbol = raw._data.symbol;
const symbol = raw._data.assetProfile.symbol;
const netPerformanceInPercentageWithSign = `${sign}${(raw._data.netPerformancePercentWithCurrencyEffect * 100).toFixed(2)}%`; const netPerformanceInPercentageWithSign = `${sign}${(raw._data.netPerformancePercentWithCurrencyEffect * 100).toFixed(2)}%`;

Loading…
Cancel
Save