Browse Source

Merge remote-tracking branch 'origin/dockerpush'

pull/5027/head
Dan 9 months ago
parent
commit
d0e55ae228
  1. 1
      .admin.cred
  2. 25
      .env.dev
  3. 3
      .env.example
  4. 47
      .github/workflows/docker-image-branch.yml
  5. 47
      .github/workflows/docker-image-dev.yml
  6. 5
      .github/workflows/docker-image.yml
  7. 47
      .github/workflows/main.yml
  8. 2
      CHANGELOG.md
  9. 11
      apps/api/project.json
  10. 1
      apps/api/src/app/account-balance/account-balance.service.ts
  11. 2
      apps/api/src/app/account/account.service.ts
  12. 7
      apps/api/src/app/admin/admin.controller.ts
  13. 2
      apps/api/src/app/admin/admin.module.ts
  14. 25
      apps/api/src/app/admin/admin.service.ts
  15. 6
      apps/api/src/app/admin/update-asset-profile.dto.ts
  16. 13
      apps/api/src/app/import/import.service.ts
  17. 32
      apps/api/src/app/order/order.service.ts
  18. 598
      apps/api/src/app/portfolio/calculator/constantPortfolioReturn/portfolio-calculator.ts
  19. 37
      apps/api/src/app/portfolio/calculator/portfolio-calculator.factory.ts
  20. 25
      apps/api/src/app/portfolio/calculator/portfolio-calculator.ts
  21. 3
      apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-baln-buy-and-sell-in-two-activities.spec.ts
  22. 3
      apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-baln-buy-and-sell.spec.ts
  23. 3
      apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-baln-buy.spec.ts
  24. 3
      apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-btcusd-buy-and-sell-partially.spec.ts
  25. 3
      apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-fee.spec.ts
  26. 3
      apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-googl-buy.spec.ts
  27. 3
      apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-item.spec.ts
  28. 3
      apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-liability.spec.ts
  29. 3
      apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-msft-buy-with-dividend.spec.ts
  30. 3
      apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-no-orders.spec.ts
  31. 3
      apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-novn-buy-and-sell-partially.spec.ts
  32. 3
      apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-novn-buy-and-sell.spec.ts
  33. 3
      apps/api/src/app/portfolio/calculator/twr/portfolio-calculator.spec.ts
  34. 17
      apps/api/src/app/portfolio/calculator/twr/portfolio-calculator.ts
  35. 1
      apps/api/src/app/portfolio/interfaces/portfolio-holding-detail.interface.ts
  36. 5
      apps/api/src/app/portfolio/interfaces/portfolio-order-item.interface.ts
  37. 34
      apps/api/src/app/portfolio/portfolio.controller.ts
  38. 193
      apps/api/src/app/portfolio/portfolio.service.ts
  39. 5
      apps/api/src/app/tag/tag.service.ts
  40. 3
      apps/api/src/app/user/update-user-setting.dto.ts
  41. 6
      apps/api/src/app/user/user.controller.ts
  42. 25
      apps/api/src/helper/dateQueryHelper.ts
  43. 1
      apps/api/src/helper/portfolio.helper.ts
  44. 2
      apps/api/src/interceptors/performance-logging/performance-logging.interceptor.ts
  45. 10
      apps/api/src/services/data-provider/data-enhancer/trackinsight/trackinsight.service.ts
  46. 29
      apps/api/src/services/data-provider/data-provider.service.ts
  47. 14
      apps/api/src/services/data-provider/manual/manual.service.ts
  48. 13
      apps/api/src/services/market-data/market-data.service.ts
  49. 3
      apps/api/src/services/queues/data-gathering/data-gathering.service.ts
  50. 12
      apps/api/src/services/symbol-profile/symbol-profile-overwrite.module.ts
  51. 69
      apps/api/src/services/symbol-profile/symbol-profile-overwrite.service.ts
  52. 19
      apps/api/src/services/symbol-profile/symbol-profile.service.ts
  53. 9
      apps/api/src/services/tag/tag.service.ts
  54. 6
      apps/client-e2e/project.json
  55. 96
      apps/client/project.json
  56. 52
      apps/client/src/app/components/admin-market-data/asset-profile-dialog/asset-profile-dialog.component.ts
  57. 31
      apps/client/src/app/components/admin-market-data/asset-profile-dialog/asset-profile-dialog.html
  58. 4
      apps/client/src/app/components/admin-market-data/asset-profile-dialog/asset-profile-dialog.module.ts
  59. 13
      apps/client/src/app/components/admin-tag/admin-tag.component.html
  60. 8
      apps/client/src/app/components/admin-tag/admin-tag.component.ts
  61. 1
      apps/client/src/app/components/benchmark-comparator/benchmark-comparator.component.scss
  62. 16
      apps/client/src/app/components/benchmark-comparator/benchmark-comparator.component.ts
  63. 35
      apps/client/src/app/components/header/header.component.ts
  64. 30
      apps/client/src/app/components/holding-detail-dialog/holding-detail-dialog.component.ts
  65. 21
      apps/client/src/app/components/holding-detail-dialog/holding-detail-dialog.html
  66. 3
      apps/client/src/app/components/toggle/toggle.component.ts
  67. 6
      apps/client/src/app/pages/portfolio/activities/create-or-update-activity-dialog/create-or-update-activity-dialog.component.ts
  68. 13
      apps/client/src/app/pages/portfolio/activities/create-or-update-activity-dialog/create-or-update-activity-dialog.html
  69. 3
      apps/client/src/app/pages/portfolio/allocations/allocations-page.component.ts
  70. 48
      apps/client/src/app/pages/portfolio/analysis/analysis-page.component.ts
  71. 30
      apps/client/src/app/pages/portfolio/analysis/analysis-page.html
  72. 2
      apps/client/src/app/services/admin.service.ts
  73. 11
      apps/client/src/app/services/data.service.ts
  74. 2
      apps/client/src/app/services/import-activities.service.ts
  75. 6
      apps/client/src/app/services/user/user.service.ts
  76. 6
      apps/ui-e2e/project.json
  77. 46
      libs/common/src/lib/chunkhelper.ts
  78. 3
      libs/common/src/lib/interfaces/admin-market-data.interface.ts
  79. 3
      libs/common/src/lib/interfaces/enhanced-symbol-profile.interface.ts
  80. 2
      libs/common/src/lib/interfaces/historical-data-item.interface.ts
  81. 6
      libs/common/src/lib/interfaces/symbol-metrics.interface.ts
  82. 9
      libs/common/src/lib/types/date-range.type.ts
  83. 51
      libs/ui/src/lib/activities-table/activities-table.component.scss
  84. 38
      libs/ui/src/lib/activity-type/activity-type.component.html
  85. 50
      libs/ui/src/lib/assistant/assistant.component.ts
  86. 6
      libs/ui/src/lib/assistant/assistant.html
  87. 1
      libs/ui/src/lib/i18n.ts
  88. 185
      migrations.json
  89. 3
      nx.json
  90. 4804
      package-lock.json
  91. 6
      package.json
  92. 22
      prisma/migrations/20231108082445_added_tags_to_holding/migration.sql
  93. 3
      prisma/schema.prisma
  94. 17248
      yarn-error.log

1
.admin.cred

@ -0,0 +1 @@
14d4daf73eefed7da7c32ec19bc37e678be0244fb46c8f4965bfe9ece7384706ed58222ad9b96323893c1d845bc33a308e7524c2c79636062cbb095e0780cb51

25
.env.dev

@ -1,25 +0,0 @@
COMPOSE_PROJECT_NAME=ghostfolio-development
# CACHE
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=<INSERT_REDIS_PASSWORD>
# POSTGRES
POSTGRES_DB=ghostfolio-db
POSTGRES_USER=user
POSTGRES_PASSWORD=<INSERT_POSTGRES_PASSWORD>
# VARIOUS
ACCESS_TOKEN_SALT=<INSERT_RANDOM_STRING>
DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:5432/${POSTGRES_DB}?connect_timeout=300&sslmode=prefer
JWT_SECRET_KEY=<INSERT_RANDOM_STRING>
# DEVELOPMENT
# Nx 18 enables using plugins to infer targets by default
# This is disabled for existing workspaces to maintain compatibility
# For more info, see: https://nx.dev/concepts/inferred-tasks
NX_ADD_PLUGINS=false
NX_NATIVE_COMMAND_RUNNER=false

3
.env.example

@ -1,4 +1,4 @@
COMPOSE_PROJECT_NAME=ghostfolio COMPOSE_PROJECT_NAME=ghostfolio-development
# CACHE # CACHE
REDIS_HOST=localhost REDIS_HOST=localhost
@ -10,7 +10,6 @@ POSTGRES_DB=ghostfolio-db
POSTGRES_USER=user POSTGRES_USER=user
POSTGRES_PASSWORD=<INSERT_POSTGRES_PASSWORD> POSTGRES_PASSWORD=<INSERT_POSTGRES_PASSWORD>
# VARIOUS
ACCESS_TOKEN_SALT=<INSERT_RANDOM_STRING> ACCESS_TOKEN_SALT=<INSERT_RANDOM_STRING>
DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:5432/${POSTGRES_DB}?connect_timeout=300&sslmode=prefer DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:5432/${POSTGRES_DB}?connect_timeout=300&sslmode=prefer
JWT_SECRET_KEY=<INSERT_RANDOM_STRING> JWT_SECRET_KEY=<INSERT_RANDOM_STRING>

47
.github/workflows/docker-image-branch.yml

@ -0,0 +1,47 @@
name: Docker image CD - Branch
on:
push:
branches:
- '*'
jobs:
build_and_push:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Docker metadata
id: meta
uses: docker/metadata-action@v4
with:
images: dandevaud/ghostfolio
tags: |
type=semver,pattern={{major}}
type=semver,pattern={{version}}
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v2
- name: Login to DockerHub
if: github.event_name != 'pull_request'
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v3
with:
context: .
platforms: linux/amd64,linux/arm/v7,linux/arm64
push: ${{ github.event_name != 'pull_request' }}
tags: dandevaud/ghostfolio:${{ github.ref_name }}
labels: ${{ steps.meta.output.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max

47
.github/workflows/docker-image-dev.yml

@ -0,0 +1,47 @@
name: Docker image CD - DEV
on:
push:
branches:
- 'dockerpush'
jobs:
build_and_push:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Docker metadata
id: meta
uses: docker/metadata-action@v4
with:
images: dandevaud/ghostfolio
tags: |
type=semver,pattern={{major}}
type=semver,pattern={{version}}
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v2
- name: Login to DockerHub
if: github.event_name != 'pull_request'
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v3
with:
context: .
platforms: linux/amd64,linux/arm/v7,linux/arm64
push: ${{ github.event_name != 'pull_request' }}
tags: dandevaud/ghostfolio:beta
labels: ${{ steps.meta.output.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max

5
.github/workflows/docker-image.yml

@ -4,9 +4,6 @@ on:
push: push:
tags: tags:
- '*.*.*' - '*.*.*'
pull_request:
branches:
- 'main'
jobs: jobs:
build_and_push: build_and_push:
@ -19,7 +16,7 @@ jobs:
id: meta id: meta
uses: docker/metadata-action@v4 uses: docker/metadata-action@v4
with: with:
images: ghostfolio/ghostfolio images: dandevaud/ghostfolio
tags: | tags: |
type=semver,pattern={{major}} type=semver,pattern={{major}}
type=semver,pattern={{version}} type=semver,pattern={{version}}

47
.github/workflows/main.yml

@ -0,0 +1,47 @@
name: Docker image CD - DEV
on:
push:
branches:
- 'main'
jobs:
build_and_push:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Docker metadata
id: meta
uses: docker/metadata-action@v4
with:
images: dandevaud/ghostfolio
tags: |
type=semver,pattern={{major}}
type=semver,pattern={{version}}
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v2
- name: Login to DockerHub
if: github.event_name != 'pull_request'
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v3
with:
context: .
platforms: linux/amd64,linux/arm/v7,linux/arm64
push: ${{ github.event_name != 'pull_request' }}
tags: dandevaud/ghostfolio:main
labels: ${{ steps.meta.output.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max

2
CHANGELOG.md

@ -1260,9 +1260,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Introduced the lazy-loaded activities table to the position detail dialog (experimental) - Introduced the lazy-loaded activities table to the position detail dialog (experimental)
- Improved the font weight in the value component - Improved the font weight in the value component
- Improved the language localization for Türkçe (`tr`) - Improved the language localization for Türkçe (`tr`)
- Upgraded `angular` from version `17.0.4` to `17.0.7`
- Upgraded to _Inter_ 4 font family - Upgraded to _Inter_ 4 font family
- Upgraded `Nx` from version `17.0.2` to `17.2.5`
### Fixed ### Fixed

11
apps/api/project.json

@ -4,6 +4,7 @@
"sourceRoot": "apps/api/src", "sourceRoot": "apps/api/src",
"projectType": "application", "projectType": "application",
"prefix": "api", "prefix": "api",
"tags": [],
"generators": {}, "generators": {},
"targets": { "targets": {
"build": { "build": {
@ -60,6 +61,13 @@
"buildTarget": "api:build" "buildTarget": "api:build"
} }
}, },
"profile": {
"executor": "@nx/js:node",
"options": {
"buildTarget": "api:build",
"runtimeArgs": ["--perf-basic-prof-only-functions"]
}
},
"lint": { "lint": {
"executor": "@nx/eslint:lint", "executor": "@nx/eslint:lint",
"options": { "options": {
@ -73,6 +81,5 @@
}, },
"outputs": ["{workspaceRoot}/coverage/apps/api"] "outputs": ["{workspaceRoot}/coverage/apps/api"]
} }
}, }
"tags": []
} }

1
apps/api/src/app/account-balance/account-balance.service.ts

@ -95,6 +95,7 @@ export class AccountBalanceService {
return accountBalance; return accountBalance;
} }
@LogPerformance
public async getAccountBalanceItems({ public async getAccountBalanceItems({
filters, filters,
userCurrency, userCurrency,

2
apps/api/src/app/account/account.service.ts

@ -1,5 +1,6 @@
import { AccountBalanceService } from '@ghostfolio/api/app/account-balance/account-balance.service'; import { AccountBalanceService } from '@ghostfolio/api/app/account-balance/account-balance.service';
import { PortfolioChangedEvent } from '@ghostfolio/api/events/portfolio-changed.event'; import { PortfolioChangedEvent } from '@ghostfolio/api/events/portfolio-changed.event';
import { LogPerformance } from '@ghostfolio/api/interceptors/performance-logging/performance-logging.interceptor';
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 { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service';
import { DATE_FORMAT } from '@ghostfolio/common/helper'; import { DATE_FORMAT } from '@ghostfolio/common/helper';
@ -149,6 +150,7 @@ export class AccountService {
}); });
} }
@LogPerformance
public async getCashDetails({ public async getCashDetails({
currency, currency,
filters = [], filters = [],

7
apps/api/src/app/admin/admin.controller.ts

@ -335,7 +335,12 @@ export class AdminController {
return this.adminService.patchAssetProfileData({ return this.adminService.patchAssetProfileData({
...assetProfileData, ...assetProfileData,
dataSource, dataSource,
symbol symbol,
tags: {
connect: assetProfileData.tags?.map(({ id }) => {
return { id };
})
}
}); });
} }

2
apps/api/src/app/admin/admin.module.ts

@ -10,6 +10,7 @@ import { MarketDataModule } from '@ghostfolio/api/services/market-data/market-da
import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module'; import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module';
import { PropertyModule } from '@ghostfolio/api/services/property/property.module'; import { PropertyModule } from '@ghostfolio/api/services/property/property.module';
import { DataGatheringModule } from '@ghostfolio/api/services/queues/data-gathering/data-gathering.module'; import { DataGatheringModule } from '@ghostfolio/api/services/queues/data-gathering/data-gathering.module';
import { SymbolProfileOverwriteModule } from '@ghostfolio/api/services/symbol-profile/symbol-profile-overwrite.module';
import { SymbolProfileModule } from '@ghostfolio/api/services/symbol-profile/symbol-profile.module'; import { SymbolProfileModule } from '@ghostfolio/api/services/symbol-profile/symbol-profile.module';
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
@ -33,6 +34,7 @@ import { QueueModule } from './queue/queue.module';
QueueModule, QueueModule,
SubscriptionModule, SubscriptionModule,
SymbolProfileModule, SymbolProfileModule,
SymbolProfileOverwriteModule,
TransformDataSourceInRequestModule TransformDataSourceInRequestModule
], ],
controllers: [AdminController], controllers: [AdminController],

25
apps/api/src/app/admin/admin.service.ts

@ -8,6 +8,7 @@ import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-
import { MarketDataService } from '@ghostfolio/api/services/market-data/market-data.service'; import { MarketDataService } from '@ghostfolio/api/services/market-data/market-data.service';
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service';
import { PropertyService } from '@ghostfolio/api/services/property/property.service'; import { PropertyService } from '@ghostfolio/api/services/property/property.service';
import { SymbolProfileOverwriteService } from '@ghostfolio/api/services/symbol-profile/symbol-profile-overwrite.service';
import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service'; import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service';
import { import {
DEFAULT_CURRENCY, DEFAULT_CURRENCY,
@ -36,11 +37,13 @@ import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { import {
AssetClass, AssetClass,
AssetSubClass, AssetSubClass,
DataSource,
Prisma, Prisma,
PrismaClient, PrismaClient,
Property, Property,
SymbolProfile SymbolProfile,
DataSource,
Tag,
SymbolProfileOverrides
} from '@prisma/client'; } from '@prisma/client';
import { differenceInDays } from 'date-fns'; import { differenceInDays } from 'date-fns';
import { groupBy } from 'lodash'; import { groupBy } from 'lodash';
@ -57,7 +60,8 @@ export class AdminService {
private readonly prismaService: PrismaService, private readonly prismaService: PrismaService,
private readonly propertyService: PropertyService, private readonly propertyService: PropertyService,
private readonly subscriptionService: SubscriptionService, private readonly subscriptionService: SubscriptionService,
private readonly symbolProfileService: SymbolProfileService private readonly symbolProfileService: SymbolProfileService,
private readonly symbolProfileOverwriteService: SymbolProfileOverwriteService
) {} ) {}
public async addAssetProfile({ public async addAssetProfile({
@ -259,7 +263,8 @@ export class AdminService {
}, },
scraperConfiguration: true, scraperConfiguration: true,
sectors: true, sectors: true,
symbol: true symbol: true,
tags: true
} }
}), }),
this.prismaService.symbolProfile.count({ where }) this.prismaService.symbolProfile.count({ where })
@ -311,7 +316,8 @@ export class AdminService {
name, name,
Order, Order,
sectors, sectors,
symbol symbol,
tags
}) => { }) => {
const countriesCount = countries const countriesCount = countries
? Object.keys(countries).length ? Object.keys(countries).length
@ -346,7 +352,9 @@ export class AdminService {
sectorsCount, sectorsCount,
activitiesCount: _count.Order, activitiesCount: _count.Order,
date: Order?.[0]?.date, date: Order?.[0]?.date,
isUsedByUsersWithSubscription: await isUsedByUsersWithSubscription isUsedByUsersWithSubscription:
await isUsedByUsersWithSubscription,
tags
}; };
} }
) )
@ -440,6 +448,7 @@ export class AdminService {
dataSource, dataSource,
holdings, holdings,
name, name,
tags,
scraperConfiguration, scraperConfiguration,
sectors, sectors,
symbol, symbol,
@ -464,6 +473,7 @@ export class AdminService {
sectors, sectors,
symbol, symbol,
symbolMapping, symbolMapping,
tags,
...(dataSource === 'MANUAL' ...(dataSource === 'MANUAL'
? { assetClass, assetSubClass, name, url } ? { assetClass, assetSubClass, name, url }
: { : {
@ -629,7 +639,8 @@ export class AdminService {
date: dateOfFirstActivity, date: dateOfFirstActivity,
id: undefined, id: undefined,
name: symbol, name: symbol,
sectorsCount: 0 sectorsCount: 0,
tags: []
}; };
} }
); );

6
apps/api/src/app/admin/update-asset-profile.dto.ts

@ -1,6 +1,6 @@
import { IsCurrencyCode } from '@ghostfolio/api/validators/is-currency-code'; import { IsCurrencyCode } from '@ghostfolio/api/validators/is-currency-code';
import { AssetClass, AssetSubClass, Prisma } from '@prisma/client'; import { AssetClass, AssetSubClass, Prisma, Tag } from '@prisma/client';
import { import {
IsArray, IsArray,
IsEnum, IsEnum,
@ -35,6 +35,10 @@ export class UpdateAssetProfileDto {
@IsOptional() @IsOptional()
name?: string; name?: string;
@IsArray()
@IsOptional()
tags?: Tag[];
@IsObject() @IsObject()
@IsOptional() @IsOptional()
scraperConfiguration?: Prisma.InputJsonObject; scraperConfiguration?: Prisma.InputJsonObject;

13
apps/api/src/app/import/import.service.ts

@ -620,18 +620,17 @@ export class ImportService {
)?.[symbol] )?.[symbol]
}; };
if (type === 'BUY' || type === 'DIVIDEND' || type === 'SELL') { if (
type === 'BUY' ||
type === 'DIVIDEND' ||
type === 'SELL' ||
type === 'STAKE'
) {
if (!assetProfile?.name) { if (!assetProfile?.name) {
throw new Error( throw new Error(
`activities.${index}.symbol ("${symbol}") is not valid for the specified data source ("${dataSource}")` `activities.${index}.symbol ("${symbol}") is not valid for the specified data source ("${dataSource}")`
); );
} }
if (assetProfile.currency !== currency) {
throw new Error(
`activities.${index}.currency ("${currency}") does not match with currency of ${assetProfile.symbol} ("${assetProfile.currency}")`
);
}
} }
assetProfiles[getAssetProfileIdentifier({ dataSource, symbol })] = assetProfiles[getAssetProfileIdentifier({ dataSource, symbol })] =

32
apps/api/src/app/order/order.service.ts

@ -297,6 +297,7 @@ export class OrderService {
}); });
} }
@LogPerformance
public async getOrders({ public async getOrders({
endDate, endDate,
filters, filters,
@ -451,13 +452,34 @@ export class OrderService {
} }
if (filtersByTag?.length > 0) { if (filtersByTag?.length > 0) {
where.tags = { where.AND = [
{
OR: [
{
tags: {
some: {
OR: filtersByTag.map(({ id }) => {
return {
id: id
};
})
}
}
},
{
SymbolProfile: {
tags: {
some: { some: {
OR: filtersByTag.map(({ id }) => { OR: filtersByTag.map(({ id }) => {
return { id }; return { id };
}) })
} }
}; }
}
}
]
}
];
} }
if (sortColumn) { if (sortColumn) {
@ -489,7 +511,11 @@ export class OrderService {
} }
}, },
// eslint-disable-next-line @typescript-eslint/naming-convention // eslint-disable-next-line @typescript-eslint/naming-convention
SymbolProfile: true, SymbolProfile: {
include: {
tags: true
}
},
tags: true tags: true
} }
}), }),

598
apps/api/src/app/portfolio/calculator/constantPortfolioReturn/portfolio-calculator.ts

@ -0,0 +1,598 @@
import { Activity } from '@ghostfolio/api/app/order/interfaces/activities.interface';
import { OrderService } from '@ghostfolio/api/app/order/order.service';
import { RedisCacheService } from '@ghostfolio/api/app/redis-cache/redis-cache.service';
import { getFactor } from '@ghostfolio/api/helper/portfolio.helper';
import { LogPerformance } from '@ghostfolio/api/interceptors/performance-logging/performance-logging.interceptor';
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service';
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service';
import { IDataGatheringItem } from '@ghostfolio/api/services/interfaces/interfaces';
import { PortfolioSnapshotService } from '@ghostfolio/api/services/queues/portfolio-snapshot/portfolio-snapshot.service';
import { getIntervalFromDateRange } from '@ghostfolio/common/calculation-helper';
import { DATE_FORMAT, parseDate, resetHours } from '@ghostfolio/common/helper';
import { Filter, HistoricalDataItem } from '@ghostfolio/common/interfaces';
import { DateRange } from '@ghostfolio/common/types';
import { Inject, Logger } from '@nestjs/common';
import { Big } from 'big.js';
import {
addDays,
differenceInDays,
eachDayOfInterval,
endOfDay,
format,
isAfter,
isBefore,
subDays
} from 'date-fns';
import { CurrentRateService } from '../../current-rate.service';
import { DateQuery } from '../../interfaces/date-query.interface';
import { PortfolioOrder } from '../../interfaces/portfolio-order.interface';
import { TWRPortfolioCalculator } from '../twr/portfolio-calculator';
export class CPRPortfolioCalculator extends TWRPortfolioCalculator {
private holdings: { [date: string]: { [symbol: string]: Big } } = {};
private holdingCurrencies: { [symbol: string]: string } = {};
constructor(
{
accountBalanceItems,
activities,
configurationService,
currency,
currentRateService,
exchangeRateDataService,
portfolioSnapshotService,
redisCacheService,
userId,
filters
}: {
accountBalanceItems: HistoricalDataItem[];
activities: Activity[];
configurationService: ConfigurationService;
currency: string;
currentRateService: CurrentRateService;
exchangeRateDataService: ExchangeRateDataService;
portfolioSnapshotService: PortfolioSnapshotService;
redisCacheService: RedisCacheService;
filters: Filter[];
userId: string;
},
@Inject()
private orderService: OrderService
) {
super({
accountBalanceItems,
activities,
configurationService,
currency,
filters,
currentRateService,
exchangeRateDataService,
portfolioSnapshotService,
redisCacheService,
userId
});
}
@LogPerformance
public async getPerformanceWithTimeWeightedReturn({
start,
end
}: {
start: Date;
end: Date;
}): Promise<{ chart: HistoricalDataItem[] }> {
let item = await super.getPerformance({
end,
start
});
let itemResult = item.chart;
let dates = itemResult.map((item) => parseDate(item.date));
let timeWeighted = await this.getTimeWeightedChartData({
dates
});
item.chart = itemResult.map((itemInt) => {
let timeWeightedItem = timeWeighted.find(
(timeWeightedItem) => timeWeightedItem.date === itemInt.date
);
if (timeWeightedItem) {
itemInt.timeWeightedPerformance =
timeWeightedItem.netPerformanceInPercentage;
itemInt.timeWeightedPerformanceWithCurrencyEffect =
timeWeightedItem.netPerformanceInPercentageWithCurrencyEffect;
}
return itemInt;
});
return item;
}
@LogPerformance
public async getUnfilteredNetWorth(currency: string): Promise<Big> {
const activities = await this.orderService.getOrders({
userId: this.userId,
userCurrency: currency,
types: ['BUY', 'SELL', 'STAKE'],
withExcludedAccounts: true
});
const orders = this.activitiesToPortfolioOrder(activities.activities);
const start = orders.reduce(
(date, order) =>
parseDate(date.date).getTime() < parseDate(order.date).getTime()
? date
: order,
{ date: orders[0].date }
).date;
const end = new Date(Date.now());
const holdings = await this.getHoldings(orders, parseDate(start), end);
const marketMap = await this.currentRateService.getValues({
dataGatheringItems: this.mapToDataGatheringItems(orders),
dateQuery: { in: [end] }
});
const endString = format(end, DATE_FORMAT);
let exchangeRates = await Promise.all(
Object.keys(holdings[endString]).map(async (holding) => {
let symbol = marketMap.values.find((m) => m.symbol === holding);
let symbolCurrency = this.getCurrencyFromActivities(orders, holding);
let exchangeRate = await this.exchangeRateDataService.toCurrencyAtDate(
1,
symbolCurrency,
this.currency,
end
);
return { symbolCurrency, exchangeRate };
})
);
let currencyRates = exchangeRates.reduce<{ [currency: string]: number }>(
(all, currency): { [currency: string]: number } => {
all[currency.symbolCurrency] ??= currency.exchangeRate;
return all;
},
{}
);
let totalInvestment = await Object.keys(holdings[endString]).reduce(
(sum, holding) => {
if (!holdings[endString][holding].toNumber()) {
return sum;
}
let symbol = marketMap.values.find((m) => m.symbol === holding);
if (symbol?.marketPrice === undefined) {
Logger.warn(
`Missing historical market data for ${holding} (${end})`,
'PortfolioCalculator'
);
return sum;
} else {
let symbolCurrency = this.getCurrency(holding);
let price = new Big(currencyRates[symbolCurrency]).mul(
symbol.marketPrice
);
return sum.plus(new Big(price).mul(holdings[endString][holding]));
}
},
new Big(0)
);
return totalInvestment;
}
@LogPerformance
protected async getTimeWeightedChartData({
dates
}: {
dates?: Date[];
}): Promise<HistoricalDataItem[]> {
dates = dates.sort((a, b) => a.getTime() - b.getTime());
const start = dates[0];
const end = dates[dates.length - 1];
let marketMapTask = this.computeMarketMap({
gte: start,
lt: addDays(end, 1)
});
const timelineHoldings = await this.getHoldings(
this.activities,
start,
end
);
let data: HistoricalDataItem[] = [];
const startString = format(start, DATE_FORMAT);
data.push({
date: startString,
netPerformanceInPercentage: 0,
netPerformanceInPercentageWithCurrencyEffect: 0,
investmentValueWithCurrencyEffect: 0,
netPerformance: 0,
netPerformanceWithCurrencyEffect: 0,
netWorth: 0,
totalAccountBalance: 0,
totalInvestment: 0,
totalInvestmentValueWithCurrencyEffect: 0,
value: 0,
valueWithCurrencyEffect: 0
});
this.marketMap = await marketMapTask;
let totalInvestment = Object.keys(timelineHoldings[startString]).reduce(
(sum, holding) => {
return sum.plus(
timelineHoldings[startString][holding].mul(
this.marketMap[startString][holding] ?? new Big(0)
)
);
},
new Big(0)
);
let previousNetPerformanceInPercentage = new Big(0);
let previousNetPerformanceInPercentageWithCurrencyEffect = new Big(0);
for (let i = 1; i < dates.length; i++) {
const date = format(dates[i], DATE_FORMAT);
const previousDate = format(dates[i - 1], DATE_FORMAT);
const holdings = timelineHoldings[previousDate];
let newTotalInvestment = new Big(0);
let netPerformanceInPercentage = new Big(0);
let netPerformanceInPercentageWithCurrencyEffect = new Big(0);
for (const holding of Object.keys(holdings)) {
({
netPerformanceInPercentage,
netPerformanceInPercentageWithCurrencyEffect,
newTotalInvestment
} = await this.handleSingleHolding(
previousDate,
holding,
date,
totalInvestment,
timelineHoldings,
netPerformanceInPercentage,
netPerformanceInPercentageWithCurrencyEffect,
newTotalInvestment
));
}
totalInvestment = newTotalInvestment;
previousNetPerformanceInPercentage = previousNetPerformanceInPercentage
.plus(1)
.mul(netPerformanceInPercentage.plus(1))
.minus(1);
previousNetPerformanceInPercentageWithCurrencyEffect =
previousNetPerformanceInPercentageWithCurrencyEffect
.plus(1)
.mul(netPerformanceInPercentageWithCurrencyEffect.plus(1))
.minus(1);
data.push({
date,
netPerformanceInPercentage: previousNetPerformanceInPercentage
.mul(100)
.toNumber(),
netPerformanceInPercentageWithCurrencyEffect:
previousNetPerformanceInPercentageWithCurrencyEffect
.mul(100)
.toNumber()
});
}
return data;
}
@LogPerformance
protected async handleSingleHolding(
previousDate: string,
holding: string,
date: string,
totalInvestment: Big,
timelineHoldings: { [date: string]: { [symbol: string]: Big } },
netPerformanceInPercentage: Big,
netPerformanceInPercentageWithCurrencyEffect: Big,
newTotalInvestment: Big
) {
const previousPrice =
Object.keys(this.marketMap).indexOf(previousDate) > 0
? this.marketMap[previousDate][holding]
: undefined;
const priceDictionary = this.marketMap[date];
let currentPrice =
priceDictionary !== undefined ? priceDictionary[holding] : previousPrice;
currentPrice ??= previousPrice;
const previousHolding = timelineHoldings[previousDate][holding];
const priceInBaseCurrency = currentPrice
? new Big(
await this.exchangeRateDataService.toCurrencyAtDate(
currentPrice?.toNumber() ?? 0,
this.getCurrency(holding),
this.currency,
parseDate(date)
)
)
: new Big(0);
if (previousHolding.eq(0)) {
return {
netPerformanceInPercentage: netPerformanceInPercentage,
netPerformanceInPercentageWithCurrencyEffect:
netPerformanceInPercentageWithCurrencyEffect,
newTotalInvestment: newTotalInvestment.plus(
timelineHoldings[date][holding].mul(priceInBaseCurrency)
)
};
}
if (previousPrice === undefined || currentPrice === undefined) {
Logger.warn(
`Missing historical market data for ${holding} (${previousPrice === undefined ? previousDate : date}})`,
'PortfolioCalculator'
);
return {
netPerformanceInPercentage: netPerformanceInPercentage,
netPerformanceInPercentageWithCurrencyEffect:
netPerformanceInPercentageWithCurrencyEffect,
newTotalInvestment: newTotalInvestment.plus(
timelineHoldings[date][holding].mul(priceInBaseCurrency)
)
};
}
const previousPriceInBaseCurrency = previousPrice
? new Big(
await this.exchangeRateDataService.toCurrencyAtDate(
previousPrice?.toNumber() ?? 0,
this.getCurrency(holding),
this.currency,
parseDate(previousDate)
)
)
: new Big(0);
const portfolioWeight = totalInvestment.toNumber()
? previousHolding.mul(previousPriceInBaseCurrency).div(totalInvestment)
: new Big(0);
netPerformanceInPercentage = netPerformanceInPercentage.plus(
currentPrice.div(previousPrice).minus(1).mul(portfolioWeight)
);
netPerformanceInPercentageWithCurrencyEffect =
netPerformanceInPercentageWithCurrencyEffect.plus(
priceInBaseCurrency
.div(previousPriceInBaseCurrency)
.minus(1)
.mul(portfolioWeight)
);
newTotalInvestment = newTotalInvestment.plus(
timelineHoldings[date][holding].mul(priceInBaseCurrency)
);
return {
netPerformanceInPercentage,
netPerformanceInPercentageWithCurrencyEffect,
newTotalInvestment
};
}
@LogPerformance
protected getCurrency(symbol: string) {
return this.getCurrencyFromActivities(this.activities, symbol);
}
@LogPerformance
protected getCurrencyFromActivities(
activities: PortfolioOrder[],
symbol: string
) {
if (!this.holdingCurrencies[symbol]) {
this.holdingCurrencies[symbol] = activities.find(
(a) => a.SymbolProfile.symbol === symbol
).SymbolProfile.currency;
}
return this.holdingCurrencies[symbol];
}
@LogPerformance
protected async getHoldings(
activities: PortfolioOrder[],
start: Date,
end: Date
) {
if (
this.holdings &&
Object.keys(this.holdings).some((h) =>
isAfter(parseDate(h), subDays(end, 1))
) &&
Object.keys(this.holdings).some((h) =>
isBefore(parseDate(h), addDays(start, 1))
)
) {
return this.holdings;
}
this.computeHoldings(activities, start, end);
return this.holdings;
}
@LogPerformance
protected async computeHoldings(
activities: PortfolioOrder[],
start: Date,
end: Date
) {
const investmentByDate = this.getInvestmentByDate(activities);
this.calculateHoldings(investmentByDate, start, end);
}
private calculateHoldings(
investmentByDate: { [date: string]: PortfolioOrder[] },
start: Date,
end: Date
) {
const transactionDates = Object.keys(investmentByDate).sort();
let dates = eachDayOfInterval({ start, end }, { step: 1 })
.map((date) => {
return resetHours(date);
})
.sort((a, b) => a.getTime() - b.getTime());
let currentHoldings: { [date: string]: { [symbol: string]: Big } } = {};
this.calculateInitialHoldings(investmentByDate, start, currentHoldings);
for (let i = 1; i < dates.length; i++) {
const dateString = format(dates[i], DATE_FORMAT);
const previousDateString = format(dates[i - 1], DATE_FORMAT);
if (transactionDates.some((d) => d === dateString)) {
let holdings = { ...currentHoldings[previousDateString] };
investmentByDate[dateString].forEach((trade) => {
holdings[trade.SymbolProfile.symbol] ??= new Big(0);
holdings[trade.SymbolProfile.symbol] = holdings[
trade.SymbolProfile.symbol
].plus(trade.quantity.mul(getFactor(trade.type)));
});
currentHoldings[dateString] = holdings;
} else {
currentHoldings[dateString] = currentHoldings[previousDateString];
}
}
this.holdings = currentHoldings;
}
@LogPerformance
protected calculateInitialHoldings(
investmentByDate: { [date: string]: PortfolioOrder[] },
start: Date,
currentHoldings: { [date: string]: { [symbol: string]: Big } }
) {
const preRangeTrades = Object.keys(investmentByDate)
.filter((date) => resetHours(new Date(date)) <= start)
.map((date) => investmentByDate[date])
.reduce((a, b) => a.concat(b), [])
.reduce((groupBySymbol, trade) => {
if (!groupBySymbol[trade.SymbolProfile.symbol]) {
groupBySymbol[trade.SymbolProfile.symbol] = [];
}
groupBySymbol[trade.SymbolProfile.symbol].push(trade);
return groupBySymbol;
}, {});
currentHoldings[format(start, DATE_FORMAT)] = {};
for (const symbol of Object.keys(preRangeTrades)) {
const trades: PortfolioOrder[] = preRangeTrades[symbol];
let startQuantity = trades.reduce((sum, trade) => {
return sum.plus(trade.quantity.mul(getFactor(trade.type)));
}, new Big(0));
currentHoldings[format(start, DATE_FORMAT)][symbol] = startQuantity;
}
}
@LogPerformance
protected getInvestmentByDate(activities: PortfolioOrder[]): {
[date: string]: PortfolioOrder[];
} {
return activities.reduce((groupedByDate, order) => {
if (!groupedByDate[order.date]) {
groupedByDate[order.date] = [];
}
groupedByDate[order.date].push(order);
return groupedByDate;
}, {});
}
@LogPerformance
protected mapToDataGatheringItems(
orders: PortfolioOrder[]
): IDataGatheringItem[] {
return orders
.map((activity) => {
return {
symbol: activity.SymbolProfile.symbol,
dataSource: activity.SymbolProfile.dataSource
};
})
.filter(
(gathering, i, arr) =>
arr.findIndex((t) => t.symbol === gathering.symbol) === i
);
}
@LogPerformance
protected async computeMarketMap(dateQuery: DateQuery): Promise<{
[date: string]: { [symbol: string]: Big };
}> {
const dataGatheringItems: IDataGatheringItem[] =
this.mapToDataGatheringItems(this.activities);
const { values: marketSymbols } = await this.currentRateService.getValues({
dataGatheringItems,
dateQuery
});
const marketSymbolMap: {
[date: string]: { [symbol: string]: Big };
} = {};
for (const marketSymbol of marketSymbols) {
const date = format(marketSymbol.date, DATE_FORMAT);
if (!marketSymbolMap[date]) {
marketSymbolMap[date] = {};
}
if (marketSymbol.marketPrice) {
marketSymbolMap[date][marketSymbol.symbol] = new Big(
marketSymbol.marketPrice
);
}
}
return marketSymbolMap;
}
@LogPerformance
protected activitiesToPortfolioOrder(
activities: Activity[]
): PortfolioOrder[] {
return activities
.map(
({
date,
fee,
quantity,
SymbolProfile,
tags = [],
type,
unitPrice
}) => {
if (isAfter(date, new Date(Date.now()))) {
// Adapt date to today if activity is in future (e.g. liability)
// to include it in the interval
date = endOfDay(new Date(Date.now()));
}
return {
SymbolProfile,
tags,
type,
date: format(date, DATE_FORMAT),
fee: new Big(fee),
quantity: new Big(quantity),
unitPrice: new Big(unitPrice)
};
}
)
.sort((a, b) => {
return a.date?.localeCompare(b.date);
});
}
}

37
apps/api/src/app/portfolio/calculator/portfolio-calculator.factory.ts

@ -1,6 +1,7 @@
import { Activity } from '@ghostfolio/api/app/order/interfaces/activities.interface'; import { Activity } from '@ghostfolio/api/app/order/interfaces/activities.interface';
import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service'; import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service';
import { RedisCacheService } from '@ghostfolio/api/app/redis-cache/redis-cache.service'; import { RedisCacheService } from '@ghostfolio/api/app/redis-cache/redis-cache.service';
import { LogPerformance } from '@ghostfolio/api/interceptors/performance-logging/performance-logging.interceptor';
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service';
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 { PortfolioSnapshotService } from '@ghostfolio/api/services/queues/portfolio-snapshot/portfolio-snapshot.service'; import { PortfolioSnapshotService } from '@ghostfolio/api/services/queues/portfolio-snapshot/portfolio-snapshot.service';
@ -8,13 +9,16 @@ import { Filter, HistoricalDataItem } from '@ghostfolio/common/interfaces';
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { OrderService } from '../../order/order.service';
import { CPRPortfolioCalculator } from './constantPortfolioReturn/portfolio-calculator';
import { MWRPortfolioCalculator } from './mwr/portfolio-calculator'; import { MWRPortfolioCalculator } from './mwr/portfolio-calculator';
import { PortfolioCalculator } from './portfolio-calculator'; import { PortfolioCalculator } from './portfolio-calculator';
import { TWRPortfolioCalculator } from './twr/portfolio-calculator'; import { TWRPortfolioCalculator } from './twr/portfolio-calculator';
export enum PerformanceCalculationType { export enum PerformanceCalculationType {
MWR = 'MWR', // Money-Weighted Rate of Return MWR = 'MWR', // Money-Weighted Rate of Return
TWR = 'TWR' // Time-Weighted Rate of Return TWR = 'TWR', // Time-Weighted Rate of Return
CPR = 'CPR' // Constant Portfolio Rate of Return
} }
@Injectable() @Injectable()
@ -24,9 +28,11 @@ export class PortfolioCalculatorFactory {
private readonly currentRateService: CurrentRateService, private readonly currentRateService: CurrentRateService,
private readonly exchangeRateDataService: ExchangeRateDataService, private readonly exchangeRateDataService: ExchangeRateDataService,
private readonly portfolioSnapshotService: PortfolioSnapshotService, private readonly portfolioSnapshotService: PortfolioSnapshotService,
private readonly redisCacheService: RedisCacheService private readonly redisCacheService: RedisCacheService,
private readonly orderService: OrderService
) {} ) {}
@LogPerformance
public createCalculator({ public createCalculator({
accountBalanceItems = [], accountBalanceItems = [],
activities, activities,
@ -57,18 +63,37 @@ export class PortfolioCalculatorFactory {
redisCacheService: this.redisCacheService redisCacheService: this.redisCacheService
}); });
case PerformanceCalculationType.TWR: case PerformanceCalculationType.TWR:
return new TWRPortfolioCalculator({ return new CPRPortfolioCalculator(
{
accountBalanceItems, accountBalanceItems,
activities, activities,
currency, currency,
currentRateService: this.currentRateService, currentRateService: this.currentRateService,
filters,
userId, userId,
configurationService: this.configurationService, configurationService: this.configurationService,
exchangeRateDataService: this.exchangeRateDataService, exchangeRateDataService: this.exchangeRateDataService,
portfolioSnapshotService: this.portfolioSnapshotService, portfolioSnapshotService: this.portfolioSnapshotService,
redisCacheService: this.redisCacheService redisCacheService: this.redisCacheService,
}); filters
},
this.orderService
);
case PerformanceCalculationType.CPR:
return new CPRPortfolioCalculator(
{
accountBalanceItems,
activities,
currency,
currentRateService: this.currentRateService,
userId,
configurationService: this.configurationService,
exchangeRateDataService: this.exchangeRateDataService,
portfolioSnapshotService: this.portfolioSnapshotService,
redisCacheService: this.redisCacheService,
filters
},
this.orderService
);
default: default:
throw new Error('Invalid calculation type'); throw new Error('Invalid calculation type');
} }

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

@ -57,12 +57,12 @@ export abstract class PortfolioCalculator {
protected accountBalanceItems: HistoricalDataItem[]; protected accountBalanceItems: HistoricalDataItem[];
protected activities: PortfolioOrder[]; protected activities: PortfolioOrder[];
private configurationService: ConfigurationService; protected configurationService: ConfigurationService;
private currency: string; protected currency: string;
private currentRateService: CurrentRateService; protected currentRateService: CurrentRateService;
private dataProviderInfos: DataProviderInfo[]; private dataProviderInfos: DataProviderInfo[];
private endDate: Date; private endDate: Date;
private exchangeRateDataService: ExchangeRateDataService; protected exchangeRateDataService: ExchangeRateDataService;
private filters: Filter[]; private filters: Filter[];
private portfolioSnapshotService: PortfolioSnapshotService; private portfolioSnapshotService: PortfolioSnapshotService;
private redisCacheService: RedisCacheService; private redisCacheService: RedisCacheService;
@ -70,7 +70,8 @@ export abstract class PortfolioCalculator {
private snapshotPromise: Promise<void>; private snapshotPromise: Promise<void>;
private startDate: Date; private startDate: Date;
private transactionPoints: TransactionPoint[]; private transactionPoints: TransactionPoint[];
private userId: string; protected userId: string;
protected marketMap: { [date: string]: { [symbol: string]: Big } } = {};
public constructor({ public constructor({
accountBalanceItems, accountBalanceItems,
@ -620,10 +621,12 @@ export abstract class PortfolioCalculator {
}; };
} }
@LogPerformance
public getDataProviderInfos() { public getDataProviderInfos() {
return this.dataProviderInfos; return this.dataProviderInfos;
} }
@LogPerformance
public async getDividendInBaseCurrency() { public async getDividendInBaseCurrency() {
await this.snapshotPromise; await this.snapshotPromise;
@ -634,18 +637,21 @@ export abstract class PortfolioCalculator {
); );
} }
@LogPerformance
public async getFeesInBaseCurrency() { public async getFeesInBaseCurrency() {
await this.snapshotPromise; await this.snapshotPromise;
return this.snapshot.totalFeesWithCurrencyEffect; return this.snapshot.totalFeesWithCurrencyEffect;
} }
@LogPerformance
public async getInterestInBaseCurrency() { public async getInterestInBaseCurrency() {
await this.snapshotPromise; await this.snapshotPromise;
return this.snapshot.totalInterestWithCurrencyEffect; return this.snapshot.totalInterestWithCurrencyEffect;
} }
@LogPerformance
public getInvestments(): { date: string; investment: Big }[] { public getInvestments(): { date: string; investment: Big }[] {
if (this.transactionPoints.length === 0) { if (this.transactionPoints.length === 0) {
return []; return [];
@ -663,6 +669,7 @@ export abstract class PortfolioCalculator {
}); });
} }
@LogPerformance
public getInvestmentsByGroup({ public getInvestmentsByGroup({
data, data,
groupBy groupBy
@ -686,12 +693,14 @@ export abstract class PortfolioCalculator {
})); }));
} }
@LogPerformance
public async getLiabilitiesInBaseCurrency() { public async getLiabilitiesInBaseCurrency() {
await this.snapshotPromise; await this.snapshotPromise;
return this.snapshot.totalLiabilitiesWithCurrencyEffect; return this.snapshot.totalLiabilitiesWithCurrencyEffect;
} }
@LogPerformance
public async getPerformance({ end, start }) { public async getPerformance({ end, start }) {
await this.snapshotPromise; await this.snapshotPromise;
@ -760,6 +769,7 @@ export abstract class PortfolioCalculator {
return { chart }; return { chart };
} }
@LogPerformance
public async getSnapshot() { public async getSnapshot() {
await this.snapshotPromise; await this.snapshotPromise;
@ -815,6 +825,7 @@ export abstract class PortfolioCalculator {
return this.transactionPoints; return this.transactionPoints;
} }
@LogPerformance
public async getValuablesInBaseCurrency() { public async getValuablesInBaseCurrency() {
await this.snapshotPromise; await this.snapshotPromise;
@ -890,7 +901,7 @@ export abstract class PortfolioCalculator {
} }
@LogPerformance @LogPerformance
private computeTransactionPoints() { protected computeTransactionPoints() {
this.transactionPoints = []; this.transactionPoints = [];
const symbols: { [symbol: string]: TransactionPointSymbol } = {}; const symbols: { [symbol: string]: TransactionPointSymbol } = {};
@ -1029,7 +1040,7 @@ export abstract class PortfolioCalculator {
} }
@LogPerformance @LogPerformance
private async initialize() { protected async initialize() {
const startTimeTotal = performance.now(); const startTimeTotal = performance.now();
let cachedPortfolioSnapshot: PortfolioSnapshot; let cachedPortfolioSnapshot: PortfolioSnapshot;

3
apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-baln-buy-and-sell-in-two-activities.spec.ts

@ -80,7 +80,8 @@ describe('PortfolioCalculator', () => {
currentRateService, currentRateService,
exchangeRateDataService, exchangeRateDataService,
portfolioSnapshotService, portfolioSnapshotService,
redisCacheService redisCacheService,
null
); );
}); });

3
apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-baln-buy-and-sell.spec.ts

@ -80,7 +80,8 @@ describe('PortfolioCalculator', () => {
currentRateService, currentRateService,
exchangeRateDataService, exchangeRateDataService,
portfolioSnapshotService, portfolioSnapshotService,
redisCacheService redisCacheService,
null
); );
}); });

3
apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-baln-buy.spec.ts

@ -80,7 +80,8 @@ describe('PortfolioCalculator', () => {
currentRateService, currentRateService,
exchangeRateDataService, exchangeRateDataService,
portfolioSnapshotService, portfolioSnapshotService,
redisCacheService redisCacheService,
null
); );
}); });

3
apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-btcusd-buy-and-sell-partially.spec.ts

@ -93,7 +93,8 @@ describe('PortfolioCalculator', () => {
currentRateService, currentRateService,
exchangeRateDataService, exchangeRateDataService,
portfolioSnapshotService, portfolioSnapshotService,
redisCacheService redisCacheService,
null
); );
}); });

3
apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-fee.spec.ts

@ -80,7 +80,8 @@ describe('PortfolioCalculator', () => {
currentRateService, currentRateService,
exchangeRateDataService, exchangeRateDataService,
portfolioSnapshotService, portfolioSnapshotService,
redisCacheService redisCacheService,
null
); );
}); });

3
apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-googl-buy.spec.ts

@ -93,7 +93,8 @@ describe('PortfolioCalculator', () => {
currentRateService, currentRateService,
exchangeRateDataService, exchangeRateDataService,
portfolioSnapshotService, portfolioSnapshotService,
redisCacheService redisCacheService,
null
); );
}); });

3
apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-item.spec.ts

@ -80,7 +80,8 @@ describe('PortfolioCalculator', () => {
currentRateService, currentRateService,
exchangeRateDataService, exchangeRateDataService,
portfolioSnapshotService, portfolioSnapshotService,
redisCacheService redisCacheService,
null
); );
}); });

3
apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-liability.spec.ts

@ -79,7 +79,8 @@ describe('PortfolioCalculator', () => {
currentRateService, currentRateService,
exchangeRateDataService, exchangeRateDataService,
portfolioSnapshotService, portfolioSnapshotService,
redisCacheService redisCacheService,
null
); );
}); });

3
apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-msft-buy-with-dividend.spec.ts

@ -93,7 +93,8 @@ describe('PortfolioCalculator', () => {
currentRateService, currentRateService,
exchangeRateDataService, exchangeRateDataService,
portfolioSnapshotService, portfolioSnapshotService,
redisCacheService redisCacheService,
null
); );
}); });

3
apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-no-orders.spec.ts

@ -74,7 +74,8 @@ describe('PortfolioCalculator', () => {
currentRateService, currentRateService,
exchangeRateDataService, exchangeRateDataService,
portfolioSnapshotService, portfolioSnapshotService,
redisCacheService redisCacheService,
null
); );
}); });

3
apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-novn-buy-and-sell-partially.spec.ts

@ -80,7 +80,8 @@ describe('PortfolioCalculator', () => {
currentRateService, currentRateService,
exchangeRateDataService, exchangeRateDataService,
portfolioSnapshotService, portfolioSnapshotService,
redisCacheService redisCacheService,
null
); );
}); });

3
apps/api/src/app/portfolio/calculator/twr/portfolio-calculator-novn-buy-and-sell.spec.ts

@ -80,7 +80,8 @@ describe('PortfolioCalculator', () => {
currentRateService, currentRateService,
exchangeRateDataService, exchangeRateDataService,
portfolioSnapshotService, portfolioSnapshotService,
redisCacheService redisCacheService,
null
); );
}); });

3
apps/api/src/app/portfolio/calculator/twr/portfolio-calculator.spec.ts

@ -34,7 +34,8 @@ describe('PortfolioCalculator', () => {
currentRateService, currentRateService,
exchangeRateDataService, exchangeRateDataService,
portfolioSnapshotService, portfolioSnapshotService,
redisCacheService redisCacheService,
null
); );
}); });

17
apps/api/src/app/portfolio/calculator/twr/portfolio-calculator.ts

@ -203,6 +203,8 @@ export class TWRPortfolioCalculator extends PortfolioCalculator {
investmentValuesWithCurrencyEffect: {}, investmentValuesWithCurrencyEffect: {},
netPerformance: new Big(0), netPerformance: new Big(0),
netPerformancePercentage: new Big(0), netPerformancePercentage: new Big(0),
netPerformanceValuesPercentage: {},
unitPrices: {},
netPerformancePercentageWithCurrencyEffectMap: {}, netPerformancePercentageWithCurrencyEffectMap: {},
netPerformanceValues: {}, netPerformanceValues: {},
netPerformanceValuesWithCurrencyEffect: {}, netPerformanceValuesWithCurrencyEffect: {},
@ -271,7 +273,9 @@ export class TWRPortfolioCalculator extends PortfolioCalculator {
totalLiabilities: new Big(0), totalLiabilities: new Big(0),
totalLiabilitiesInBaseCurrency: new Big(0), totalLiabilitiesInBaseCurrency: new Big(0),
totalValuables: new Big(0), totalValuables: new Big(0),
totalValuablesInBaseCurrency: new Big(0) totalValuablesInBaseCurrency: new Big(0),
netPerformanceValuesPercentage: {},
unitPrices: {}
}; };
} }
@ -499,6 +503,13 @@ export class TWRPortfolioCalculator extends PortfolioCalculator {
.mul(order.quantity) .mul(order.quantity)
.mul(getFactor(order.type)); .mul(getFactor(order.type));
} }
} else if (order.type === 'STAKE') {
transactionInvestment = new Big(0);
transactionInvestmentWithCurrencyEffect = new Big(0);
totalQuantityFromBuyTransactions =
totalQuantityFromBuyTransactions.plus(order.quantity);
} }
if (PortfolioCalculator.ENABLE_LOGGING) { if (PortfolioCalculator.ENABLE_LOGGING) {
@ -958,7 +969,9 @@ export class TWRPortfolioCalculator extends PortfolioCalculator {
timeWeightedInvestment: timeWeightedInvestment:
timeWeightedAverageInvestmentBetweenStartAndEndDate, timeWeightedAverageInvestmentBetweenStartAndEndDate,
timeWeightedInvestmentWithCurrencyEffect: timeWeightedInvestmentWithCurrencyEffect:
timeWeightedAverageInvestmentBetweenStartAndEndDateWithCurrencyEffect timeWeightedAverageInvestmentBetweenStartAndEndDateWithCurrencyEffect,
netPerformanceValuesPercentage: {},
unitPrices: {}
}; };
} }
} }

1
apps/api/src/app/portfolio/interfaces/portfolio-holding-detail.interface.ts

@ -11,6 +11,7 @@ export interface PortfolioHoldingDetail {
averagePrice: number; averagePrice: number;
dataProviderInfo: DataProviderInfo; dataProviderInfo: DataProviderInfo;
dividendInBaseCurrency: number; dividendInBaseCurrency: number;
stakeRewards: number;
dividendYieldPercent: number; dividendYieldPercent: number;
dividendYieldPercentWithCurrencyEffect: number; dividendYieldPercentWithCurrencyEffect: number;
feeInBaseCurrency: number; feeInBaseCurrency: number;

5
apps/api/src/app/portfolio/interfaces/portfolio-order-item.interface.ts

@ -10,3 +10,8 @@ export interface PortfolioOrderItem extends PortfolioOrder {
unitPriceInBaseCurrency?: Big; unitPriceInBaseCurrency?: Big;
unitPriceInBaseCurrencyWithCurrencyEffect?: Big; unitPriceInBaseCurrencyWithCurrencyEffect?: Big;
} }
export interface WithCurrencyEffect<T> {
Value: T;
WithCurrencyEffect: T;
}

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

@ -6,7 +6,10 @@ import {
hasNotDefinedValuesInObject, hasNotDefinedValuesInObject,
nullifyValuesInObject nullifyValuesInObject
} from '@ghostfolio/api/helper/object.helper'; } from '@ghostfolio/api/helper/object.helper';
import { PerformanceLoggingInterceptor } from '@ghostfolio/api/interceptors/performance-logging/performance-logging.interceptor'; import {
LogPerformance,
PerformanceLoggingInterceptor
} from '@ghostfolio/api/interceptors/performance-logging/performance-logging.interceptor';
import { RedactValuesInResponseInterceptor } from '@ghostfolio/api/interceptors/redact-values-in-response/redact-values-in-response.interceptor'; import { RedactValuesInResponseInterceptor } from '@ghostfolio/api/interceptors/redact-values-in-response/redact-values-in-response.interceptor';
import { TransformDataSourceInRequestInterceptor } from '@ghostfolio/api/interceptors/transform-data-source-in-request/transform-data-source-in-request.interceptor'; import { TransformDataSourceInRequestInterceptor } from '@ghostfolio/api/interceptors/transform-data-source-in-request/transform-data-source-in-request.interceptor';
import { TransformDataSourceInResponseInterceptor } from '@ghostfolio/api/interceptors/transform-data-source-in-response/transform-data-source-in-response.interceptor'; import { TransformDataSourceInResponseInterceptor } from '@ghostfolio/api/interceptors/transform-data-source-in-response/transform-data-source-in-response.interceptor';
@ -80,6 +83,7 @@ export class PortfolioController {
@Query('assetClasses') filterByAssetClasses?: string, @Query('assetClasses') filterByAssetClasses?: string,
@Query('range') dateRange: DateRange = 'max', @Query('range') dateRange: DateRange = 'max',
@Query('tags') filterByTags?: string, @Query('tags') filterByTags?: string,
@Query('isAllocation') isAllocation: boolean = false,
@Query('withMarkets') withMarketsParam = 'false' @Query('withMarkets') withMarketsParam = 'false'
): Promise<PortfolioDetails & { hasError: boolean }> { ): Promise<PortfolioDetails & { hasError: boolean }> {
const withMarkets = withMarketsParam === 'true'; const withMarkets = withMarketsParam === 'true';
@ -145,6 +149,24 @@ export class PortfolioController {
portfolioPosition.investment / totalInvestment; portfolioPosition.investment / totalInvestment;
portfolioPosition.valueInPercentage = portfolioPosition.valueInPercentage =
portfolioPosition.valueInBaseCurrency / totalValue; portfolioPosition.valueInBaseCurrency / totalValue;
(portfolioPosition.assetClass = hasDetails
? portfolioPosition.assetClass
: undefined),
(portfolioPosition.assetSubClass = hasDetails
? portfolioPosition.assetSubClass
: undefined),
(portfolioPosition.countries = hasDetails
? portfolioPosition.countries
: []),
(portfolioPosition.currency = hasDetails
? portfolioPosition.currency
: undefined),
(portfolioPosition.markets = hasDetails
? portfolioPosition.markets
: undefined),
(portfolioPosition.sectors = hasDetails
? portfolioPosition.sectors
: []);
} }
for (const [name, { valueInBaseCurrency }] of Object.entries(accounts)) { for (const [name, { valueInBaseCurrency }] of Object.entries(accounts)) {
@ -386,16 +408,17 @@ export class PortfolioController {
@UseInterceptors(PerformanceLoggingInterceptor) @UseInterceptors(PerformanceLoggingInterceptor)
@UseInterceptors(TransformDataSourceInResponseInterceptor) @UseInterceptors(TransformDataSourceInResponseInterceptor)
@Version('2') @Version('2')
@LogPerformance
public async getPerformanceV2( public async getPerformanceV2(
@Headers(HEADER_KEY_IMPERSONATION.toLowerCase()) impersonationId: string, @Headers(HEADER_KEY_IMPERSONATION.toLowerCase()) impersonationId: string,
@Query('accounts') filterByAccounts?: string, @Query('accounts') filterByAccounts?: string,
@Query('assetClasses') filterByAssetClasses?: string, @Query('assetClasses') filterByAssetClasses?: string,
@Query('range') dateRange: DateRange = 'max', @Query('range') dateRange: DateRange = 'max',
@Query('tags') filterByTags?: string, @Query('tags') filterByTags?: string,
@Query('withExcludedAccounts') withExcludedAccountsParam = 'false' @Query('withExcludedAccounts') withExcludedAccounts = false,
@Query('timeWeightedPerformance') calculateTimeWeightedPerformance = false,
@Query('withItems') withItems = false
): Promise<PortfolioPerformanceResponse> { ): Promise<PortfolioPerformanceResponse> {
const withExcludedAccounts = withExcludedAccountsParam === 'true';
const filters = this.apiService.buildFiltersFromQueryParams({ const filters = this.apiService.buildFiltersFromQueryParams({
filterByAccounts, filterByAccounts,
filterByAssetClasses, filterByAssetClasses,
@ -407,7 +430,8 @@ export class PortfolioController {
filters, filters,
impersonationId, impersonationId,
withExcludedAccounts, withExcludedAccounts,
userId: this.request.user.id userId: this.request.user.id,
calculateTimeWeightedPerformance
}); });
if ( if (

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

@ -5,6 +5,7 @@ import { Activity } from '@ghostfolio/api/app/order/interfaces/activities.interf
import { OrderService } from '@ghostfolio/api/app/order/order.service'; import { OrderService } from '@ghostfolio/api/app/order/order.service';
import { UserService } from '@ghostfolio/api/app/user/user.service'; import { UserService } from '@ghostfolio/api/app/user/user.service';
import { getFactor } from '@ghostfolio/api/helper/portfolio.helper'; import { getFactor } from '@ghostfolio/api/helper/portfolio.helper';
import { LogPerformance } from '@ghostfolio/api/interceptors/performance-logging/performance-logging.interceptor';
import { AccountClusterRiskCurrentInvestment } from '@ghostfolio/api/models/rules/account-cluster-risk/current-investment'; import { AccountClusterRiskCurrentInvestment } from '@ghostfolio/api/models/rules/account-cluster-risk/current-investment';
import { AccountClusterRiskSingleAccount } from '@ghostfolio/api/models/rules/account-cluster-risk/single-account'; import { AccountClusterRiskSingleAccount } from '@ghostfolio/api/models/rules/account-cluster-risk/single-account';
import { CurrencyClusterRiskBaseCurrencyCurrentInvestment } from '@ghostfolio/api/models/rules/currency-cluster-risk/base-currency-current-investment'; import { CurrencyClusterRiskBaseCurrencyCurrentInvestment } from '@ghostfolio/api/models/rules/currency-cluster-risk/base-currency-current-investment';
@ -14,6 +15,7 @@ import { FeeRatioInitialInvestment } from '@ghostfolio/api/models/rules/fees/fee
import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service'; import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service';
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 { ImpersonationService } from '@ghostfolio/api/services/impersonation/impersonation.service'; import { ImpersonationService } from '@ghostfolio/api/services/impersonation/impersonation.service';
import { IDataProviderResponse } from '@ghostfolio/api/services/interfaces/interfaces';
import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service'; import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service';
import { import {
getAnnualizedPerformancePercent, getAnnualizedPerformancePercent,
@ -75,6 +77,7 @@ import {
} from 'date-fns'; } from 'date-fns';
import { isEmpty, last, uniq } from 'lodash'; import { isEmpty, last, uniq } from 'lodash';
import { CPRPortfolioCalculator } from './calculator/constantPortfolioReturn/portfolio-calculator';
import { PortfolioCalculator } from './calculator/portfolio-calculator'; import { PortfolioCalculator } from './calculator/portfolio-calculator';
import { import {
PerformanceCalculationType, PerformanceCalculationType,
@ -104,6 +107,7 @@ export class PortfolioService {
private readonly userService: UserService private readonly userService: UserService
) {} ) {}
@LogPerformance
public async getAccounts({ public async getAccounts({
filters, filters,
userId, userId,
@ -194,6 +198,7 @@ export class PortfolioService {
}); });
} }
@LogPerformance
public async getAccountsWithAggregations({ public async getAccountsWithAggregations({
filters, filters,
userId, userId,
@ -230,6 +235,7 @@ export class PortfolioService {
}; };
} }
@LogPerformance
public async getDividends({ public async getDividends({
activities, activities,
groupBy groupBy
@ -251,6 +257,7 @@ export class PortfolioService {
return dividends; return dividends;
} }
@LogPerformance
public async getInvestments({ public async getInvestments({
dateRange, dateRange,
filters, filters,
@ -327,6 +334,7 @@ export class PortfolioService {
}; };
} }
@LogPerformance
public async getDetails({ public async getDetails({
dateRange = 'max', dateRange = 'max',
filters, filters,
@ -608,6 +616,80 @@ export class PortfolioService {
}; };
} }
@LogPerformance
private calculateMarketsAllocation(
symbolProfile: EnhancedSymbolProfile,
markets: {
developedMarkets: number;
emergingMarkets: number;
otherMarkets: number;
},
marketsAdvanced: {
asiaPacific: number;
emergingMarkets: number;
europe: number;
japan: number;
northAmerica: number;
otherMarkets: number;
},
value: Big
) {
if (symbolProfile.countries.length > 0) {
for (const country of symbolProfile.countries) {
if (developedMarkets.includes(country.code)) {
markets.developedMarkets = new Big(markets.developedMarkets)
.plus(country.weight)
.toNumber();
} else if (emergingMarkets.includes(country.code)) {
markets.emergingMarkets = new Big(markets.emergingMarkets)
.plus(country.weight)
.toNumber();
} else {
markets.otherMarkets = new Big(markets.otherMarkets)
.plus(country.weight)
.toNumber();
}
if (country.code === 'JP') {
marketsAdvanced.japan = new Big(marketsAdvanced.japan)
.plus(country.weight)
.toNumber();
} else if (country.code === 'CA' || country.code === 'US') {
marketsAdvanced.northAmerica = new Big(marketsAdvanced.northAmerica)
.plus(country.weight)
.toNumber();
} else if (asiaPacificMarkets.includes(country.code)) {
marketsAdvanced.asiaPacific = new Big(marketsAdvanced.asiaPacific)
.plus(country.weight)
.toNumber();
} else if (emergingMarkets.includes(country.code)) {
marketsAdvanced.emergingMarkets = new Big(
marketsAdvanced.emergingMarkets
)
.plus(country.weight)
.toNumber();
} else if (europeMarkets.includes(country.code)) {
marketsAdvanced.europe = new Big(marketsAdvanced.europe)
.plus(country.weight)
.toNumber();
} else {
marketsAdvanced.otherMarkets = new Big(marketsAdvanced.otherMarkets)
.plus(country.weight)
.toNumber();
}
}
} else {
markets[UNKNOWN_KEY] = new Big(markets[UNKNOWN_KEY])
.plus(value)
.toNumber();
marketsAdvanced[UNKNOWN_KEY] = new Big(marketsAdvanced[UNKNOWN_KEY])
.plus(value)
.toNumber();
}
}
@LogPerformance
public async getPosition( public async getPosition(
aDataSource: DataSource, aDataSource: DataSource,
aImpersonationId: string, aImpersonationId: string,
@ -627,6 +709,7 @@ export class PortfolioService {
return { return {
averagePrice: undefined, averagePrice: undefined,
dataProviderInfo: undefined, dataProviderInfo: undefined,
stakeRewards: undefined,
dividendInBaseCurrency: undefined, dividendInBaseCurrency: undefined,
dividendYieldPercent: undefined, dividendYieldPercent: undefined,
dividendYieldPercentWithCurrencyEffect: undefined, dividendYieldPercentWithCurrencyEffect: undefined,
@ -717,6 +800,33 @@ export class PortfolioService {
) )
}); });
const stakeRewards = getSum(
activities
.filter(({ type }) => {
return type === 'STAKE';
})
.map(({ quantity }) => {
return new Big(quantity);
})
);
// Convert investment, gross and net performance to currency of user
const investment = this.exchangeRateDataService.toCurrency(
position.investment?.toNumber(),
currency,
userCurrency
);
const grossPerformance = this.exchangeRateDataService.toCurrency(
position.grossPerformance?.toNumber(),
currency,
userCurrency
);
const netPerformance = this.exchangeRateDataService.toCurrency(
position.netPerformance?.toNumber(),
currency,
userCurrency
);
const historicalData = await this.dataProviderService.getHistorical( const historicalData = await this.dataProviderService.getHistorical(
[{ dataSource, symbol: aSymbol }], [{ dataSource, symbol: aSymbol }],
'day', 'day',
@ -787,6 +897,7 @@ export class PortfolioService {
transactionCount, transactionCount,
averagePrice: averagePrice.toNumber(), averagePrice: averagePrice.toNumber(),
dataProviderInfo: portfolioCalculator.getDataProviderInfos()?.[0], dataProviderInfo: portfolioCalculator.getDataProviderInfos()?.[0],
stakeRewards: stakeRewards.toNumber(),
dividendInBaseCurrency: dividendInBaseCurrency.toNumber(), dividendInBaseCurrency: dividendInBaseCurrency.toNumber(),
dividendYieldPercent: dividendYieldPercent.toNumber(), dividendYieldPercent: dividendYieldPercent.toNumber(),
dividendYieldPercentWithCurrencyEffect: dividendYieldPercentWithCurrencyEffect:
@ -874,6 +985,7 @@ export class PortfolioService {
SymbolProfile, SymbolProfile,
averagePrice: 0, averagePrice: 0,
dataProviderInfo: undefined, dataProviderInfo: undefined,
stakeRewards: 0,
dividendInBaseCurrency: 0, dividendInBaseCurrency: 0,
dividendYieldPercent: 0, dividendYieldPercent: 0,
dividendYieldPercentWithCurrencyEffect: 0, dividendYieldPercentWithCurrencyEffect: 0,
@ -898,6 +1010,7 @@ export class PortfolioService {
} }
} }
@LogPerformance
public async getPositions({ public async getPositions({
dateRange = 'max', dateRange = 'max',
filters, filters,
@ -1022,6 +1135,7 @@ export class PortfolioService {
dataProviderResponses[symbol]?.marketState ?? 'delayed', dataProviderResponses[symbol]?.marketState ?? 'delayed',
name: symbolProfileMap[symbol].name, name: symbolProfileMap[symbol].name,
netPerformance: netPerformance?.toNumber() ?? null, netPerformance: netPerformance?.toNumber() ?? null,
tags: symbolProfileMap[symbol].tags,
netPerformancePercentage: netPerformancePercentage:
netPerformancePercentage?.toNumber() ?? null, netPerformancePercentage?.toNumber() ?? null,
netPerformancePercentageWithCurrencyEffect: netPerformancePercentageWithCurrencyEffect:
@ -1041,18 +1155,21 @@ export class PortfolioService {
}; };
} }
@LogPerformance
public async getPerformance({ public async getPerformance({
dateRange = 'max', dateRange = 'max',
filters, filters,
impersonationId, impersonationId,
userId, userId,
withExcludedAccounts = false withExcludedAccounts = false,
calculateTimeWeightedPerformance = false
}: { }: {
dateRange?: DateRange; dateRange?: DateRange;
filters?: Filter[]; filters?: Filter[];
impersonationId: string; impersonationId: string;
userId: string; userId: string;
withExcludedAccounts?: boolean; withExcludedAccounts?: boolean;
calculateTimeWeightedPerformance?: boolean;
}): Promise<PortfolioPerformanceResponse> { }): Promise<PortfolioPerformanceResponse> {
userId = await this.getUserId(impersonationId, userId); userId = await this.getUserId(impersonationId, userId);
const user = await this.userService.user({ id: userId }); const user = await this.userService.user({ id: userId });
@ -1098,15 +1215,14 @@ export class PortfolioService {
currency: userCurrency currency: userCurrency
}); });
const { errors, hasErrors, historicalData } =
await portfolioCalculator.getSnapshot();
const { endDate, startDate } = getIntervalFromDateRange(dateRange); const { endDate, startDate } = getIntervalFromDateRange(dateRange);
const range = { end: endDate, start: startDate };
const { chart } = await portfolioCalculator.getPerformance({ const { chart } = await (calculateTimeWeightedPerformance
end: endDate, ? (
start: startDate portfolioCalculator as CPRPortfolioCalculator
}); ).getPerformanceWithTimeWeightedReturn(range)
: portfolioCalculator.getPerformance(range));
const { const {
netPerformance, netPerformance,
@ -1131,9 +1247,8 @@ export class PortfolioService {
return { return {
chart, chart,
errors, hasErrors: false,
hasErrors, firstOrderDate: parseDate(chart[0]?.date),
firstOrderDate: parseDate(historicalData[0]?.date),
performance: { performance: {
netPerformance, netPerformance,
netPerformanceWithCurrencyEffect, netPerformanceWithCurrencyEffect,
@ -1147,6 +1262,7 @@ export class PortfolioService {
}; };
} }
@LogPerformance
public async getReport(impersonationId: string): Promise<PortfolioReport> { public async getReport(impersonationId: string): Promise<PortfolioReport> {
const userId = await this.getUserId(impersonationId, this.request.user.id); const userId = await this.getUserId(impersonationId, this.request.user.id);
const user = await this.userService.user({ id: userId }); const user = await this.userService.user({ id: userId });
@ -1240,6 +1356,7 @@ export class PortfolioService {
}; };
} }
@LogPerformance
public async updateTags({ public async updateTags({
dataSource, dataSource,
impersonationId, impersonationId,
@ -1254,10 +1371,40 @@ export class PortfolioService {
userId: string; userId: string;
}) { }) {
userId = await this.getUserId(impersonationId, userId); userId = await this.getUserId(impersonationId, userId);
let symbolProfile = await this.symbolProfileService.getSymbolProfiles([
await this.orderService.assignTags({ dataSource, symbol, tags, userId }); {
dataSource,
symbol
}
])[0];
await this.symbolProfileService.updateSymbolProfile({
assetClass: symbolProfile.assetClass,
assetSubClass: symbolProfile.assetSubClass,
countries: symbolProfile.countries,
currency: symbolProfile.currency,
dataSource,
holdings: symbolProfile.holdings,
name: symbolProfile.name,
sectors: symbolProfile.sectors,
symbol,
tags: {
connectOrCreate: tags.map(({ id, name }) => {
return {
create: {
id,
name
},
where: {
id
}
};
})
},
url: symbolProfile.url
});
} }
@LogPerformance
private async getCashPositions({ private async getCashPositions({
cashDetails, cashDetails,
userCurrency, userCurrency,
@ -1370,6 +1517,7 @@ export class PortfolioService {
return dividendsByGroup; return dividendsByGroup;
} }
@LogPerformance
private getEmergencyFundPositionsValueInBaseCurrency({ private getEmergencyFundPositionsValueInBaseCurrency({
holdings holdings
}: { }: {
@ -1512,6 +1660,7 @@ export class PortfolioService {
return { markets, marketsAdvanced }; return { markets, marketsAdvanced };
} }
@LogPerformance
private getStreaks({ private getStreaks({
investments, investments,
savingsRate savingsRate
@ -1534,6 +1683,7 @@ export class PortfolioService {
return { currentStreak, longestStreak }; return { currentStreak, longestStreak };
} }
@LogPerformance
private async getSummary({ private async getSummary({
balanceInBaseCurrency, balanceInBaseCurrency,
emergencyFundPositionsValueInBaseCurrency, emergencyFundPositionsValueInBaseCurrency,
@ -1559,7 +1709,6 @@ export class PortfolioService {
userId, userId,
withExcludedAccounts: true withExcludedAccounts: true
}); });
const excludedActivities: Activity[] = []; const excludedActivities: Activity[] = [];
const nonExcludedActivities: Activity[] = []; const nonExcludedActivities: Activity[] = [];
@ -1624,7 +1773,9 @@ export class PortfolioService {
.plus(emergencyFundPositionsValueInBaseCurrency) .plus(emergencyFundPositionsValueInBaseCurrency)
.toNumber(); .toNumber();
const committedFunds = new Big(totalBuy).minus(totalSell); const committedFunds = new Big(totalBuy)
.minus(totalSell)
.minus(dividendInBaseCurrency);
const totalOfExcludedActivities = this.getSumOfActivityType({ const totalOfExcludedActivities = this.getSumOfActivityType({
userCurrency, userCurrency,
@ -1644,16 +1795,20 @@ export class PortfolioService {
currency: userCurrency, currency: userCurrency,
withExcludedAccounts: true withExcludedAccounts: true
}); });
const excludedBalanceInBaseCurrency = new Big( const excludedBalanceInBaseCurrency = new Big(
cashDetailsWithExcludedAccounts.balanceInBaseCurrency cashDetailsWithExcludedAccounts.balanceInBaseCurrency
).minus(balanceInBaseCurrency); ).minus(balanceInBaseCurrency);
const excludedAccountsAndActivities = excludedBalanceInBaseCurrency let excludedAccountsAndActivities = excludedBalanceInBaseCurrency
.plus(totalOfExcludedActivities) .plus(totalOfExcludedActivities)
.toNumber(); .toNumber();
const netWorth = new Big(balanceInBaseCurrency) const netWorth =
portfolioCalculator instanceof CPRPortfolioCalculator
? await (portfolioCalculator as CPRPortfolioCalculator)
.getUnfilteredNetWorth(this.getUserCurrency())
.then((value) => value.toNumber())
: new Big(balanceInBaseCurrency)
.plus(currentValueInBaseCurrency) .plus(currentValueInBaseCurrency)
.plus(valuables) .plus(valuables)
.plus(excludedAccountsAndActivities) .plus(excludedAccountsAndActivities)
@ -1722,6 +1877,7 @@ export class PortfolioService {
}; };
} }
@LogPerformance
private getSumOfActivityType({ private getSumOfActivityType({
activities, activities,
activityType, activityType,
@ -1763,6 +1919,7 @@ export class PortfolioService {
return impersonationUserId || aUserId; return impersonationUserId || aUserId;
} }
@LogPerformance
private async getValueOfAccountsAndPlatforms({ private async getValueOfAccountsAndPlatforms({
activities, activities,
filters = [], filters = [],

5
apps/api/src/app/tag/tag.service.ts

@ -51,7 +51,7 @@ export class TagService {
const tagsWithOrderCount = await this.prismaService.tag.findMany({ const tagsWithOrderCount = await this.prismaService.tag.findMany({
include: { include: {
_count: { _count: {
select: { orders: true } select: { orders: true, symbolProfile: true }
} }
} }
}); });
@ -61,7 +61,8 @@ export class TagService {
id, id,
name, name,
userId, userId,
activityCount: _count.orders activityCount: _count.orders,
holdingCount: _count.symbolProfile
}; };
}); });
} }

3
apps/api/src/app/user/update-user-setting.dto.ts

@ -38,6 +38,9 @@ export class UpdateUserSettingDto {
@IsIn(<DateRange[]>[ @IsIn(<DateRange[]>[
'1d', '1d',
'1w',
'1m',
'3m',
'1y', '1y',
'5y', '5y',
'max', 'max',

6
apps/api/src/app/user/user.controller.ts

@ -158,6 +158,12 @@ export class UserController {
} }
} }
for (const key in data) {
if (data[key] !== false && data[key] !== null) {
userSettings[key] = data[key];
}
}
return this.userService.updateUserSetting({ return this.userService.updateUserSetting({
emitPortfolioChangedEvent, emitPortfolioChangedEvent,
userSettings, userSettings,

25
apps/api/src/helper/dateQueryHelper.ts

@ -0,0 +1,25 @@
import { resetHours } from '@ghostfolio/common/helper';
import { addDays } from 'date-fns';
import { DateQuery } from '../app/portfolio/interfaces/date-query.interface';
export class DateQueryHelper {
public handleDateQueryIn(dateQuery: DateQuery): {
query: DateQuery;
dates: Date[];
} {
let dates = [];
let query = dateQuery;
if (dateQuery.in?.length > 0) {
dates = dateQuery.in;
let end = Math.max(...dates.map((d) => d.getTime()));
let start = Math.min(...dates.map((d) => d.getTime()));
query = {
gte: resetHours(new Date(start)),
lt: resetHours(addDays(end, 1))
};
}
return { query, dates };
}
}

1
apps/api/src/helper/portfolio.helper.ts

@ -5,6 +5,7 @@ export function getFactor(activityType: ActivityType) {
switch (activityType) { switch (activityType) {
case 'BUY': case 'BUY':
case 'STAKE':
factor = 1; factor = 1;
break; break;
case 'SELL': case 'SELL':

2
apps/api/src/interceptors/performance-logging/performance-logging.interceptor.ts

@ -43,7 +43,7 @@ export function LogPerformance(
) { ) {
const originalMethod = descriptor.value; const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) { descriptor.value = function (...args: any[]) {
const startTime = performance.now(); const startTime = performance.now();
const performanceLoggingService = new PerformanceLoggingService(); const performanceLoggingService = new PerformanceLoggingService();

10
apps/api/src/services/data-provider/data-enhancer/trackinsight/trackinsight.service.ts

@ -36,9 +36,7 @@ export class TrackinsightDataEnhancerService implements DataEnhancerInterface {
response: Partial<SymbolProfile>; response: Partial<SymbolProfile>;
symbol: string; symbol: string;
}): Promise<Partial<SymbolProfile>> { }): Promise<Partial<SymbolProfile>> {
if ( if (!(response.assetSubClass === 'ETF')) {
!(response.assetClass === 'EQUITY' && response.assetSubClass === 'ETF')
) {
return response; return response;
} }
@ -120,10 +118,8 @@ export class TrackinsightDataEnhancerService implements DataEnhancerInterface {
}); });
}); });
if ( if (holdings?.weight < 1 - Math.min(holdings?.count * 0.000015, 0.95)) {
holdings?.weight < TrackinsightDataEnhancerService.holdingsWeightTreshold // Skip if data is inaccurate, dependent on holdings count there might be rounding issues
) {
// Skip if data is inaccurate
return response; return response;
} }

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

@ -1,5 +1,6 @@
import { RedisCacheService } from '@ghostfolio/api/app/redis-cache/redis-cache.service'; import { RedisCacheService } from '@ghostfolio/api/app/redis-cache/redis-cache.service';
import { LookupItem } from '@ghostfolio/api/app/symbol/interfaces/lookup-item.interface'; import { LookupItem } from '@ghostfolio/api/app/symbol/interfaces/lookup-item.interface';
import { LogPerformance } from '@ghostfolio/api/interceptors/performance-logging/performance-logging.interceptor';
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service';
import { DataProviderInterface } from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface'; import { DataProviderInterface } from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface';
import { import {
@ -344,6 +345,7 @@ export class DataProviderService {
return result; return result;
} }
@LogPerformance
public async getQuotes({ public async getQuotes({
items, items,
requestTimeout, requestTimeout,
@ -471,6 +473,8 @@ export class DataProviderService {
} }
response[symbol] = dataProviderResponse; response[symbol] = dataProviderResponse;
let quotesCacheTTL =
this.getAppropriateCacheTTL(dataProviderResponse);
this.redisCacheService.set( this.redisCacheService.set(
this.redisCacheService.getQuoteKey({ this.redisCacheService.getQuoteKey({
@ -478,7 +482,7 @@ export class DataProviderService {
dataSource: DataSource[dataSource] dataSource: DataSource[dataSource]
}), }),
JSON.stringify(response[symbol]), JSON.stringify(response[symbol]),
this.configurationService.get('CACHE_QUOTES_TTL') quotesCacheTTL
); );
for (const { for (const {
@ -561,6 +565,25 @@ export class DataProviderService {
return response; return response;
} }
private getAppropriateCacheTTL(dataProviderResponse: IDataProviderResponse) {
let quotesCacheTTL = this.configurationService.get('CACHE_QUOTES_TTL');
if (dataProviderResponse.dataSource === 'MANUAL') {
quotesCacheTTL = 14400; // 4h Cache for Manual Service
} else if (dataProviderResponse.marketState === 'closed') {
let date = new Date();
let dayOfWeek = date.getDay();
if (dayOfWeek === 0 || dayOfWeek === 6) {
quotesCacheTTL = 14400;
} else if (date.getHours() > 16) {
quotesCacheTTL = 14400;
} else {
quotesCacheTTL = 900;
}
}
return quotesCacheTTL;
}
public async search({ public async search({
includeIndices = false, includeIndices = false,
query, query,
@ -667,7 +690,9 @@ export class DataProviderService {
for (const date in rootData) { for (const date in rootData) {
data[date] = { data[date] = {
marketPrice: new Big(factor).mul(rootData[date].marketPrice).toNumber() marketPrice: rootData[date].marketPrice
? new Big(factor).mul(rootData[date].marketPrice).toNumber()
: null
}; };
} }

14
apps/api/src/services/data-provider/manual/manual.service.ts

@ -13,6 +13,7 @@ import {
} from '@ghostfolio/api/services/interfaces/interfaces'; } from '@ghostfolio/api/services/interfaces/interfaces';
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service';
import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service'; import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service';
import { BatchPrismaClient } from '@ghostfolio/common/chunkhelper';
import { import {
DATE_FORMAT, DATE_FORMAT,
extractNumberFromString, extractNumberFromString,
@ -153,7 +154,12 @@ export class ManualService implements DataProviderInterface {
}) })
); );
const marketData = await this.prismaService.marketData.findMany({ const batch = new BatchPrismaClient(this.prismaService);
const marketData = await batch
.over(symbols)
.with((prisma, _symbols) =>
prisma.marketData.findMany({
distinct: ['symbol'], distinct: ['symbol'],
orderBy: { orderBy: {
date: 'desc' date: 'desc'
@ -161,10 +167,12 @@ export class ManualService implements DataProviderInterface {
take: symbols.length, take: symbols.length,
where: { where: {
symbol: { symbol: {
in: symbols in: _symbols
} }
} }
}); })
)
.then((_result) => _result.flat());
const symbolProfilesWithScraperConfigurationAndInstantMode = const symbolProfilesWithScraperConfigurationAndInstantMode =
symbolProfiles.filter(({ scraperConfiguration }) => { symbolProfiles.filter(({ scraperConfiguration }) => {

13
apps/api/src/services/market-data/market-data.service.ts

@ -1,7 +1,9 @@
import { UpdateMarketDataDto } from '@ghostfolio/api/app/admin/update-market-data.dto'; import { UpdateMarketDataDto } from '@ghostfolio/api/app/admin/update-market-data.dto';
import { DateQuery } from '@ghostfolio/api/app/portfolio/interfaces/date-query.interface'; import { DateQuery } from '@ghostfolio/api/app/portfolio/interfaces/date-query.interface';
import { DateQueryHelper } from '@ghostfolio/api/helper/dateQueryHelper';
import { IDataGatheringItem } from '@ghostfolio/api/services/interfaces/interfaces'; import { IDataGatheringItem } from '@ghostfolio/api/services/interfaces/interfaces';
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service';
import { BatchPrismaClient } from '@ghostfolio/common/chunkhelper';
import { resetHours } from '@ghostfolio/common/helper'; import { resetHours } from '@ghostfolio/common/helper';
import { AssetProfileIdentifier } from '@ghostfolio/common/interfaces'; import { AssetProfileIdentifier } from '@ghostfolio/common/interfaces';
@ -12,11 +14,16 @@ import {
MarketDataState, MarketDataState,
Prisma Prisma
} from '@prisma/client'; } from '@prisma/client';
import AwaitLock from 'await-lock';
@Injectable() @Injectable()
export class MarketDataService { export class MarketDataService {
public constructor(private readonly prismaService: PrismaService) {} public constructor(private readonly prismaService: PrismaService) {}
lock = new AwaitLock();
private dateQueryHelper = new DateQueryHelper();
public async deleteMany({ dataSource, symbol }: AssetProfileIdentifier) { public async deleteMany({ dataSource, symbol }: AssetProfileIdentifier) {
return this.prismaService.marketData.deleteMany({ return this.prismaService.marketData.deleteMany({
where: { where: {
@ -117,7 +124,6 @@ export class MarketDataService {
where: Prisma.MarketDataWhereUniqueInput; where: Prisma.MarketDataWhereUniqueInput;
}): Promise<MarketData> { }): Promise<MarketData> {
const { data, where } = params; const { data, where } = params;
return this.prismaService.marketData.upsert({ return this.prismaService.marketData.upsert({
where, where,
create: { create: {
@ -141,7 +147,7 @@ export class MarketDataService {
data: Prisma.MarketDataUpdateInput[]; data: Prisma.MarketDataUpdateInput[];
}): Promise<MarketData[]> { }): Promise<MarketData[]> {
const upsertPromises = data.map( const upsertPromises = data.map(
({ dataSource, date, marketPrice, symbol, state }) => { async ({ dataSource, date, marketPrice, symbol, state }) => {
return this.prismaService.marketData.upsert({ return this.prismaService.marketData.upsert({
create: { create: {
dataSource: <DataSource>dataSource, dataSource: <DataSource>dataSource,
@ -164,7 +170,6 @@ export class MarketDataService {
}); });
} }
); );
return await Promise.all(upsertPromises);
return this.prismaService.$transaction(upsertPromises);
} }
} }

3
apps/api/src/services/queues/data-gathering/data-gathering.service.ts

@ -28,6 +28,7 @@ import {
import { InjectQueue } from '@nestjs/bull'; import { InjectQueue } from '@nestjs/bull';
import { Inject, Injectable, Logger } from '@nestjs/common'; import { Inject, Injectable, Logger } from '@nestjs/common';
import { DataSource } from '@prisma/client'; import { DataSource } from '@prisma/client';
import AwaitLock from 'await-lock';
import { JobOptions, Queue } from 'bull'; import { JobOptions, Queue } from 'bull';
import { format, min, subDays, subYears } from 'date-fns'; import { format, min, subDays, subYears } from 'date-fns';
import { isEmpty } from 'lodash'; import { isEmpty } from 'lodash';
@ -47,6 +48,8 @@ export class DataGatheringService {
private readonly symbolProfileService: SymbolProfileService private readonly symbolProfileService: SymbolProfileService
) {} ) {}
lock = new AwaitLock();
public async addJobToQueue({ public async addJobToQueue({
data, data,
name, name,

12
apps/api/src/services/symbol-profile/symbol-profile-overwrite.module.ts

@ -0,0 +1,12 @@
import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module';
import { Module } from '@nestjs/common';
import { SymbolProfileOverwriteService } from './symbol-profile-overwrite.service';
@Module({
imports: [PrismaModule],
providers: [SymbolProfileOverwriteService],
exports: [SymbolProfileOverwriteService]
})
export class SymbolProfileOverwriteModule {}

69
apps/api/src/services/symbol-profile/symbol-profile-overwrite.service.ts

@ -0,0 +1,69 @@
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service';
import { Injectable } from '@nestjs/common';
import { DataSource, Prisma, SymbolProfileOverrides } from '@prisma/client';
@Injectable()
export class SymbolProfileOverwriteService {
public constructor(private readonly prismaService: PrismaService) {}
public async add(
assetProfileOverwrite: Prisma.SymbolProfileOverridesCreateInput
): Promise<SymbolProfileOverrides | never> {
return this.prismaService.symbolProfileOverrides.create({
data: assetProfileOverwrite
});
}
public async delete(symbolProfileId: string) {
return this.prismaService.symbolProfileOverrides.delete({
where: { symbolProfileId: symbolProfileId }
});
}
public updateSymbolProfileOverrides({
assetClass,
assetSubClass,
name,
countries,
sectors,
url,
symbolProfileId
}: Prisma.SymbolProfileOverridesUpdateInput & { symbolProfileId: string }) {
return this.prismaService.symbolProfileOverrides.update({
data: {
assetClass,
assetSubClass,
name,
countries,
sectors,
url
},
where: { symbolProfileId: symbolProfileId }
});
}
public async GetSymbolProfileId(
Symbol: string,
datasource: DataSource
): Promise<string> {
let SymbolProfileId = await this.prismaService.symbolProfile
.findFirst({
where: {
symbol: Symbol,
dataSource: datasource
}
})
.then((s) => s.id);
let symbolProfileIdSaved = await this.prismaService.symbolProfileOverrides
.findFirst({
where: {
symbolProfileId: SymbolProfileId
}
})
.then((s) => s?.symbolProfileId);
return symbolProfileIdSaved;
}
}

19
apps/api/src/services/symbol-profile/symbol-profile.service.ts

@ -1,3 +1,4 @@
import { LogPerformance } from '@ghostfolio/api/interceptors/performance-logging/performance-logging.interceptor';
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service';
import { UNKNOWN_KEY } from '@ghostfolio/common/config'; import { UNKNOWN_KEY } from '@ghostfolio/common/config';
import { import {
@ -10,7 +11,12 @@ import { Country } from '@ghostfolio/common/interfaces/country.interface';
import { Sector } from '@ghostfolio/common/interfaces/sector.interface'; import { Sector } from '@ghostfolio/common/interfaces/sector.interface';
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { Prisma, SymbolProfile, SymbolProfileOverrides } from '@prisma/client'; import {
Prisma,
SymbolProfile,
SymbolProfileOverrides,
Tag
} from '@prisma/client';
import { continents, countries } from 'countries-list'; import { continents, countries } from 'countries-list';
@Injectable() @Injectable()
@ -35,6 +41,7 @@ export class SymbolProfileService {
}); });
} }
@LogPerformance
public async getSymbolProfiles( public async getSymbolProfiles(
aAssetProfileIdentifiers: AssetProfileIdentifier[] aAssetProfileIdentifiers: AssetProfileIdentifier[]
): Promise<EnhancedSymbolProfile[]> { ): Promise<EnhancedSymbolProfile[]> {
@ -51,6 +58,7 @@ export class SymbolProfileService {
select: { date: true }, select: { date: true },
take: 1 take: 1
}, },
tags: true,
SymbolProfileOverrides: true SymbolProfileOverrides: true
}, },
where: { where: {
@ -76,7 +84,8 @@ export class SymbolProfileService {
_count: { _count: {
select: { Order: true } select: { Order: true }
}, },
SymbolProfileOverrides: true SymbolProfileOverrides: true,
tags: true
}, },
where: { where: {
id: { id: {
@ -134,6 +143,7 @@ export class SymbolProfileService {
dataSource, dataSource,
holdings, holdings,
name, name,
tags,
scraperConfiguration, scraperConfiguration,
sectors, sectors,
symbol, symbol,
@ -150,6 +160,7 @@ export class SymbolProfileService {
currency, currency,
holdings, holdings,
name, name,
tags,
scraperConfiguration, scraperConfiguration,
sectors, sectors,
symbolMapping, symbolMapping,
@ -166,6 +177,7 @@ export class SymbolProfileService {
Order?: { Order?: {
date: Date; date: Date;
}[]; }[];
tags?: Tag[];
SymbolProfileOverrides: SymbolProfileOverrides; SymbolProfileOverrides: SymbolProfileOverrides;
})[] })[]
): EnhancedSymbolProfile[] { ): EnhancedSymbolProfile[] {
@ -180,7 +192,8 @@ export class SymbolProfileService {
holdings: this.getHoldings(symbolProfile), holdings: this.getHoldings(symbolProfile),
scraperConfiguration: this.getScraperConfiguration(symbolProfile), scraperConfiguration: this.getScraperConfiguration(symbolProfile),
sectors: this.getSectors(symbolProfile), sectors: this.getSectors(symbolProfile),
symbolMapping: this.getSymbolMapping(symbolProfile) symbolMapping: this.getSymbolMapping(symbolProfile),
tags: symbolProfile?.tags
}; };
item.activitiesCount = symbolProfile._count.Order; item.activitiesCount = symbolProfile._count.Order;

9
apps/api/src/services/tag/tag.service.ts

@ -23,11 +23,20 @@ export class TagService {
name: 'asc' name: 'asc'
}, },
where: { where: {
OR: [
{
orders: { orders: {
some: { some: {
userId userId
} }
} }
},
{
symbolProfile: {
some: {}
}
}
]
} }
}); });
} }

6
apps/client-e2e/project.json

@ -3,6 +3,8 @@
"$schema": "../../node_modules/nx/schemas/project-schema.json", "$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "apps/client-e2e/src", "sourceRoot": "apps/client-e2e/src",
"projectType": "application", "projectType": "application",
"tags": [],
"implicitDependencies": ["client"],
"targets": { "targets": {
"e2e": { "e2e": {
"executor": "@nx/cypress:cypress", "executor": "@nx/cypress:cypress",
@ -17,7 +19,5 @@
} }
} }
} }
}, }
"tags": [],
"implicitDependencies": ["client"]
} }

96
apps/client/project.json

@ -2,13 +2,59 @@
"name": "client", "name": "client",
"$schema": "../../node_modules/nx/schemas/project-schema.json", "$schema": "../../node_modules/nx/schemas/project-schema.json",
"projectType": "application", "projectType": "application",
"sourceRoot": "apps/client/src",
"prefix": "gf",
"i18n": {
"locales": {
"ca": {
"baseHref": "/ca/",
"translation": "apps/client/src/locales/messages.ca.xlf"
},
"de": {
"baseHref": "/de/",
"translation": "apps/client/src/locales/messages.de.xlf"
},
"es": {
"baseHref": "/es/",
"translation": "apps/client/src/locales/messages.es.xlf"
},
"fr": {
"baseHref": "/fr/",
"translation": "apps/client/src/locales/messages.fr.xlf"
},
"it": {
"baseHref": "/it/",
"translation": "apps/client/src/locales/messages.it.xlf"
},
"nl": {
"baseHref": "/nl/",
"translation": "apps/client/src/locales/messages.nl.xlf"
},
"pl": {
"baseHref": "/pl/",
"translation": "apps/client/src/locales/messages.pl.xlf"
},
"pt": {
"baseHref": "/pt/",
"translation": "apps/client/src/locales/messages.pt.xlf"
},
"tr": {
"baseHref": "/tr/",
"translation": "apps/client/src/locales/messages.tr.xlf"
},
"zh": {
"baseHref": "/zh/",
"translation": "apps/client/src/locales/messages.zh.xlf"
}
},
"sourceLocale": "en"
},
"tags": [],
"generators": { "generators": {
"@schematics/angular:component": { "@schematics/angular:component": {
"style": "scss" "style": "scss"
} }
}, },
"sourceRoot": "apps/client/src",
"prefix": "gf",
"targets": { "targets": {
"build": { "build": {
"executor": "@nx/angular:webpack-browser", "executor": "@nx/angular:webpack-browser",
@ -242,51 +288,5 @@
}, },
"outputs": ["{workspaceRoot}/coverage/apps/client"] "outputs": ["{workspaceRoot}/coverage/apps/client"]
} }
},
"i18n": {
"locales": {
"ca": {
"baseHref": "/ca/",
"translation": "apps/client/src/locales/messages.ca.xlf"
},
"de": {
"baseHref": "/de/",
"translation": "apps/client/src/locales/messages.de.xlf"
},
"es": {
"baseHref": "/es/",
"translation": "apps/client/src/locales/messages.es.xlf"
},
"fr": {
"baseHref": "/fr/",
"translation": "apps/client/src/locales/messages.fr.xlf"
},
"it": {
"baseHref": "/it/",
"translation": "apps/client/src/locales/messages.it.xlf"
},
"nl": {
"baseHref": "/nl/",
"translation": "apps/client/src/locales/messages.nl.xlf"
},
"pl": {
"baseHref": "/pl/",
"translation": "apps/client/src/locales/messages.pl.xlf"
},
"pt": {
"baseHref": "/pt/",
"translation": "apps/client/src/locales/messages.pt.xlf"
},
"tr": {
"baseHref": "/tr/",
"translation": "apps/client/src/locales/messages.tr.xlf"
},
"zh": {
"baseHref": "/zh/",
"translation": "apps/client/src/locales/messages.zh.xlf"
} }
},
"sourceLocale": "en"
},
"tags": []
} }

52
apps/client/src/app/components/admin-market-data/asset-profile-dialog/asset-profile-dialog.component.ts

@ -13,22 +13,27 @@ import {
} from '@ghostfolio/common/interfaces'; } from '@ghostfolio/common/interfaces';
import { translate } from '@ghostfolio/ui/i18n'; import { translate } from '@ghostfolio/ui/i18n';
import { COMMA, ENTER } from '@angular/cdk/keycodes';
import { import {
ChangeDetectionStrategy, ChangeDetectionStrategy,
ChangeDetectorRef, ChangeDetectorRef,
Component, Component,
ElementRef,
Inject, Inject,
OnDestroy, OnDestroy,
OnInit OnInit,
ViewChild
} from '@angular/core'; } from '@angular/core';
import { FormBuilder, FormControl, Validators } from '@angular/forms'; import { FormBuilder, FormControl, Validators } from '@angular/forms';
import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar'; import { MatSnackBar } from '@angular/material/snack-bar';
import { import {
AssetClass, AssetClass,
AssetSubClass, AssetSubClass,
MarketData, MarketData,
SymbolProfile SymbolProfile,
Tag
} from '@prisma/client'; } from '@prisma/client';
import { format } from 'date-fns'; import { format } from 'date-fns';
import { parse as csvToJson } from 'papaparse'; import { parse as csvToJson } from 'papaparse';
@ -45,6 +50,8 @@ import { AssetProfileDialogParams } from './interfaces/interfaces';
styleUrls: ['./asset-profile-dialog.component.scss'] styleUrls: ['./asset-profile-dialog.component.scss']
}) })
export class AssetProfileDialog implements OnDestroy, OnInit { export class AssetProfileDialog implements OnDestroy, OnInit {
@ViewChild('tagInput') tagInput: ElementRef<HTMLInputElement>;
public separatorKeysCodes: number[] = [ENTER, COMMA];
public assetProfileClass: string; public assetProfileClass: string;
public assetClasses = Object.keys(AssetClass).map((assetClass) => { public assetClasses = Object.keys(AssetClass).map((assetClass) => {
return { id: assetClass, label: translate(assetClass) }; return { id: assetClass, label: translate(assetClass) };
@ -63,6 +70,7 @@ export class AssetProfileDialog implements OnDestroy, OnInit {
csvString: '' csvString: ''
}), }),
name: ['', Validators.required], name: ['', Validators.required],
tags: new FormControl<Tag[]>(undefined),
scraperConfiguration: '', scraperConfiguration: '',
sectors: '', sectors: '',
symbolMapping: '', symbolMapping: '',
@ -81,6 +89,8 @@ export class AssetProfileDialog implements OnDestroy, OnInit {
[name: string]: { name: string; value: number }; [name: string]: { name: string; value: number };
}; };
public HoldingTags: { id: string; name: string }[];
private static readonly HISTORICAL_DATA_TEMPLATE = `date;marketPrice\n${format( private static readonly HISTORICAL_DATA_TEMPLATE = `date;marketPrice\n${format(
new Date(), new Date(),
DATE_FORMAT DATE_FORMAT
@ -109,6 +119,18 @@ export class AssetProfileDialog implements OnDestroy, OnInit {
} }
public initialize() { public initialize() {
this.adminService
.fetchTags()
.pipe(takeUntil(this.unsubscribeSubject))
.subscribe((tags) => {
this.HoldingTags = tags.map(({ id, name }) => {
return { id, name };
});
this.dataService.updateInfo();
this.changeDetectorRef.markForCheck();
});
this.adminService this.adminService
.fetchAdminMarketDataBySymbol({ .fetchAdminMarketDataBySymbol({
dataSource: this.data.dataSource, dataSource: this.data.dataSource,
@ -149,6 +171,7 @@ export class AssetProfileDialog implements OnDestroy, OnInit {
assetClass: this.assetProfile.assetClass ?? null, assetClass: this.assetProfile.assetClass ?? null,
assetSubClass: this.assetProfile.assetSubClass ?? null, assetSubClass: this.assetProfile.assetSubClass ?? null,
comment: this.assetProfile?.comment ?? '', comment: this.assetProfile?.comment ?? '',
tags: this.assetProfile?.tags ?? [],
countries: JSON.stringify( countries: JSON.stringify(
this.assetProfile?.countries?.map(({ code, weight }) => { this.assetProfile?.countries?.map(({ code, weight }) => {
return { code, weight }; return { code, weight };
@ -164,7 +187,7 @@ export class AssetProfileDialog implements OnDestroy, OnInit {
), ),
sectors: JSON.stringify(this.assetProfile?.sectors ?? []), sectors: JSON.stringify(this.assetProfile?.sectors ?? []),
symbolMapping: JSON.stringify(this.assetProfile?.symbolMapping ?? {}), symbolMapping: JSON.stringify(this.assetProfile?.symbolMapping ?? {}),
url: this.assetProfile?.url ?? '' url: this.assetProfile?.url
}); });
this.assetProfileForm.markAsPristine(); this.assetProfileForm.markAsPristine();
@ -294,9 +317,10 @@ export class AssetProfileDialog implements OnDestroy, OnInit {
assetClass: this.assetProfileForm.get('assetClass').value, assetClass: this.assetProfileForm.get('assetClass').value,
assetSubClass: this.assetProfileForm.get('assetSubClass').value, assetSubClass: this.assetProfileForm.get('assetSubClass').value,
comment: this.assetProfileForm.get('comment').value || null, comment: this.assetProfileForm.get('comment').value || null,
tags: this.assetProfileForm.get('tags').value,
currency: this.assetProfileForm.get('currency').value, currency: this.assetProfileForm.get('currency').value,
name: this.assetProfileForm.get('name').value, name: this.assetProfileForm.get('name').value,
url: this.assetProfileForm.get('url').value || null url: this.assetProfileForm.get('url').value
}; };
try { try {
@ -364,6 +388,26 @@ export class AssetProfileDialog implements OnDestroy, OnInit {
}); });
} }
public onRemoveTag(aTag: Tag) {
this.assetProfileForm.controls['tags'].setValue(
this.assetProfileForm.controls['tags'].value.filter(({ id }) => {
return id !== aTag.id;
})
);
this.assetProfileForm.markAsDirty();
}
public onAddTag(event: MatAutocompleteSelectedEvent) {
this.assetProfileForm.controls['tags'].setValue([
...(this.assetProfileForm.controls['tags'].value ?? []),
this.HoldingTags.find(({ id }) => {
return id === event.option.value;
})
]);
this.tagInput.nativeElement.value = '';
this.assetProfileForm.markAsDirty();
}
public ngOnDestroy() { public ngOnDestroy() {
this.unsubscribeSubject.next(); this.unsubscribeSubject.next();
this.unsubscribeSubject.complete(); this.unsubscribeSubject.complete();

31
apps/client/src/app/components/admin-market-data/asset-profile-dialog/asset-profile-dialog.html

@ -267,6 +267,37 @@
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
</div> </div>
<div class="mt-3">
<mat-form-field appearance="outline" class="w-100">
<mat-label i18n>Tags</mat-label>
<mat-chip-grid #tagsChipList>
<mat-chip-row
*ngFor="let tag of assetProfileForm.controls['tags']?.value"
matChipRemove
[removable]="true"
(removed)="onRemoveTag(tag)"
>
{{ tag.name }}
<ion-icon class="ml-2" matPrefix name="close-outline"></ion-icon>
</mat-chip-row>
<input
#tagInput
name="close-outline"
[matAutocomplete]="autocompleteTags"
[matChipInputFor]="tagsChipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
/>
</mat-chip-grid>
<mat-autocomplete
#autocompleteTags="matAutocomplete"
(optionSelected)="onAddTag($event)"
>
<mat-option *ngFor="let tag of HoldingTags" [value]="tag.id">
{{ tag.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</div>
<div class="d-flex my-3"> <div class="d-flex my-3">
<div class="w-50"> <div class="w-50">
<mat-checkbox <mat-checkbox

4
apps/client/src/app/components/admin-market-data/asset-profile-dialog/asset-profile-dialog.module.ts

@ -9,8 +9,10 @@ import { TextFieldModule } from '@angular/cdk/text-field';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core'; import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatChipsModule } from '@angular/material/chips';
import { MatDialogModule } from '@angular/material/dialog'; import { MatDialogModule } from '@angular/material/dialog';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { MatMenuModule } from '@angular/material/menu'; import { MatMenuModule } from '@angular/material/menu';
@ -28,6 +30,8 @@ import { AssetProfileDialog } from './asset-profile-dialog.component';
GfAssetProfileIconComponent, GfAssetProfileIconComponent,
GfCurrencySelectorComponent, GfCurrencySelectorComponent,
GfPortfolioProportionChartComponent, GfPortfolioProportionChartComponent,
MatAutocompleteModule,
MatChipsModule,
GfValueComponent, GfValueComponent,
MatButtonModule, MatButtonModule,
MatCheckboxModule, MatCheckboxModule,

13
apps/client/src/app/components/admin-tag/admin-tag.component.html

@ -61,6 +61,19 @@
{{ element.activityCount }} {{ element.activityCount }}
</td> </td>
</ng-container> </ng-container>
<ng-container matColumnDef="holdings">
<th
*matHeaderCellDef
class="px-1"
mat-header-cell
mat-sort-header="holdingCount"
>
<ng-container i18n>Holdings</ng-container>
</th>
<td *matCellDef="let element" class="px-1" mat-cell>
{{ element.holdingCount }}
</td>
</ng-container>
<ng-container matColumnDef="actions" stickyEnd> <ng-container matColumnDef="actions" stickyEnd>
<th <th

8
apps/client/src/app/components/admin-tag/admin-tag.component.ts

@ -36,7 +36,13 @@ export class AdminTagComponent implements OnInit, OnDestroy {
public dataSource: MatTableDataSource<Tag> = new MatTableDataSource(); public dataSource: MatTableDataSource<Tag> = new MatTableDataSource();
public deviceType: string; public deviceType: string;
public displayedColumns = ['name', 'userId', 'activities', 'actions']; public displayedColumns = [
'name',
'userId',
'activities',
'holdings',
'actions'
];
public tags: Tag[]; public tags: Tag[];
private unsubscribeSubject = new Subject<void>(); private unsubscribeSubject = new Subject<void>();

1
apps/client/src/app/components/benchmark-comparator/benchmark-comparator.component.scss

@ -7,5 +7,6 @@
ngx-skeleton-loader { ngx-skeleton-loader {
height: 100%; height: 100%;
} }
margin-bottom: 0.5rem;
} }
} }

16
apps/client/src/app/components/benchmark-comparator/benchmark-comparator.component.ts

@ -54,6 +54,7 @@ export class BenchmarkComparatorComponent implements OnChanges, OnDestroy {
@Input() isLoading: boolean; @Input() isLoading: boolean;
@Input() locale = getLocale(); @Input() locale = getLocale();
@Input() performanceDataItems: LineChartItem[]; @Input() performanceDataItems: LineChartItem[];
@Input() timeWeightedPerformanceDataItems: LineChartItem[];
@Input() user: User; @Input() user: User;
@Output() benchmarkChanged = new EventEmitter<string>(); @Output() benchmarkChanged = new EventEmitter<string>();
@ -84,7 +85,10 @@ export class BenchmarkComparatorComponent implements OnChanges, OnDestroy {
permissions.accessAdminControl permissions.accessAdminControl
); );
if (this.performanceDataItems) { if (
this.performanceDataItems ||
this.timeWeightedPerformanceDataItems?.length > 0
) {
this.initialize(); this.initialize();
} }
} }
@ -115,6 +119,16 @@ export class BenchmarkComparatorComponent implements OnChanges, OnDestroy {
}), }),
label: $localize`Portfolio` label: $localize`Portfolio`
}, },
{
backgroundColor: `rgb(${primaryColorRgb.r}, ${primaryColorRgb.g}, ${primaryColorRgb.b})`,
borderColor: `rgb(${primaryColorRgb.r}, ${primaryColorRgb.g}, ${primaryColorRgb.b})`,
borderWidth: 2,
borderDash: [5, 5],
data: this.timeWeightedPerformanceDataItems.map(({ date, value }) => {
return { x: parseDate(date).getTime(), y: value };
}),
label: $localize`Portfolio (time-weighted)`
},
{ {
backgroundColor: `rgb(${secondaryColorRgb.r}, ${secondaryColorRgb.g}, ${secondaryColorRgb.b})`, backgroundColor: `rgb(${secondaryColorRgb.r}, ${secondaryColorRgb.g}, ${secondaryColorRgb.b})`,
borderColor: `rgb(${secondaryColorRgb.r}, ${secondaryColorRgb.g}, ${secondaryColorRgb.b})`, borderColor: `rgb(${secondaryColorRgb.r}, ${secondaryColorRgb.g}, ${secondaryColorRgb.b})`,

35
apps/client/src/app/components/header/header.component.ts

@ -174,18 +174,24 @@ export class HeaderComponent implements OnChanges {
const userSetting: UpdateUserSettingDto = {}; const userSetting: UpdateUserSettingDto = {};
for (const filter of filters) { for (const filter of filters) {
let filtersType: string; let filtersType = this.getFilterType(filter.type);
if (filter.type === 'ACCOUNT') { let userFilters = filters
filtersType = 'accounts'; .filter((f) => f.type === filter.type && filter.id)
} else if (filter.type === 'ASSET_CLASS') { .map((f) => f.id);
filtersType = 'assetClasses';
} else if (filter.type === 'TAG') {
filtersType = 'tags';
}
userSetting[`filters.${filtersType}`] = filter.id ? [filter.id] : null; userSetting[`filters.${filtersType}`] = userFilters.length
? userFilters
: null;
} }
['ACCOUNT', 'ASSET_CLASS', 'TAG']
.filter(
(fitlerType) =>
!filters.some((f: Filter) => f.type.toString() === fitlerType)
)
.forEach((filterType) => {
userSetting[`filters.${this.getFilterType(filterType)}`] = null;
});
this.dataService this.dataService
.putUserSetting(userSetting) .putUserSetting(userSetting)
@ -268,4 +274,13 @@ export class HeaderComponent implements OnChanges {
this.unsubscribeSubject.next(); this.unsubscribeSubject.next();
this.unsubscribeSubject.complete(); this.unsubscribeSubject.complete();
} }
private getFilterType(filterType: string) {
if (filterType === 'ACCOUNT') {
return 'accounts';
} else if (filterType === 'ASSET_CLASS') {
return 'assetClasses';
} else if (filterType === 'TAG') {
return 'tags';
}
}
} }

30
apps/client/src/app/components/holding-detail-dialog/holding-detail-dialog.component.ts

@ -100,6 +100,7 @@ export class GfHoldingDetailDialogComponent implements OnDestroy, OnInit {
public dataProviderInfo: DataProviderInfo; public dataProviderInfo: DataProviderInfo;
public dataSource: MatTableDataSource<Activity>; public dataSource: MatTableDataSource<Activity>;
public dividendInBaseCurrency: number; public dividendInBaseCurrency: number;
public stakeRewards: number;
public dividendInBaseCurrencyPrecision = 2; public dividendInBaseCurrencyPrecision = 2;
public dividendYieldPercentWithCurrencyEffect: number; public dividendYieldPercentWithCurrencyEffect: number;
public feeInBaseCurrency: number; public feeInBaseCurrency: number;
@ -119,6 +120,7 @@ export class GfHoldingDetailDialogComponent implements OnDestroy, OnInit {
public netPerformanceWithCurrencyEffectPrecision = 2; public netPerformanceWithCurrencyEffectPrecision = 2;
public quantity: number; public quantity: number;
public quantityPrecision = 2; public quantityPrecision = 2;
public stakePrecision = 2;
public reportDataGlitchMail: string; public reportDataGlitchMail: string;
public sectors: { public sectors: {
[name: string]: { name: string; value: number }; [name: string]: { name: string; value: number };
@ -214,10 +216,7 @@ export class GfHoldingDetailDialogComponent implements OnDestroy, OnInit {
averagePrice, averagePrice,
dataProviderInfo, dataProviderInfo,
dividendInBaseCurrency, dividendInBaseCurrency,
dividendYieldPercentWithCurrencyEffect, stakeRewards,
feeInBaseCurrency,
firstBuyDate,
historicalData,
investment, investment,
marketPrice, marketPrice,
maxPrice, maxPrice,
@ -230,13 +229,18 @@ export class GfHoldingDetailDialogComponent implements OnDestroy, OnInit {
SymbolProfile, SymbolProfile,
tags, tags,
transactionCount, transactionCount,
value value,
dividendYieldPercentWithCurrencyEffect,
feeInBaseCurrency,
firstBuyDate,
historicalData
}) => { }) => {
this.averagePrice = averagePrice; this.averagePrice = averagePrice;
this.benchmarkDataItems = []; this.benchmarkDataItems = [];
this.countries = {}; this.countries = {};
this.dataProviderInfo = dataProviderInfo; this.dataProviderInfo = dataProviderInfo;
this.dividendInBaseCurrency = dividendInBaseCurrency; this.dividendInBaseCurrency = dividendInBaseCurrency;
this.stakeRewards = stakeRewards;
if ( if (
this.data.deviceType === 'mobile' && this.data.deviceType === 'mobile' &&
@ -370,7 +374,7 @@ export class GfHoldingDetailDialogComponent implements OnDestroy, OnInit {
} }
} }
if (isToday(parseISO(this.firstBuyDate))) { if (this.firstBuyDate && isToday(parseISO(this.firstBuyDate))) {
// Add average price // Add average price
this.historicalDataItems.push({ this.historicalDataItems.push({
date: this.firstBuyDate, date: this.firstBuyDate,
@ -410,6 +414,7 @@ export class GfHoldingDetailDialogComponent implements OnDestroy, OnInit {
if ( if (
this.benchmarkDataItems[0]?.value === undefined && this.benchmarkDataItems[0]?.value === undefined &&
this.firstBuyDate &&
isSameMonth(parseISO(this.firstBuyDate), new Date()) isSameMonth(parseISO(this.firstBuyDate), new Date())
) { ) {
this.benchmarkDataItems[0].value = this.averagePrice; this.benchmarkDataItems[0].value = this.averagePrice;
@ -424,6 +429,19 @@ export class GfHoldingDetailDialogComponent implements OnDestroy, OnInit {
} }
); );
if (Number.isInteger(this.quantity)) {
this.quantityPrecision = 0;
} else if (this.SymbolProfile?.assetSubClass === 'CRYPTOCURRENCY') {
if (this.quantity < 1) {
this.quantityPrecision = 7;
} else if (this.quantity < 1000) {
this.quantityPrecision = 5;
} else if (this.quantity > 10000000) {
this.quantityPrecision = 0;
}
this.stakePrecision = this.quantityPrecision;
}
this.changeDetectorRef.markForCheck(); this.changeDetectorRef.markForCheck();
} }
); );

21
apps/client/src/app/components/holding-detail-dialog/holding-detail-dialog.html

@ -152,8 +152,10 @@
>Investment</gf-value >Investment</gf-value
> >
</div> </div>
@if (dividendInBaseCurrency && user?.settings?.isExperimentalFeatures) { <div
<div class="col-6 mb-3"> *ngIf="dividendInBaseCurrency > 0 || !stakeRewards"
class="col-6 mb-3"
>
<gf-value <gf-value
i18n i18n
size="medium" size="medium"
@ -165,17 +167,20 @@
>Dividend</gf-value >Dividend</gf-value
> >
</div> </div>
<div class="col-6 mb-3">
<div
*ngIf="stakeRewards > 0 && dividendInBaseCurrency == 0"
class="col-6 mb-3"
>
<gf-value <gf-value
i18n i18n
size="medium" size="medium"
[isPercent]="true"
[locale]="data.locale" [locale]="data.locale"
[value]="dividendYieldPercentWithCurrencyEffect" [precision]="stakePrecision"
>Dividend Yield</gf-value [value]="stakeRewards"
> >Stake Rewards
</gf-value>
</div> </div>
}
<div class="col-6 mb-3"> <div class="col-6 mb-3">
<gf-value <gf-value
i18n i18n

3
apps/client/src/app/components/toggle/toggle.component.ts

@ -20,6 +20,9 @@ import { FormControl } from '@angular/forms';
export class ToggleComponent implements OnChanges, OnInit { export class ToggleComponent implements OnChanges, OnInit {
public static DEFAULT_DATE_RANGE_OPTIONS: ToggleOption[] = [ public static DEFAULT_DATE_RANGE_OPTIONS: ToggleOption[] = [
{ label: $localize`Today`, value: '1d' }, { label: $localize`Today`, value: '1d' },
{ label: $localize`1W`, value: '1w' },
{ label: $localize`1M`, value: '1m' },
{ label: $localize`3M`, value: '3m' },
{ label: $localize`YTD`, value: 'ytd' }, { label: $localize`YTD`, value: 'ytd' },
{ label: $localize`1Y`, value: '1y' }, { label: $localize`1Y`, value: '1y' },
{ label: $localize`5Y`, value: '5y' }, { label: $localize`5Y`, value: '5y' },

6
apps/client/src/app/pages/portfolio/activities/create-or-update-activity-dialog/create-or-update-activity-dialog.component.ts

@ -215,6 +215,10 @@ export class CreateOrUpdateActivityDialog implements OnDestroy {
this.activityForm.get('quantity').value * this.activityForm.get('quantity').value *
this.activityForm.get('unitPrice').value + this.activityForm.get('unitPrice').value +
this.activityForm.get('fee').value ?? 0; this.activityForm.get('fee').value ?? 0;
} else if (this.activityForm.get('type').value === 'STAKE') {
this.total =
this.activityForm.get('quantity').value * this.currentMarketPrice ??
0;
} else { } else {
this.total = this.total =
this.activityForm.get('quantity').value * this.activityForm.get('quantity').value *
@ -268,7 +272,7 @@ export class CreateOrUpdateActivityDialog implements OnDestroy {
if (this.activityForm.get('searchSymbol').invalid) { if (this.activityForm.get('searchSymbol').invalid) {
this.data.activity.SymbolProfile = null; this.data.activity.SymbolProfile = null;
} else if ( } else if (
['BUY', 'DIVIDEND', 'SELL'].includes( ['BUY', 'DIVIDEND', 'SELL', 'STAKE'].includes(
this.activityForm.get('type').value this.activityForm.get('type').value
) )
) { ) {

13
apps/client/src/app/pages/portfolio/activities/create-or-update-activity-dialog/create-or-update-activity-dialog.html

@ -49,6 +49,14 @@
>Revenue for lending out money</small >Revenue for lending out money</small
> >
</mat-option> </mat-option>
<mat-option class="line-height-1" value="STAKE">
<span
><b>{{ typesTranslationMap['STAKE'] }}</b></span
><br />
<small class="text-muted text-nowrap" i18n
>Stake rewards, stock dividends, free/gifted stocks</small
>
</mat-option>
<mat-option value="LIABILITY"> <mat-option value="LIABILITY">
<span <span
><b>{{ typesTranslationMap['LIABILITY'] }}</b></span ><b>{{ typesTranslationMap['LIABILITY'] }}</b></span
@ -193,7 +201,10 @@
class="mb-3" class="mb-3"
[ngClass]="{ 'd-none': activityForm.get('type')?.value === 'FEE' }" [ngClass]="{ 'd-none': activityForm.get('type')?.value === 'FEE' }"
> >
<div class="align-items-start d-flex"> <div
*ngIf="activityForm.controls['type']?.value !== 'STAKE'"
class="align-items-start d-flex"
>
<mat-form-field appearance="outline" class="w-100"> <mat-form-field appearance="outline" class="w-100">
<mat-label> <mat-label>
@switch (activityForm.get('type')?.value) { @switch (activityForm.get('type')?.value) {

3
apps/client/src/app/pages/portfolio/allocations/allocations-page.component.ts

@ -201,6 +201,9 @@ export class AllocationsPageComponent implements OnDestroy, OnInit {
private fetchPortfolioDetails() { private fetchPortfolioDetails() {
return this.dataService.fetchPortfolioDetails({ return this.dataService.fetchPortfolioDetails({
filters: this.userService.getFilters(), filters: this.userService.getFilters(),
parameters: {
isAllocation: true
},
withMarkets: true withMarkets: true
}); });
} }

48
apps/client/src/app/pages/portfolio/analysis/analysis-page.component.ts

@ -10,11 +10,12 @@ import {
User User
} from '@ghostfolio/common/interfaces'; } from '@ghostfolio/common/interfaces';
import { InvestmentItem } from '@ghostfolio/common/interfaces/investment-item.interface'; import { InvestmentItem } from '@ghostfolio/common/interfaces/investment-item.interface';
import { GroupBy, ToggleOption } from '@ghostfolio/common/types'; import { DateRange, GroupBy, ToggleOption } from '@ghostfolio/common/types';
import { translate } from '@ghostfolio/ui/i18n'; import { translate } from '@ghostfolio/ui/i18n';
import { ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; import { ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core';
import { SymbolProfile } from '@prisma/client'; import { SymbolProfile } from '@prisma/client';
import { Big } from 'big.js';
import { differenceInDays } from 'date-fns'; import { differenceInDays } from 'date-fns';
import { isNumber, sortBy } from 'lodash'; import { isNumber, sortBy } from 'lodash';
import { DeviceDetectorService } from 'ngx-device-detector'; import { DeviceDetectorService } from 'ngx-device-detector';
@ -32,6 +33,12 @@ export class AnalysisPageComponent implements OnDestroy, OnInit {
public benchmarks: Partial<SymbolProfile>[]; public benchmarks: Partial<SymbolProfile>[];
public bottom3: PortfolioPosition[]; public bottom3: PortfolioPosition[];
public dateRangeOptions = ToggleComponent.DEFAULT_DATE_RANGE_OPTIONS; public dateRangeOptions = ToggleComponent.DEFAULT_DATE_RANGE_OPTIONS;
public timeWeightedPerformanceOptions = [
{ label: $localize`No`, value: 'N' },
{ label: $localize`Both`, value: 'B' },
{ label: $localize`Only`, value: 'O' }
];
public selectedTimeWeightedPerformanceOption: string;
public daysInMarket: number; public daysInMarket: number;
public deviceType: string; public deviceType: string;
public dividendsByGroup: InvestmentItem[]; public dividendsByGroup: InvestmentItem[];
@ -53,8 +60,11 @@ export class AnalysisPageComponent implements OnDestroy, OnInit {
public performance: PortfolioPerformance; public performance: PortfolioPerformance;
public performanceDataItems: HistoricalDataItem[]; public performanceDataItems: HistoricalDataItem[];
public performanceDataItemsInPercentage: HistoricalDataItem[]; public performanceDataItemsInPercentage: HistoricalDataItem[];
public performanceDataItemsTimeWeightedInPercentage: HistoricalDataItem[] =
[];
public portfolioEvolutionDataLabel = $localize`Investment`; public portfolioEvolutionDataLabel = $localize`Investment`;
public streaks: PortfolioInvestments['streaks']; public streaks: PortfolioInvestments['streaks'];
public timeWeightedPerformance: string = 'N';
public top3: PortfolioPosition[]; public top3: PortfolioPosition[];
public unitCurrentStreak: string; public unitCurrentStreak: string;
public unitLongestStreak: string; public unitLongestStreak: string;
@ -125,6 +135,30 @@ export class AnalysisPageComponent implements OnDestroy, OnInit {
}); });
} }
public onChangeDateRange(dateRange: DateRange) {
this.dataService
.putUserSetting({ dateRange })
.pipe(takeUntil(this.unsubscribeSubject))
.subscribe(() => {
this.userService.remove();
this.userService
.get()
.pipe(takeUntil(this.unsubscribeSubject))
.subscribe((user) => {
this.user = user;
this.changeDetectorRef.markForCheck();
});
});
}
public onTimeWeightedPerformanceChanged(timeWeightedPerformance: string) {
this.timeWeightedPerformance = timeWeightedPerformance;
this.update();
}
public onChangeGroupBy(aMode: GroupBy) { public onChangeGroupBy(aMode: GroupBy) {
this.mode = aMode; this.mode = aMode;
this.fetchDividendsAndInvestments(); this.fetchDividendsAndInvestments();
@ -193,7 +227,9 @@ export class AnalysisPageComponent implements OnDestroy, OnInit {
this.dataService this.dataService
.fetchPortfolioPerformance({ .fetchPortfolioPerformance({
filters: this.userService.getFilters(), filters: this.userService.getFilters(),
range: this.user?.settings?.dateRange range: this.user?.settings?.dateRange,
timeWeightedPerformance:
this.timeWeightedPerformance === 'N' ? false : true
}) })
.pipe(takeUntil(this.unsubscribeSubject)) .pipe(takeUntil(this.unsubscribeSubject))
.subscribe(({ chart, firstOrderDate, performance }) => { .subscribe(({ chart, firstOrderDate, performance }) => {
@ -204,6 +240,7 @@ export class AnalysisPageComponent implements OnDestroy, OnInit {
this.performance = performance; this.performance = performance;
this.performanceDataItems = []; this.performanceDataItems = [];
this.performanceDataItemsInPercentage = []; this.performanceDataItemsInPercentage = [];
this.performanceDataItemsTimeWeightedInPercentage = [];
for (const [ for (const [
index, index,
@ -212,6 +249,7 @@ export class AnalysisPageComponent implements OnDestroy, OnInit {
netPerformanceInPercentageWithCurrencyEffect, netPerformanceInPercentageWithCurrencyEffect,
totalInvestmentValueWithCurrencyEffect, totalInvestmentValueWithCurrencyEffect,
valueInPercentage, valueInPercentage,
timeWeightedPerformance,
valueWithCurrencyEffect valueWithCurrencyEffect
} }
] of chart.entries()) { ] of chart.entries()) {
@ -232,6 +270,12 @@ export class AnalysisPageComponent implements OnDestroy, OnInit {
date, date,
value: netPerformanceInPercentageWithCurrencyEffect value: netPerformanceInPercentageWithCurrencyEffect
}); });
if ((this.timeWeightedPerformance ?? 'N') !== 'N') {
this.performanceDataItemsTimeWeightedInPercentage.push({
date,
value: chart[index].timeWeightedPerformance
});
}
} }
this.isLoadingInvestmentChart = false; this.isLoadingInvestmentChart = false;

30
apps/client/src/app/pages/portfolio/analysis/analysis-page.html

@ -11,10 +11,36 @@
[daysInMarket]="daysInMarket" [daysInMarket]="daysInMarket"
[isLoading]="isLoadingBenchmarkComparator || isLoadingInvestmentChart" [isLoading]="isLoadingBenchmarkComparator || isLoadingInvestmentChart"
[locale]="user?.settings?.locale" [locale]="user?.settings?.locale"
[performanceDataItems]="performanceDataItemsInPercentage" [performanceDataItems]="
timeWeightedPerformance === 'O'
? []
: performanceDataItemsInPercentage
"
[timeWeightedPerformanceDataItems]="
timeWeightedPerformance === 'N'
? []
: performanceDataItemsTimeWeightedInPercentage
"
[user]="user" [user]="user"
(benchmarkChanged)="onChangeBenchmark($event)" (benchmarkChanged)="onChangeBenchmark($event)"
/> ></gf-benchmark-comparator>
<div>
<div class="col-md-6 col-xs-12 d-flex">
<div
class="align-items-center d-flex flex-grow-1 h6 mb-0 py-2 text-truncate"
>
<span i18n>Include time-weighted performance </span>
<gf-toggle
[defaultValue]="timeWeightedPerformance"
[isLoading]="
isLoadingBenchmarkComparator || isLoadingInvestmentChart
"
[options]="timeWeightedPerformanceOptions"
(change)="onTimeWeightedPerformanceChanged($event.value)"
></gf-toggle>
</div>
</div>
</div>
</div> </div>
</div> </div>

2
apps/client/src/app/services/admin.service.ts

@ -224,6 +224,7 @@ export class AdminService {
sectors, sectors,
symbol, symbol,
symbolMapping, symbolMapping,
tags,
url url
}: AssetProfileIdentifier & UpdateAssetProfileDto) { }: AssetProfileIdentifier & UpdateAssetProfileDto) {
return this.http.patch<EnhancedSymbolProfile>( return this.http.patch<EnhancedSymbolProfile>(
@ -238,6 +239,7 @@ export class AdminService {
scraperConfiguration, scraperConfiguration,
sectors, sectors,
symbolMapping, symbolMapping,
tags,
url url
} }
); );

11
apps/client/src/app/services/data.service.ts

@ -474,15 +474,18 @@ export class DataService {
public fetchPortfolioDetails({ public fetchPortfolioDetails({
filters, filters,
parameters,
withMarkets = false withMarkets = false
}: { }: {
filters?: Filter[]; filters?: Filter[];
parameters?: any;
withMarkets?: boolean; withMarkets?: boolean;
} = {}): Observable<PortfolioDetails> { } = {}): Observable<PortfolioDetails> {
let params = this.buildFiltersAsQueryParams({ filters }); let params = this.buildFiltersAsQueryParams({ filters });
if (withMarkets) { if (withMarkets) {
params = params.append('withMarkets', withMarkets); params = params.append('withMarkets', withMarkets);
params = parameters ? params.appendAll(parameters) : params;
} }
return this.http return this.http
@ -578,11 +581,13 @@ export class DataService {
filters, filters,
range, range,
withExcludedAccounts = false, withExcludedAccounts = false,
timeWeightedPerformance = false,
withItems = false withItems = false
}: { }: {
filters?: Filter[]; filters?: Filter[];
range: DateRange; range: DateRange;
withExcludedAccounts?: boolean; withExcludedAccounts?: boolean;
timeWeightedPerformance?: boolean;
withItems?: boolean; withItems?: boolean;
}): Observable<PortfolioPerformanceResponse> { }): Observable<PortfolioPerformanceResponse> {
let params = this.buildFiltersAsQueryParams({ filters }); let params = this.buildFiltersAsQueryParams({ filters });
@ -591,6 +596,12 @@ export class DataService {
if (withExcludedAccounts) { if (withExcludedAccounts) {
params = params.append('withExcludedAccounts', withExcludedAccounts); params = params.append('withExcludedAccounts', withExcludedAccounts);
} }
if (timeWeightedPerformance) {
params = params.append(
'timeWeightedPerformance',
timeWeightedPerformance
);
}
if (withItems) { if (withItems) {
params = params.append('withItems', withItems); params = params.append('withItems', withItems);

2
apps/client/src/app/services/import-activities.service.ts

@ -348,6 +348,8 @@ export class ImportActivitiesService {
return 'LIABILITY'; return 'LIABILITY';
case 'sell': case 'sell':
return 'SELL'; return 'SELL';
case 'stake':
return 'STAKE';
default: default:
break; break;
} }

6
apps/client/src/app/services/user/user.service.ts

@ -53,21 +53,21 @@ export class UserService extends ObservableStore<UserStoreState> {
if (user?.settings['filters.accounts']) { if (user?.settings['filters.accounts']) {
filters.push({ filters.push({
id: user.settings['filters.accounts'][0], id: user.settings['filters.accounts'].join(','),
type: 'ACCOUNT' type: 'ACCOUNT'
}); });
} }
if (user?.settings['filters.assetClasses']) { if (user?.settings['filters.assetClasses']) {
filters.push({ filters.push({
id: user.settings['filters.assetClasses'][0], id: user.settings['filters.assetClasses'].join(','),
type: 'ASSET_CLASS' type: 'ASSET_CLASS'
}); });
} }
if (user?.settings['filters.tags']) { if (user?.settings['filters.tags']) {
filters.push({ filters.push({
id: user.settings['filters.tags'][0], id: user.settings['filters.tags'].join(','),
type: 'TAG' type: 'TAG'
}); });
} }

6
apps/ui-e2e/project.json

@ -3,6 +3,8 @@
"$schema": "../../node_modules/nx/schemas/project-schema.json", "$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "apps/ui-e2e/src", "sourceRoot": "apps/ui-e2e/src",
"projectType": "application", "projectType": "application",
"tags": [],
"implicitDependencies": ["ui"],
"targets": { "targets": {
"e2e": { "e2e": {
"executor": "@nx/cypress:cypress", "executor": "@nx/cypress:cypress",
@ -23,7 +25,5 @@
"lintFilePatterns": ["apps/ui-e2e/**/*.{js,ts}"] "lintFilePatterns": ["apps/ui-e2e/**/*.{js,ts}"]
} }
} }
}, }
"tags": [],
"implicitDependencies": ["ui"]
} }

46
libs/common/src/lib/chunkhelper.ts

@ -0,0 +1,46 @@
import { Prisma, PrismaClient } from '@prisma/client';
class Chunk<T> implements Iterable<T[] | undefined> {
protected constructor(
private readonly values: readonly T[],
private readonly size: number
) {}
*[Symbol.iterator]() {
const copy = [...this.values];
if (copy.length === 0) yield undefined;
while (copy.length) yield copy.splice(0, this.size);
}
map<U>(mapper: (items?: T[]) => U): U[] {
return Array.from(this).map((items) => mapper(items));
}
static of<U>(values: readonly U[]) {
return {
by: (size: number) => new Chunk(values, size)
};
}
}
export type Queryable<T, Result> = (
p: PrismaClient,
vs?: T[]
) => Prisma.PrismaPromise<Result>;
export class BatchPrismaClient {
constructor(
private readonly prisma: PrismaClient,
private readonly size = 32_000
) {}
over<T>(values: readonly T[]) {
return {
with: <Result>(queryable: Queryable<T, Result>) =>
this.prisma.$transaction(
Chunk.of(values)
.by(this.size)
.map((vs) => queryable(this.prisma, vs))
)
};
}
}

3
libs/common/src/lib/interfaces/admin-market-data.interface.ts

@ -1,4 +1,4 @@
import { AssetClass, AssetSubClass, DataSource } from '@prisma/client'; import { AssetClass, AssetSubClass, DataSource, Tag } from '@prisma/client';
export interface AdminMarketData { export interface AdminMarketData {
count: number; count: number;
@ -21,4 +21,5 @@ export interface AdminMarketDataItem {
name: string; name: string;
sectorsCount: number; sectorsCount: number;
symbol: string; symbol: string;
tags: Tag[];
} }

3
libs/common/src/lib/interfaces/enhanced-symbol-profile.interface.ts

@ -1,4 +1,4 @@
import { AssetClass, AssetSubClass, DataSource } from '@prisma/client'; import { AssetClass, AssetSubClass, DataSource, Tag } from '@prisma/client';
import { Country } from './country.interface'; import { Country } from './country.interface';
import { DataProviderInfo } from './data-provider-info.interface'; import { DataProviderInfo } from './data-provider-info.interface';
@ -30,4 +30,5 @@ export interface EnhancedSymbolProfile {
symbolMapping?: { [key: string]: string }; symbolMapping?: { [key: string]: string };
updatedAt: Date; updatedAt: Date;
url?: string; url?: string;
tags?: Tag[];
} }

2
libs/common/src/lib/interfaces/historical-data-item.interface.ts

@ -16,5 +16,7 @@ export interface HistoricalDataItem {
totalInvestmentValueWithCurrencyEffect?: number; totalInvestmentValueWithCurrencyEffect?: number;
value?: number; value?: number;
valueInPercentage?: number; valueInPercentage?: number;
timeWeightedPerformance?: number;
timeWeightedPerformanceWithCurrencyEffect?: number;
valueWithCurrencyEffect?: number; valueWithCurrencyEffect?: number;
} }

6
libs/common/src/lib/interfaces/symbol-metrics.interface.ts

@ -28,6 +28,9 @@ export interface SymbolMetrics {
}; };
netPerformance: Big; netPerformance: Big;
netPerformancePercentage: Big; netPerformancePercentage: Big;
netPerformanceValuesPercentage: {
[date: string]: Big;
};
netPerformancePercentageWithCurrencyEffectMap: { [key: DateRange]: Big }; netPerformancePercentageWithCurrencyEffectMap: { [key: DateRange]: Big };
netPerformanceValues: { netPerformanceValues: {
[date: string]: Big; [date: string]: Big;
@ -49,6 +52,9 @@ export interface SymbolMetrics {
totalInterestInBaseCurrency: Big; totalInterestInBaseCurrency: Big;
totalInvestment: Big; totalInvestment: Big;
totalInvestmentWithCurrencyEffect: Big; totalInvestmentWithCurrencyEffect: Big;
unitPrices: {
[date: string]: Big;
};
totalLiabilities: Big; totalLiabilities: Big;
totalLiabilitiesInBaseCurrency: Big; totalLiabilitiesInBaseCurrency: Big;
totalValuables: Big; totalValuables: Big;

9
libs/common/src/lib/types/date-range.type.ts

@ -1,9 +1,12 @@
export type DateRange = export type DateRange =
| '1d' | '1d'
| 'wtd'
| '1w'
| 'mtd'
| '1m'
| '3m'
| 'ytd'
| '1y' | '1y'
| '5y' | '5y'
| 'max' | 'max'
| 'mtd'
| 'wtd'
| 'ytd'
| string; // '2024', '2023', '2022', etc. | string; // '2024', '2023', '2022', etc.

51
libs/ui/src/lib/activities-table/activities-table.component.scss

@ -1,3 +1,54 @@
:host { :host {
display: block; display: block;
.activities {
overflow-x: auto;
.mat-mdc-table {
th {
::ng-deep {
.mat-sort-header-container {
justify-content: inherit;
}
}
}
.mat-mdc-row {
.type-badge {
background-color: rgba(var(--palette-foreground-text), 0.05);
border-radius: 1rem;
line-height: 1em;
ion-icon {
font-size: 1rem;
}
&.buy {
color: var(--green);
}
&.dividend {
color: var(--blue);
}
&.stake {
color: var(--blue);
}
&.item {
color: var(--purple);
}
&.liability {
color: var(--red);
}
&.sell {
color: var(--orange);
}
}
}
}
}
}
:host-context(.is-dark-theme) {
.mat-mdc-table {
.type-badge {
background-color: rgba(
var(--palette-foreground-text-dark),
0.1
) !important;
}
}
} }

38
libs/ui/src/lib/activity-type/activity-type.component.html

@ -7,21 +7,31 @@
interest: activityType === 'INTEREST', interest: activityType === 'INTEREST',
item: activityType === 'ITEM', item: activityType === 'ITEM',
liability: activityType === 'LIABILITY', liability: activityType === 'LIABILITY',
sell: activityType === 'SELL' sell: activityType === 'SELL',
stake: activityType === 'STAKE'
}" }"
> >
@if (activityType === 'BUY') { <ion-icon
<ion-icon name="arrow-up-circle-outline" /> *ngIf="activityType === 'BUY'"
} @else if (activityType === 'DIVIDEND' || activityType === 'INTEREST') { name="arrow-up-circle-outline"
<ion-icon name="add-circle-outline" /> ></ion-icon>
} @else if (activityType === 'FEE') { <ion-icon
<ion-icon name="hammer-outline" /> *ngIf="
} @else if (activityType === 'ITEM') { activityType === 'DIVIDEND' ||
<ion-icon name="cube-outline" /> activityType === 'INTEREST' ||
} @else if (activityType === 'LIABILITY') { activityType === 'STAKE'
<ion-icon name="flame-outline" /> "
} @else if (activityType === 'SELL') { name="add-circle-outline"
<ion-icon name="arrow-down-circle-outline" /> ></ion-icon>
} <ion-icon *ngIf="activityType === 'FEE'" name="hammer-outline"></ion-icon>
<ion-icon *ngIf="activityType === 'ITEM'" name="cube-outline"></ion-icon>
<ion-icon
*ngIf="activityType === 'LIABILITY'"
name="flame-outline"
></ion-icon>
<ion-icon
*ngIf="activityType === 'SELL'"
name="arrow-down-circle-outline"
></ion-icon>
<span class="d-none d-lg-block mx-1">{{ activityTypeLabel }}</span> <span class="d-none d-lg-block mx-1">{{ activityTypeLabel }}</span>
</div> </div>

50
libs/ui/src/lib/assistant/assistant.component.ts

@ -131,9 +131,9 @@ export class GfAssistantComponent implements OnChanges, OnDestroy, OnInit {
public dateRangeFormControl = new FormControl<string>(undefined); public dateRangeFormControl = new FormControl<string>(undefined);
public dateRangeOptions: IDateRangeOption[] = []; public dateRangeOptions: IDateRangeOption[] = [];
public filterForm = this.formBuilder.group({ public filterForm = this.formBuilder.group({
account: new FormControl<string>(undefined), account: new FormControl<string[]>(undefined),
assetClass: new FormControl<string>(undefined), assetClass: new FormControl<string[]>(undefined),
tag: new FormControl<string>(undefined) tag: new FormControl<string[]>(undefined)
}); });
public isLoading = false; public isLoading = false;
public isOpen = false; public isOpen = false;
@ -272,9 +272,9 @@ export class GfAssistantComponent implements OnChanges, OnDestroy, OnInit {
this.filterForm.setValue( this.filterForm.setValue(
{ {
account: this.user?.settings?.['filters.accounts']?.[0] ?? null, account: this.user?.settings?.['filters.accounts'] ?? null,
assetClass: this.user?.settings?.['filters.assetClasses']?.[0] ?? null, assetClass: this.user?.settings?.['filters.assetClasses'] ?? null,
tag: this.user?.settings?.['filters.tags']?.[0] ?? null tag: this.user?.settings?.['filters.tags'] ?? null
}, },
{ {
emitEvent: false emitEvent: false
@ -282,7 +282,7 @@ export class GfAssistantComponent implements OnChanges, OnDestroy, OnInit {
); );
} }
public hasFilter(aFormValue: { [key: string]: string }) { public hasFilter(aFormValue: { [key: string]: string[] }) {
return Object.values(aFormValue).some((value) => { return Object.values(aFormValue).some((value) => {
return !!value; return !!value;
}); });
@ -312,20 +312,28 @@ export class GfAssistantComponent implements OnChanges, OnDestroy, OnInit {
} }
public onApplyFilters() { public onApplyFilters() {
this.filtersChanged.emit([ let accountFilters =
{ this.filterForm
id: this.filterForm.get('account').value, .get('account')
type: 'ACCOUNT' .value?.reduce(
}, (arr, val) => [...arr, { id: val, type: 'ACCOUNT' }],
{ []
id: this.filterForm.get('assetClass').value, ) ?? [];
type: 'ASSET_CLASS' let assetClassFilters =
}, this.filterForm
{ .get('assetClass')
id: this.filterForm.get('tag').value, .value?.reduce(
type: 'TAG' (arr, val) => [...arr, { id: val, type: 'ASSET_CLASS' }],
} []
]); ) ?? [];
let tagFilters =
this.filterForm
.get('tag')
.value?.reduce((arr, val) => [...arr, { id: val, type: 'TAG' }], []) ??
[];
let filters = [...accountFilters, ...assetClassFilters];
filters = [...filters, ...tagFilters];
this.filtersChanged.emit(filters);
this.onCloseAssistant(); this.onCloseAssistant();
} }

6
libs/ui/src/lib/assistant/assistant.html

@ -105,7 +105,7 @@
<div class="mb-3"> <div class="mb-3">
<mat-form-field appearance="outline" class="w-100 without-hint"> <mat-form-field appearance="outline" class="w-100 without-hint">
<mat-label i18n>Accounts</mat-label> <mat-label i18n>Accounts</mat-label>
<mat-select formControlName="account"> <mat-select formControlName="account" multiple>
<mat-option [value]="null" /> <mat-option [value]="null" />
@for (account of accounts; track account.id) { @for (account of accounts; track account.id) {
<mat-option [value]="account.id"> <mat-option [value]="account.id">
@ -125,7 +125,7 @@
<div class="mb-3"> <div class="mb-3">
<mat-form-field appearance="outline" class="w-100 without-hint"> <mat-form-field appearance="outline" class="w-100 without-hint">
<mat-label i18n>Tags</mat-label> <mat-label i18n>Tags</mat-label>
<mat-select formControlName="tag"> <mat-select formControlName="tag" multiple>
<mat-option [value]="null" /> <mat-option [value]="null" />
@for (tag of tags; track tag.id) { @for (tag of tags; track tag.id) {
<mat-option [value]="tag.id">{{ tag.label }}</mat-option> <mat-option [value]="tag.id">{{ tag.label }}</mat-option>
@ -136,7 +136,7 @@
<div class="mb-3"> <div class="mb-3">
<mat-form-field appearance="outline" class="w-100 without-hint"> <mat-form-field appearance="outline" class="w-100 without-hint">
<mat-label i18n>Asset Classes</mat-label> <mat-label i18n>Asset Classes</mat-label>
<mat-select formControlName="assetClass"> <mat-select formControlName="assetClass" multiple>
<mat-option [value]="null" /> <mat-option [value]="null" />
@for (assetClass of assetClasses; track assetClass.id) { @for (assetClass of assetClasses; track assetClass.id) {
<mat-option [value]="assetClass.id">{{ <mat-option [value]="assetClass.id">{{

1
libs/ui/src/lib/i18n.ts

@ -38,6 +38,7 @@ const locales = {
ITEM: $localize`Valuable`, ITEM: $localize`Valuable`,
LIABILITY: $localize`Liability`, LIABILITY: $localize`Liability`,
SELL: $localize`Sell`, SELL: $localize`Sell`,
STAKE: $localize`Stake`,
// AssetClass (enum) // AssetClass (enum)
CASH: $localize`Cash`, CASH: $localize`Cash`,

185
migrations.json

@ -0,0 +1,185 @@
{
"migrations": [
{
"cli": "nx",
"version": "17.3.0-beta.6",
"description": "Updates the nx wrapper.",
"implementation": "./src/migrations/update-17-3-0/update-nxw",
"package": "nx",
"name": "17.3.0-update-nx-wrapper"
},
{
"cli": "nx",
"version": "18.0.0-beta.2",
"description": "Updates nx.json to disabled adding plugins when generating projects in an existing Nx workspace",
"implementation": "./src/migrations/update-18-0-0/disable-crystal-for-existing-workspaces",
"x-repair-skip": true,
"package": "nx",
"name": "18.0.0-disable-adding-plugins-for-existing-workspaces"
},
{
"version": "18.1.0-beta.3",
"description": "Moves affected.defaultBase to defaultBase in `nx.json`",
"implementation": "./src/migrations/update-17-2-0/move-default-base",
"package": "nx",
"name": "move-default-base-to-nx-json-root"
},
{
"cli": "nx",
"version": "18.1.0-beta.3",
"description": "Update to Cypress ^13.6.6 if the workspace is using Cypress v13 to ensure workspaces don't use v13.6.5 which has an issue when verifying Cypress.",
"implementation": "./src/migrations/update-18-1-0/update-cypress-version-13-6-6",
"package": "@nx/cypress",
"name": "update-cypress-version-13-6-6"
},
{
"cli": "nx",
"version": "17.2.6-beta.1",
"description": "Rename workspace rules from @nx/workspace/name to @nx/workspace-name",
"implementation": "./src/migrations/update-17-2-6-rename-workspace-rules/rename-workspace-rules",
"package": "@nx/eslint-plugin",
"name": "update-17-2-6-rename-workspace-rules"
},
{
"version": "17.1.0-beta.2",
"description": "Move jest executor options to nx.json targetDefaults",
"implementation": "./src/migrations/update-17-1-0/move-options-to-target-defaults",
"package": "@nx/jest",
"name": "move-options-to-target-defaults"
},
{
"cli": "nx",
"version": "17.1.0-beta.5",
"requires": {
"@angular/core": ">=17.0.0"
},
"description": "Update the @angular/cli package version to ~17.0.0.",
"factory": "./src/migrations/update-17-1-0/update-angular-cli",
"package": "@nx/angular",
"name": "update-angular-cli-version-17-0-0"
},
{
"cli": "nx",
"version": "17.1.0-beta.5",
"requires": {
"@angular/core": ">=17.0.0"
},
"description": "Rename 'browserTarget' to 'buildTarget'.",
"factory": "./src/migrations/update-17-1-0/browser-target-to-build-target",
"package": "@nx/angular",
"name": "rename-browser-target-to-build-target"
},
{
"cli": "nx",
"version": "17.1.0-beta.5",
"requires": {
"@angular/core": ">=17.0.0"
},
"description": "Replace usages of '@nguniversal/builders' with '@angular-devkit/build-angular'.",
"factory": "./src/migrations/update-17-1-0/replace-nguniversal-builders",
"package": "@nx/angular",
"name": "replace-nguniversal-builders"
},
{
"cli": "nx",
"version": "17.1.0-beta.5",
"requires": {
"@angular/core": ">=17.0.0"
},
"description": "Replace usages of '@nguniversal/' packages with '@angular/ssr'.",
"factory": "./src/migrations/update-17-1-0/replace-nguniversal-engines",
"package": "@nx/angular",
"name": "replace-nguniversal-engines"
},
{
"cli": "nx",
"version": "17.1.0-beta.5",
"requires": {
"@angular/core": ">=17.0.0"
},
"description": "Replace the deep imports from 'zone.js/dist/zone' and 'zone.js/dist/zone-testing' with 'zone.js' and 'zone.js/testing'.",
"factory": "./src/migrations/update-17-1-0/update-zone-js-deep-import",
"package": "@nx/angular",
"name": "update-zone-js-deep-import"
},
{
"cli": "nx",
"version": "17.2.0-beta.2",
"description": "Rename '@nx/angular:webpack-dev-server' executor to '@nx/angular:dev-server'",
"factory": "./src/migrations/update-17-2-0/rename-webpack-dev-server",
"package": "@nx/angular",
"name": "rename-webpack-dev-server-executor"
},
{
"cli": "nx",
"version": "17.3.0-beta.10",
"requires": {
"@angular/core": ">=17.1.0"
},
"description": "Update the @angular/cli package version to ~17.1.0.",
"factory": "./src/migrations/update-17-3-0/update-angular-cli",
"package": "@nx/angular",
"name": "update-angular-cli-version-17-1-0"
},
{
"cli": "nx",
"version": "17.3.0-beta.10",
"requires": {
"@angular/core": ">=17.1.0"
},
"description": "Add 'browser-sync' as dev dependency when '@angular-devkit/build-angular:ssr-dev-server' or '@nx/angular:module-federation-dev-ssr' is used.",
"factory": "./src/migrations/update-17-3-0/add-browser-sync-dependency",
"package": "@nx/angular",
"name": "add-browser-sync-dependency"
},
{
"cli": "nx",
"version": "17.3.0-beta.10",
"requires": {
"@angular/core": ">=17.1.0"
},
"description": "Add 'autoprefixer' as dev dependency when '@nx/angular:ng-packagr-lite' or '@nx/angular:package` is used.",
"factory": "./src/migrations/update-17-3-0/add-autoprefixer-dependency",
"package": "@nx/angular",
"name": "add-autoprefixer-dependency"
},
{
"cli": "nx",
"version": "18.0.0-beta.0",
"description": "Add NX_MF_DEV_SERVER_STATIC_REMOTES to inputs for task hashing when '@nx/angular:webpack-browser' is used for Module Federation.",
"factory": "./src/migrations/update-18-0-0/add-mf-env-var-to-target-defaults",
"package": "@nx/angular",
"name": "add-module-federation-env-var-to-target-defaults"
},
{
"cli": "nx",
"version": "18.1.0-beta.1",
"requires": {
"@angular/core": ">=17.2.0"
},
"description": "Update the @angular/cli package version to ~17.2.0.",
"factory": "./src/migrations/update-18-1-0/update-angular-cli",
"package": "@nx/angular",
"name": "update-angular-cli-version-17-2-0"
},
{
"cli": "nx",
"version": "18.1.1-beta.0",
"description": "Ensure targetDefaults inputs for task hashing when '@nx/angular:webpack-browser' is used are correct for Module Federation.",
"factory": "./src/migrations/update-18-1-1/fix-target-defaults-inputs",
"package": "@nx/angular",
"name": "fix-target-defaults-for-webpack-browser"
},
{
"cli": "nx",
"version": "18.2.0-beta.0",
"requires": {
"@angular/core": ">=17.3.0"
},
"description": "Update the @angular/cli package version to ~17.3.0.",
"factory": "./src/migrations/update-18-2-0/update-angular-cli",
"package": "@nx/angular",
"name": "update-angular-cli-version-17-3-0"
}
]
}

3
nx.json

@ -71,5 +71,6 @@
] ]
}, },
"parallel": 1, "parallel": 1,
"defaultBase": "origin/main" "defaultBase": "origin/main",
"useInferencePlugins": false
} }

4804
package-lock.json

File diff suppressed because it is too large

6
package.json

@ -51,6 +51,7 @@
"ts-node": "ts-node", "ts-node": "ts-node",
"update": "nx migrate latest", "update": "nx migrate latest",
"watch:server": "nx run api:copy-assets && nx run api:build --watch", "watch:server": "nx run api:copy-assets && nx run api:build --watch",
"profile:server": "nx run api:profile",
"watch:test": "nx test --watch", "watch:test": "nx test --watch",
"workspace-generator": "nx workspace-generator" "workspace-generator": "nx workspace-generator"
}, },
@ -90,6 +91,7 @@
"@simplewebauthn/server": "9.0.3", "@simplewebauthn/server": "9.0.3",
"@stripe/stripe-js": "3.5.0", "@stripe/stripe-js": "3.5.0",
"alphavantage": "2.2.0", "alphavantage": "2.2.0",
"await-lock": "^2.2.2",
"big.js": "6.2.1", "big.js": "6.2.1",
"body-parser": "1.20.2", "body-parser": "1.20.2",
"bootstrap": "4.6.0", "bootstrap": "4.6.0",
@ -140,13 +142,13 @@
"zone.js": "0.14.10" "zone.js": "0.14.10"
}, },
"devDependencies": { "devDependencies": {
"@angular-devkit/build-angular": "18.1.1", "@angular-devkit/build-angular": "18.2.5",
"@angular-devkit/core": "18.1.1", "@angular-devkit/core": "18.1.1",
"@angular-devkit/schematics": "18.1.1", "@angular-devkit/schematics": "18.1.1",
"@angular-eslint/eslint-plugin": "18.1.0", "@angular-eslint/eslint-plugin": "18.1.0",
"@angular-eslint/eslint-plugin-template": "18.1.0", "@angular-eslint/eslint-plugin-template": "18.1.0",
"@angular-eslint/template-parser": "18.1.0", "@angular-eslint/template-parser": "18.1.0",
"@angular/cli": "18.1.1", "@angular/cli": "18.2.1",
"@angular/compiler-cli": "18.1.1", "@angular/compiler-cli": "18.1.1",
"@angular/language-service": "18.1.1", "@angular/language-service": "18.1.1",
"@angular/localize": "18.1.1", "@angular/localize": "18.1.1",

22
prisma/migrations/20231108082445_added_tags_to_holding/migration.sql

@ -0,0 +1,22 @@
-- AlterEnum
ALTER TYPE "Type" ADD VALUE IF NOT EXISTS 'STAKE';
-- CreateTable
CREATE TABLE IF NOT EXISTS "_SymbolProfileToTag" (
"A" TEXT NOT NULL,
"B" TEXT NOT NULL
);
-- CreateIndex
CREATE UNIQUE INDEX IF NOT EXISTS "_SymbolProfileToTag_AB_unique" ON "_SymbolProfileToTag"("A", "B");
-- CreateIndex
CREATE INDEX IF NOT EXISTS "_SymbolProfileToTag_B_index" ON "_SymbolProfileToTag"("B");
-- AddForeignKey
ALTER TABLE "_SymbolProfileToTag" DROP CONSTRAINT IF EXISTS "_SymbolProfileToTag_A_fkey" ;
ALTER TABLE "_SymbolProfileToTag" ADD CONSTRAINT "_SymbolProfileToTag_A_fkey" FOREIGN KEY ("A") REFERENCES "SymbolProfile"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "_SymbolProfileToTag" DROP CONSTRAINT IF EXISTS "_SymbolProfileToTag_B_fkey" ;
ALTER TABLE "_SymbolProfileToTag" ADD CONSTRAINT "_SymbolProfileToTag_B_fkey" FOREIGN KEY ("B") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE;

3
prisma/schema.prisma

@ -175,6 +175,7 @@ model SymbolProfile {
symbolMapping Json? symbolMapping Json?
url String? url String?
Order Order[] Order Order[]
tags Tag[]
SymbolProfileOverrides SymbolProfileOverrides? SymbolProfileOverrides SymbolProfileOverrides?
@@unique([dataSource, symbol]) @@unique([dataSource, symbol])
@ -217,6 +218,7 @@ model Tag {
orders Order[] orders Order[]
userId String? userId String?
User User? @relation(fields: [userId], onDelete: Cascade, references: [id]) User User? @relation(fields: [userId], onDelete: Cascade, references: [id])
symbolProfile SymbolProfile[]
@@unique([name, userId]) @@unique([name, userId])
@@index([name]) @@index([name])
@ -310,6 +312,7 @@ enum Type {
ITEM ITEM
LIABILITY LIABILITY
SELL SELL
STAKE
} }
enum ViewMode { enum ViewMode {

17248
yarn-error.log

File diff suppressed because it is too large
Loading…
Cancel
Save