Skip to content

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

16.0 KB
Raw Blame
import { GfBenchmarkComparatorComponent } from '@ghostfolio/client/components/benchmark-comparator/benchmark-comparator.component';
import { UserService } from '@ghostfolio/client/services/user/user.service';
import {
  DEFAULT_DATE_RANGE,
  NUMERICAL_PRECISION_THRESHOLD_6_FIGURES
} from '@ghostfolio/common/config';
import { SubscriptionType } from '@ghostfolio/common/enums';
import { canOpenHoldingDetail } from '@ghostfolio/common/helper';
import {
  InvestmentItem,
  LineChartItem,
  PortfolioInvestmentsResponse,
  PortfolioPerformance,
  PortfolioPosition,
  User
} from '@ghostfolio/common/interfaces';
import { hasPermission, permissions } from '@ghostfolio/common/permissions';
import { hasScope, scopes } from '@ghostfolio/common/scopes';
import type {
  AiPromptMode,
  GroupBy,
  ToggleOption
} from '@ghostfolio/common/types';
import { PerformanceCalculationType } from '@ghostfolio/common/types/performance-calculation-type.type';
import type { SymbolProfile } from '@ghostfolio/prisma/browser';
import { translate } from '@ghostfolio/ui/i18n';
import { GfInvestmentChartComponent } from '@ghostfolio/ui/investment-chart';
import { GfPremiumIndicatorComponent } from '@ghostfolio/ui/premium-indicator';
import { DataService } from '@ghostfolio/ui/services';
import { GfToggleComponent } from '@ghostfolio/ui/toggle';
import { GfValueComponent } from '@ghostfolio/ui/value';

import { Clipboard } from '@angular/cdk/clipboard';
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  computed,
  DestroyRef,
  inject,
  OnInit,
  signal,
  viewChild
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatMenuModule, MatMenuTrigger } from '@angular/material/menu';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSnackBar } from '@angular/material/snack-bar';
import { RouterModule } from '@angular/router';
import { IonIcon } from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { copyOutline, ellipsisVertical } from 'ionicons/icons';
import { isNumber, keyBy, sortBy, union } from 'lodash-es';
import ms from 'ms';
import { DeviceDetectorService } from 'ngx-device-detector';
import { NgxSkeletonLoaderModule } from 'ngx-skeleton-loader';
import { forkJoin } from 'rxjs';

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    GfBenchmarkComparatorComponent,
    GfInvestmentChartComponent,
    GfPremiumIndicatorComponent,
    GfToggleComponent,
    GfValueComponent,
    IonIcon,
    MatButtonModule,
    MatCardModule,
    MatMenuModule,
    MatProgressSpinnerModule,
    NgxSkeletonLoaderModule,
    RouterModule
  ],
  selector: 'gf-analysis-page',
  styleUrls: ['./analysis-page.scss'],
  templateUrl: './analysis-page.html'
})
export class GfAnalysisPageComponent implements OnInit {
  protected benchmark?: Partial<SymbolProfile>;
  protected benchmarkDataItems: LineChartItem[] = [];
  protected readonly benchmarks: Partial<SymbolProfile>[];
  protected bottom3: PortfolioPosition[];
  protected dividendsByGroup: InvestmentItem[];
  protected readonly dividendTimelineDataLabel = $localize`Dividend`;
  protected hasPermissionToReadAiPrompt: boolean;
  protected investments: InvestmentItem[];
  protected readonly investmentTimelineDataLabel = $localize`Invested Capital`;
  protected investmentsByGroup: InvestmentItem[];
  protected isLoadingAnalysisPrompt: boolean;
  protected isLoadingBenchmarkComparator: boolean;
  protected isLoadingDividendTimelineChart: boolean;
  protected isLoadingInvestmentChart: boolean;
  protected isLoadingInvestmentTimelineChart: boolean;
  protected isLoadingPerformanceTimelineChart: boolean;
  protected isLoadingPortfolioPrompt: boolean;
  protected readonly mode = signal<GroupBy>('month');
  protected readonly modeOptions: ToggleOption<GroupBy>[] = [
    { label: $localize`Monthly`, value: 'month' },
    { label: $localize`Yearly`, value: 'year' }
  ];
  protected performance: PortfolioPerformance;
  protected readonly PerformanceCalculationType = PerformanceCalculationType;
  protected performanceDataItems: LineChartItem[];
  protected performanceDataItemsInPercentage: LineChartItem[];
  protected performancePercentagesByYear: InvestmentItem[];
  protected readonly performanceTimelineDataLabel = $localize`Net Performance`;
  protected readonly portfolioEvolutionDataLabel = $localize`Invested Capital`;
  protected precision = 2;
  protected savingsRatePerMonth: number | undefined;
  protected streaks: PortfolioInvestmentsResponse['streaks'];
  protected top3: PortfolioPosition[];
  protected unitCurrentStreak: string;
  protected unitLongestStreak: string;
  protected user: User;

  private readonly actionsMenuButton = viewChild.required(MatMenuTrigger);
  private readonly deviceType = computed(
    () => this.deviceDetectorService.deviceInfo().deviceType
  );
  private dateOfFirstActivity: Date;

  private readonly changeDetectorRef = inject(ChangeDetectorRef);
  private readonly clipboard = inject(Clipboard);
  private readonly dataService = inject(DataService);
  private readonly destroyRef = inject(DestroyRef);
  private readonly deviceDetectorService = inject(DeviceDetectorService);
  private readonly snackBar = inject(MatSnackBar);
  private readonly userService = inject(UserService);

  public constructor() {
    const { benchmarks } = this.dataService.fetchInfo();
    this.benchmarks = benchmarks;

    addIcons({ copyOutline, ellipsisVertical });
  }

  get savingsRate() {
    if (!this.savingsRatePerMonth) {
      return undefined;
    }

    return this.mode() === 'year'
      ? this.savingsRatePerMonth * 12
      : this.savingsRatePerMonth;
  }

  public ngOnInit() {
    this.userService.stateChanged
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe((state) => {
        if (state?.user) {
          this.user = state.user;

          this.benchmark = this.benchmarks.find(({ id }) => {
            return id === this.user.settings?.benchmark;
          });

          this.hasPermissionToReadAiPrompt = hasPermission(
            this.user.permissions,
            permissions.readAiPrompt
          );

          this.update();
        }

        this.changeDetectorRef.markForCheck();
      });
  }

  protected onChangeBenchmark(symbolProfileId: string) {
    this.dataService
      .putUserSetting({ benchmark: symbolProfileId })
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(() => {
        this.userService
          .get(true)
          .pipe(takeUntilDestroyed(this.destroyRef))
          .subscribe((user) => {
            this.user = user;

            this.changeDetectorRef.markForCheck();
          });
      });
  }

  protected onChangeGroupBy(aMode: GroupBy) {
    this.mode.set(aMode);
    this.fetchDividendsAndInvestments();
  }

  protected onCopyPromptToClipboard(mode: AiPromptMode) {
    if (mode === 'analysis') {
      this.isLoadingAnalysisPrompt = true;
    } else if (mode === 'portfolio') {
      this.isLoadingPortfolioPrompt = true;
    }

    this.dataService
      .fetchPrompt({
        mode,
        filters: this.userService.getFilters()
      })
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(({ prompt }) => {
        this.clipboard.copy(prompt);

        const snackBarRef = this.snackBar.open(
          '✅ ' + $localize`AI prompt has been copied to the clipboard`,
          $localize`Open Duck.ai` + ' →',
          {
            duration: ms('7 seconds')
          }
        );

        snackBarRef
          .onAction()
          .pipe(takeUntilDestroyed(this.destroyRef))
          .subscribe(() => {
            window.open('https://duck.ai', '_blank');
          });

        this.actionsMenuButton().closeMenu();

        if (mode === 'analysis') {
          this.isLoadingAnalysisPrompt = false;
        } else if (mode === 'portfolio') {
          this.isLoadingPortfolioPrompt = false;
        }

        this.changeDetectorRef.markForCheck();
      });
  }

  protected showValuesInPercentage() {
    return (
      !hasScope(this.user?.scopes, scopes.portfolioReadValues) ||
      this.user?.settings?.isRestrictedView
    );
  }

  private fetchDividendsAndInvestments() {
    this.isLoadingDividendTimelineChart = true;
    this.isLoadingInvestmentTimelineChart = true;

    forkJoin({
      dividends: this.dataService.fetchDividends({
        filters: this.userService.getFilters(),
        groupBy: this.mode(),
        range: this.user?.settings?.dateRange ?? DEFAULT_DATE_RANGE
      }),
      investments: this.dataService.fetchInvestments({
        filters: this.userService.getFilters(),
        groupBy: this.mode(),
        range: this.user?.settings?.dateRange ?? DEFAULT_DATE_RANGE
      })
    })
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(
        ({
          dividends: { dividends },
          investments: { investments, savingsRate, streaks }
        }) => {
          // Expand both timelines to the union of their groups so that the
          // charts share the same axis, independent of whether a dividend or
          // an investment has been tracked in a given group
          const dividendByDate = keyBy(dividends, 'date');
          const investmentByDate = keyBy(investments, 'date');

          const dates = sortBy(
            union(Object.keys(dividendByDate), Object.keys(investmentByDate))
          );

          this.dividendsByGroup = dates.map((date) => {
            return {
              date,
              investment: dividendByDate[date]?.investment ?? 0
            };
          });

          this.investmentsByGroup = dates.map((date) => {
            return {
              date,
              investment: investmentByDate[date]?.investment ?? 0
            };
          });

          this.savingsRatePerMonth = savingsRate;
          this.streaks = streaks;

          this.unitCurrentStreak =
            this.mode() === 'year'
              ? this.streaks?.currentStreak === 1
                ? translate('YEAR')
                : translate('YEARS')
              : this.streaks?.currentStreak === 1
                ? translate('MONTH')
                : translate('MONTHS');

          this.unitLongestStreak =
            this.mode() === 'year'
              ? this.streaks?.longestStreak === 1
                ? translate('YEAR')
                : translate('YEARS')
              : this.streaks?.longestStreak === 1
                ? translate('MONTH')
                : translate('MONTHS');

          this.isLoadingDividendTimelineChart = false;
          this.isLoadingInvestmentTimelineChart = false;

          this.changeDetectorRef.markForCheck();
        }
      );
  }

  private fetchPerformanceByYear() {
    this.isLoadingPerformanceTimelineChart = true;

    this.dataService
      .fetchPortfolioPerformance({
        filters: this.userService.getFilters(),
        groupBy: 'year',
        range: this.user?.settings?.dateRange ?? DEFAULT_DATE_RANGE
      })
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(({ chart }) => {
        this.performancePercentagesByYear = [];

        for (const {
          date,
          netPerformanceInPercentageWithCurrencyEffect
        } of chart ?? []) {
          if (isNumber(netPerformanceInPercentageWithCurrencyEffect)) {
            this.performancePercentagesByYear.push({
              date,
              investment: netPerformanceInPercentageWithCurrencyEffect
            });
          }
        }

        this.isLoadingPerformanceTimelineChart = false;

        this.changeDetectorRef.markForCheck();
      });
  }

  private update() {
    this.isLoadingInvestmentChart = true;

    this.dataService
      .fetchPortfolioPerformance({
        filters: this.userService.getFilters(),
        range: this.user?.settings?.dateRange ?? DEFAULT_DATE_RANGE
      })
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(({ chart, dateOfFirstActivity, performance }) => {
        this.dateOfFirstActivity = dateOfFirstActivity ?? new Date();

        this.investments = [];
        this.performance = performance;
        this.performanceDataItems = [];
        this.performanceDataItemsInPercentage = [];

        for (const {
          date,
          dividendInPercentageWithCurrencyEffect,
          netPerformanceInPercentageWithCurrencyEffect,
          totalInvestmentValueWithCurrencyEffect,
          valueInPercentage,
          valueWithCurrencyEffect
        } of chart ?? []) {
          if (totalInvestmentValueWithCurrencyEffect !== undefined) {
            this.investments.push({
              date,
              investment: totalInvestmentValueWithCurrencyEffect
            });
          }

          const value = isNumber(valueWithCurrencyEffect)
            ? valueWithCurrencyEffect
            : valueInPercentage;

          if (isNumber(value)) {
            this.performanceDataItems.push({
              date,
              value
            });
          }

          if (isNumber(netPerformanceInPercentageWithCurrencyEffect)) {
            this.performanceDataItemsInPercentage.push({
              date,
              value:
                netPerformanceInPercentageWithCurrencyEffect -
                (dividendInPercentageWithCurrencyEffect ?? 0)
            });
          }
        }

        if (
          this.deviceType() === 'mobile' &&
          this.performance.currentValueInBaseCurrency >=
            NUMERICAL_PRECISION_THRESHOLD_6_FIGURES
        ) {
          this.precision = 0;
        }

        this.isLoadingInvestmentChart = false;

        this.updateBenchmarkDataItems();

        this.changeDetectorRef.markForCheck();
      });

    this.dataService
      .fetchPortfolioHoldings({
        filters: [
          ...this.userService.getFilters(),
          { id: 'ACTIVE', type: 'HOLDING_TYPE' }
        ],
        range: this.user?.settings?.dateRange
      })
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(({ holdings }) => {
        const holdingsSorted = sortBy(
          holdings.filter((holding) => {
            return (
              canOpenHoldingDetail(holding) &&
              isNumber(holding.netPerformancePercentWithCurrencyEffect)
            );
          }),
          'netPerformancePercentWithCurrencyEffect'
        ).reverse();

        this.top3 = holdingsSorted
          .filter(
            ({ netPerformancePercentWithCurrencyEffect }) =>
              netPerformancePercentWithCurrencyEffect > 0
          )
          .slice(0, 3);

        this.bottom3 = holdingsSorted
          .filter(
            ({ netPerformancePercentWithCurrencyEffect }) =>
              netPerformancePercentWithCurrencyEffect < 0
          )
          .slice(-3)
          .reverse();

        this.changeDetectorRef.markForCheck();
      });

    this.fetchDividendsAndInvestments();

    if (
      this.user?.settings?.isExperimentalFeatures &&
      this.user?.subscription?.type !== SubscriptionType.Basic
    ) {
      this.fetchPerformanceByYear();
    }

    this.changeDetectorRef.markForCheck();
  }

  private updateBenchmarkDataItems() {
    this.benchmarkDataItems = [];

    if (this.user.settings.benchmark) {
      const { dataSource, symbol } =
        this.benchmarks.find(({ id }) => {
          return id === this.user.settings.benchmark;
        }) ?? {};

      if (dataSource && symbol) {
        this.isLoadingBenchmarkComparator = true;

        this.dataService
          .fetchBenchmarkForUser({
            dataSource,
            symbol,
            filters: this.userService.getFilters(),
            range: this.user?.settings?.dateRange ?? DEFAULT_DATE_RANGE,
            startDate: this.dateOfFirstActivity
          })
          .pipe(takeUntilDestroyed(this.destroyRef))
          .subscribe(({ marketData }) => {
            this.benchmarkDataItems = marketData.map(({ date, value }) => {
              return {
                date,
                value
              };
            });

            this.isLoadingBenchmarkComparator = false;

            this.changeDetectorRef.markForCheck();
          });
      }
    }
  }
}