mirror of https://github.com/ghostfolio/ghostfolio
committed by
GitHub
411 changed files with 32992 additions and 15485 deletions
@ -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 |
@ -0,0 +1,12 @@ |
|||
import { IsISO8601, IsNumber, IsUUID } from 'class-validator'; |
|||
|
|||
export class CreateAccountBalanceDto { |
|||
@IsUUID() |
|||
accountId: string; |
|||
|
|||
@IsNumber() |
|||
balance: number; |
|||
|
|||
@IsISO8601() |
|||
date: string; |
|||
} |
@ -1,9 +1,12 @@ |
|||
import { IsString } from 'class-validator'; |
|||
import { IsString, IsUrl } from 'class-validator'; |
|||
|
|||
export class CreatePlatformDto { |
|||
@IsString() |
|||
name: string; |
|||
|
|||
@IsString() |
|||
@IsUrl({ |
|||
protocols: ['https'], |
|||
require_protocol: true |
|||
}) |
|||
url: string; |
|||
} |
|||
|
@ -0,0 +1,302 @@ |
|||
import { getFactor } from '@ghostfolio/api/helper/portfolio.helper'; |
|||
import { DATE_FORMAT, parseDate, resetHours } from '@ghostfolio/common/helper'; |
|||
import { |
|||
HistoricalDataItem, |
|||
SymbolMetrics, |
|||
UniqueAsset |
|||
} from '@ghostfolio/common/interfaces'; |
|||
import { PortfolioSnapshot, TimelinePosition } from '@ghostfolio/common/models'; |
|||
|
|||
import { Big } from 'big.js'; |
|||
import { addDays, eachDayOfInterval, format } from 'date-fns'; |
|||
|
|||
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 } = {}; |
|||
|
|||
protected calculateOverallPerformance( |
|||
positions: TimelinePosition[] |
|||
): PortfolioSnapshot { |
|||
return super.calculateOverallPerformance(positions); |
|||
} |
|||
|
|||
protected getSymbolMetrics({ |
|||
dataSource, |
|||
end, |
|||
exchangeRates, |
|||
isChartMode = false, |
|||
marketSymbolMap, |
|||
start, |
|||
step = 1, |
|||
symbol |
|||
}: { |
|||
end: Date; |
|||
exchangeRates: { [dateString: string]: number }; |
|||
isChartMode?: boolean; |
|||
marketSymbolMap: { |
|||
[date: string]: { [symbol: string]: Big }; |
|||
}; |
|||
start: Date; |
|||
step?: number; |
|||
} & UniqueAsset): SymbolMetrics { |
|||
return super.getSymbolMetrics({ |
|||
dataSource, |
|||
end, |
|||
exchangeRates, |
|||
isChartMode, |
|||
marketSymbolMap, |
|||
start, |
|||
step, |
|||
symbol |
|||
}); |
|||
} |
|||
|
|||
public override async getChartData({ |
|||
end = new Date(Date.now()), |
|||
start, |
|||
step = 1 |
|||
}: { |
|||
end?: Date; |
|||
start: Date; |
|||
step?: number; |
|||
}): Promise<HistoricalDataItem[]> { |
|||
const timelineHoldings = this.getHoldings(start, end); |
|||
const calculationDates = Object.keys(timelineHoldings) |
|||
.filter((date) => { |
|||
let parsed = parseDate(date); |
|||
parsed >= start && parsed <= end; |
|||
}) |
|||
.sort(); |
|||
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 |
|||
}); |
|||
|
|||
let totalInvestment = Object.keys(timelineHoldings[startString]).reduce( |
|||
(sum, holding) => { |
|||
return sum.plus( |
|||
timelineHoldings[startString][holding].mul( |
|||
this.marketMap[startString][holding] |
|||
) |
|||
); |
|||
}, |
|||
new Big(0) |
|||
); |
|||
|
|||
let previousNetPerformanceInPercentage = new Big(0); |
|||
let previousNetPerformanceInPercentageWithCurrencyEffect = new Big(0); |
|||
|
|||
for (let i = 1; i < calculationDates.length; i++) { |
|||
const date = calculationDates[i]; |
|||
const previousDate = calculationDates[i - 1]; |
|||
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.mul( |
|||
netPerformanceInPercentage.plus(1) |
|||
); |
|||
previousNetPerformanceInPercentageWithCurrencyEffect = |
|||
previousNetPerformanceInPercentageWithCurrencyEffect.mul( |
|||
netPerformanceInPercentageWithCurrencyEffect.plus(1) |
|||
); |
|||
|
|||
data.push({ |
|||
date, |
|||
netPerformanceInPercentage: |
|||
previousNetPerformanceInPercentage.toNumber(), |
|||
netPerformanceInPercentageWithCurrencyEffect: |
|||
previousNetPerformanceInPercentageWithCurrencyEffect.toNumber() |
|||
}); |
|||
} |
|||
|
|||
return data; |
|||
} |
|||
|
|||
private async handleSingleHolding( |
|||
previousDate: string, |
|||
holding: string, |
|||
date: string, |
|||
totalInvestment, |
|||
timelineHoldings: { [date: string]: { [symbol: string]: Big } }, |
|||
netPerformanceInPercentage, |
|||
netPerformanceInPercentageWithCurrencyEffect, |
|||
newTotalInvestment |
|||
) { |
|||
const previousPrice = this.marketMap[previousDate][holding]; |
|||
const currentPrice = this.marketMap[date][holding]; |
|||
const previousPriceInBaseCurrency = |
|||
await this.exchangeRateDataService.toCurrencyAtDate( |
|||
previousPrice.toNumber(), |
|||
this.getCurrency(holding), |
|||
this.currency, |
|||
parseDate(previousDate) |
|||
); |
|||
const portfolioWeight = totalInvestment |
|||
? timelineHoldings[previousDate][holding] |
|||
.mul(previousPriceInBaseCurrency) |
|||
.div(totalInvestment) |
|||
: 0; |
|||
|
|||
netPerformanceInPercentage = netPerformanceInPercentage.plus( |
|||
currentPrice.div(previousPrice).minus(1).mul(portfolioWeight) |
|||
); |
|||
|
|||
const priceInBaseCurrency = |
|||
await this.exchangeRateDataService.toCurrencyAtDate( |
|||
currentPrice.toNumber(), |
|||
this.getCurrency(holding), |
|||
this.currency, |
|||
parseDate(date) |
|||
); |
|||
netPerformanceInPercentageWithCurrencyEffect = |
|||
netPerformanceInPercentageWithCurrencyEffect.plus( |
|||
new Big(priceInBaseCurrency) |
|||
.div(new Big(previousPriceInBaseCurrency)) |
|||
.minus(1) |
|||
.mul(portfolioWeight) |
|||
); |
|||
|
|||
newTotalInvestment = newTotalInvestment.plus( |
|||
timelineHoldings[date][holding].mul(priceInBaseCurrency) |
|||
); |
|||
return { |
|||
netPerformanceInPercentage, |
|||
netPerformanceInPercentageWithCurrencyEffect, |
|||
newTotalInvestment |
|||
}; |
|||
} |
|||
|
|||
private getCurrency(symbol: string) { |
|||
if (!this.holdingCurrencies[symbol]) { |
|||
this.holdingCurrencies[symbol] = this.activities.find( |
|||
(a) => a.SymbolProfile.symbol === symbol |
|||
).SymbolProfile.currency; |
|||
} |
|||
|
|||
return this.holdingCurrencies[symbol]; |
|||
} |
|||
|
|||
private getHoldings(start: Date, end: Date) { |
|||
if ( |
|||
this.holdings && |
|||
Object.keys(this.holdings).some((h) => parseDate(h) >= end) && |
|||
Object.keys(this.holdings).some((h) => parseDate(h) <= start) |
|||
) { |
|||
return this.holdings; |
|||
} |
|||
|
|||
this.computeHoldings(start, end); |
|||
return this.holdings; |
|||
} |
|||
|
|||
private computeHoldings(start: Date, end: Date) { |
|||
const investmentByDate = this.getInvestmentByDate(); |
|||
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; |
|||
} |
|||
|
|||
private 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; |
|||
} |
|||
} |
|||
|
|||
private getInvestmentByDate(): { [date: string]: PortfolioOrder[] } { |
|||
return this.activities.reduce((groupedByDate, order) => { |
|||
if (!groupedByDate[order.date]) { |
|||
groupedByDate[order.date] = []; |
|||
} |
|||
|
|||
groupedByDate[order.date].push(order); |
|||
|
|||
return groupedByDate; |
|||
}, {}); |
|||
} |
|||
} |
@ -0,0 +1,33 @@ |
|||
import { PortfolioCalculator } from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator'; |
|||
import { SymbolMetrics, UniqueAsset } from '@ghostfolio/common/interfaces'; |
|||
import { PortfolioSnapshot, TimelinePosition } from '@ghostfolio/common/models'; |
|||
|
|||
export class MWRPortfolioCalculator extends PortfolioCalculator { |
|||
protected calculateOverallPerformance( |
|||
positions: TimelinePosition[] |
|||
): PortfolioSnapshot { |
|||
throw new Error('Method not implemented.'); |
|||
} |
|||
|
|||
protected getSymbolMetrics({ |
|||
dataSource, |
|||
end, |
|||
exchangeRates, |
|||
isChartMode = false, |
|||
marketSymbolMap, |
|||
start, |
|||
step = 1, |
|||
symbol |
|||
}: { |
|||
end: Date; |
|||
exchangeRates: { [dateString: string]: number }; |
|||
isChartMode?: boolean; |
|||
marketSymbolMap: { |
|||
[date: string]: { [symbol: string]: Big }; |
|||
}; |
|||
start: Date; |
|||
step?: number; |
|||
} & UniqueAsset): SymbolMetrics { |
|||
throw new Error('Method not implemented.'); |
|||
} |
|||
} |
@ -0,0 +1,30 @@ |
|||
export const activityDummyData = { |
|||
accountId: undefined, |
|||
accountUserId: undefined, |
|||
comment: undefined, |
|||
createdAt: new Date(), |
|||
currency: undefined, |
|||
feeInBaseCurrency: undefined, |
|||
id: undefined, |
|||
isDraft: false, |
|||
symbolProfileId: undefined, |
|||
updatedAt: new Date(), |
|||
userId: undefined, |
|||
value: undefined, |
|||
valueInBaseCurrency: undefined |
|||
}; |
|||
|
|||
export const symbolProfileDummyData = { |
|||
activitiesCount: undefined, |
|||
assetClass: undefined, |
|||
assetSubClass: undefined, |
|||
countries: [], |
|||
createdAt: undefined, |
|||
id: undefined, |
|||
sectors: [], |
|||
updatedAt: undefined |
|||
}; |
|||
|
|||
export const userDummyData = { |
|||
id: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' |
|||
}; |
@ -0,0 +1,96 @@ |
|||
import { Activity } from '@ghostfolio/api/app/order/interfaces/activities.interface'; |
|||
import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service'; |
|||
import { RedisCacheService } from '@ghostfolio/api/app/redis-cache/redis-cache.service'; |
|||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|||
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; |
|||
import { HistoricalDataItem } from '@ghostfolio/common/interfaces'; |
|||
import { DateRange, UserWithSettings } from '@ghostfolio/common/types'; |
|||
|
|||
import { Injectable } from '@nestjs/common'; |
|||
|
|||
import { CPRPortfolioCalculator } from './constantPortfolioReturn/portfolio-calculator'; |
|||
import { MWRPortfolioCalculator } from './mwr/portfolio-calculator'; |
|||
import { PortfolioCalculator } from './portfolio-calculator'; |
|||
import { TWRPortfolioCalculator } from './twr/portfolio-calculator'; |
|||
|
|||
export enum PerformanceCalculationType { |
|||
MWR = 'MWR', // Money-Weighted Rate of Return
|
|||
TWR = 'TWR', // Time-Weighted Rate of Return
|
|||
CPR = 'CPR' // Constant Portfolio Rate of Return
|
|||
} |
|||
|
|||
@Injectable() |
|||
export class PortfolioCalculatorFactory { |
|||
public constructor( |
|||
private readonly configurationService: ConfigurationService, |
|||
private readonly currentRateService: CurrentRateService, |
|||
private readonly exchangeRateDataService: ExchangeRateDataService, |
|||
private readonly redisCacheService: RedisCacheService |
|||
) {} |
|||
|
|||
public createCalculator({ |
|||
accountBalanceItems = [], |
|||
activities, |
|||
calculationType, |
|||
currency, |
|||
dateRange = 'max', |
|||
hasFilters, |
|||
isExperimentalFeatures = false, |
|||
userId |
|||
}: { |
|||
accountBalanceItems?: HistoricalDataItem[]; |
|||
activities: Activity[]; |
|||
calculationType: PerformanceCalculationType; |
|||
currency: string; |
|||
dateRange?: DateRange; |
|||
hasFilters: boolean; |
|||
isExperimentalFeatures?: boolean; |
|||
userId: string; |
|||
}): PortfolioCalculator { |
|||
const useCache = !hasFilters && isExperimentalFeatures; |
|||
|
|||
switch (calculationType) { |
|||
case PerformanceCalculationType.MWR: |
|||
return new MWRPortfolioCalculator({ |
|||
accountBalanceItems, |
|||
activities, |
|||
currency, |
|||
dateRange, |
|||
useCache, |
|||
userId, |
|||
configurationService: this.configurationService, |
|||
currentRateService: this.currentRateService, |
|||
exchangeRateDataService: this.exchangeRateDataService, |
|||
redisCacheService: this.redisCacheService |
|||
}); |
|||
case PerformanceCalculationType.TWR: |
|||
return new TWRPortfolioCalculator({ |
|||
accountBalanceItems, |
|||
activities, |
|||
currency, |
|||
currentRateService: this.currentRateService, |
|||
dateRange, |
|||
useCache, |
|||
userId, |
|||
configurationService: this.configurationService, |
|||
exchangeRateDataService: this.exchangeRateDataService, |
|||
redisCacheService: this.redisCacheService |
|||
}); |
|||
case PerformanceCalculationType.CPR: |
|||
return new CPRPortfolioCalculator({ |
|||
accountBalanceItems, |
|||
activities, |
|||
currency, |
|||
currentRateService: this.currentRateService, |
|||
dateRange, |
|||
useCache, |
|||
userId, |
|||
configurationService: this.configurationService, |
|||
exchangeRateDataService: this.exchangeRateDataService, |
|||
redisCacheService: this.redisCacheService |
|||
}); |
|||
default: |
|||
throw new Error('Invalid calculation type'); |
|||
} |
|||
} |
|||
} |
File diff suppressed because it is too large
@ -0,0 +1,218 @@ |
|||
import { Activity } from '@ghostfolio/api/app/order/interfaces/activities.interface'; |
|||
import { |
|||
activityDummyData, |
|||
symbolProfileDummyData, |
|||
userDummyData |
|||
} from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator-test-utils'; |
|||
import { |
|||
PortfolioCalculatorFactory, |
|||
PerformanceCalculationType |
|||
} from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator.factory'; |
|||
import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service'; |
|||
import { CurrentRateServiceMock } from '@ghostfolio/api/app/portfolio/current-rate.service.mock'; |
|||
import { RedisCacheService } from '@ghostfolio/api/app/redis-cache/redis-cache.service'; |
|||
import { RedisCacheServiceMock } from '@ghostfolio/api/app/redis-cache/redis-cache.service.mock'; |
|||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|||
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; |
|||
import { parseDate } from '@ghostfolio/common/helper'; |
|||
|
|||
import { Big } from 'big.js'; |
|||
|
|||
jest.mock('@ghostfolio/api/app/portfolio/current-rate.service', () => { |
|||
return { |
|||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|||
CurrentRateService: jest.fn().mockImplementation(() => { |
|||
return CurrentRateServiceMock; |
|||
}) |
|||
}; |
|||
}); |
|||
|
|||
jest.mock('@ghostfolio/api/app/redis-cache/redis-cache.service', () => { |
|||
return { |
|||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|||
RedisCacheService: jest.fn().mockImplementation(() => { |
|||
return RedisCacheServiceMock; |
|||
}) |
|||
}; |
|||
}); |
|||
|
|||
describe('PortfolioCalculator', () => { |
|||
let configurationService: ConfigurationService; |
|||
let currentRateService: CurrentRateService; |
|||
let exchangeRateDataService: ExchangeRateDataService; |
|||
let factory: PortfolioCalculatorFactory; |
|||
let redisCacheService: RedisCacheService; |
|||
|
|||
beforeEach(() => { |
|||
configurationService = new ConfigurationService(); |
|||
|
|||
currentRateService = new CurrentRateService(null, null, null, null); |
|||
|
|||
exchangeRateDataService = new ExchangeRateDataService( |
|||
null, |
|||
null, |
|||
null, |
|||
null |
|||
); |
|||
|
|||
redisCacheService = new RedisCacheService(null, null); |
|||
|
|||
factory = new PortfolioCalculatorFactory( |
|||
configurationService, |
|||
currentRateService, |
|||
exchangeRateDataService, |
|||
redisCacheService |
|||
); |
|||
}); |
|||
|
|||
describe('get current positions', () => { |
|||
it.only('with BALN.SW buy and sell in two activities', async () => { |
|||
const spy = jest |
|||
.spyOn(Date, 'now') |
|||
.mockImplementation(() => parseDate('2021-12-18').getTime()); |
|||
|
|||
const activities: Activity[] = [ |
|||
{ |
|||
...activityDummyData, |
|||
date: new Date('2021-11-22'), |
|||
fee: 1.55, |
|||
quantity: 2, |
|||
SymbolProfile: { |
|||
...symbolProfileDummyData, |
|||
currency: 'CHF', |
|||
dataSource: 'YAHOO', |
|||
name: 'Bâloise Holding AG', |
|||
symbol: 'BALN.SW' |
|||
}, |
|||
type: 'BUY', |
|||
unitPrice: 142.9 |
|||
}, |
|||
{ |
|||
...activityDummyData, |
|||
date: new Date('2021-11-30'), |
|||
fee: 1.65, |
|||
quantity: 1, |
|||
SymbolProfile: { |
|||
...symbolProfileDummyData, |
|||
currency: 'CHF', |
|||
dataSource: 'YAHOO', |
|||
name: 'Bâloise Holding AG', |
|||
symbol: 'BALN.SW' |
|||
}, |
|||
type: 'SELL', |
|||
unitPrice: 136.6 |
|||
}, |
|||
{ |
|||
...activityDummyData, |
|||
date: new Date('2021-11-30'), |
|||
fee: 0, |
|||
quantity: 1, |
|||
SymbolProfile: { |
|||
...symbolProfileDummyData, |
|||
currency: 'CHF', |
|||
dataSource: 'YAHOO', |
|||
name: 'Bâloise Holding AG', |
|||
symbol: 'BALN.SW' |
|||
}, |
|||
type: 'SELL', |
|||
unitPrice: 136.6 |
|||
} |
|||
]; |
|||
|
|||
const portfolioCalculator = factory.createCalculator({ |
|||
activities, |
|||
calculationType: PerformanceCalculationType.TWR, |
|||
currency: 'CHF', |
|||
hasFilters: false, |
|||
userId: userDummyData.id |
|||
}); |
|||
|
|||
const chartData = await portfolioCalculator.getChartData({ |
|||
start: parseDate('2021-11-22') |
|||
}); |
|||
|
|||
const portfolioSnapshot = await portfolioCalculator.computeSnapshot( |
|||
parseDate('2021-11-22') |
|||
); |
|||
|
|||
const investments = portfolioCalculator.getInvestments(); |
|||
|
|||
const investmentsByMonth = portfolioCalculator.getInvestmentsByGroup({ |
|||
data: chartData, |
|||
groupBy: 'month' |
|||
}); |
|||
|
|||
spy.mockRestore(); |
|||
|
|||
expect(portfolioSnapshot).toEqual({ |
|||
currentValueInBaseCurrency: new Big('0'), |
|||
errors: [], |
|||
grossPerformance: new Big('-12.6'), |
|||
grossPerformancePercentage: new Big('-0.04408677396780965649'), |
|||
grossPerformancePercentageWithCurrencyEffect: new Big( |
|||
'-0.04408677396780965649' |
|||
), |
|||
grossPerformanceWithCurrencyEffect: new Big('-12.6'), |
|||
hasErrors: false, |
|||
netPerformance: new Big('-15.8'), |
|||
netPerformancePercentage: new Big('-0.05528341497550734703'), |
|||
netPerformancePercentageWithCurrencyEffect: new Big( |
|||
'-0.05528341497550734703' |
|||
), |
|||
netPerformanceWithCurrencyEffect: new Big('-15.8'), |
|||
positions: [ |
|||
{ |
|||
averagePrice: new Big('0'), |
|||
currency: 'CHF', |
|||
dataSource: 'YAHOO', |
|||
dividend: new Big('0'), |
|||
dividendInBaseCurrency: new Big('0'), |
|||
fee: new Big('3.2'), |
|||
firstBuyDate: '2021-11-22', |
|||
grossPerformance: new Big('-12.6'), |
|||
grossPerformancePercentage: new Big('-0.04408677396780965649'), |
|||
grossPerformancePercentageWithCurrencyEffect: new Big( |
|||
'-0.04408677396780965649' |
|||
), |
|||
grossPerformanceWithCurrencyEffect: new Big('-12.6'), |
|||
investment: new Big('0'), |
|||
investmentWithCurrencyEffect: new Big('0'), |
|||
netPerformance: new Big('-15.8'), |
|||
netPerformancePercentage: new Big('-0.05528341497550734703'), |
|||
netPerformancePercentageWithCurrencyEffect: new Big( |
|||
'-0.05528341497550734703' |
|||
), |
|||
netPerformanceWithCurrencyEffect: new Big('-15.8'), |
|||
marketPrice: 148.9, |
|||
marketPriceInBaseCurrency: 148.9, |
|||
quantity: new Big('0'), |
|||
symbol: 'BALN.SW', |
|||
tags: [], |
|||
timeWeightedInvestment: new Big('285.80000000000000396627'), |
|||
timeWeightedInvestmentWithCurrencyEffect: new Big( |
|||
'285.80000000000000396627' |
|||
), |
|||
transactionCount: 3, |
|||
valueInBaseCurrency: new Big('0') |
|||
} |
|||
], |
|||
totalFeesWithCurrencyEffect: new Big('3.2'), |
|||
totalInterestWithCurrencyEffect: new Big('0'), |
|||
totalInvestment: new Big('0'), |
|||
totalInvestmentWithCurrencyEffect: new Big('0'), |
|||
totalLiabilitiesWithCurrencyEffect: new Big('0'), |
|||
totalValuablesWithCurrencyEffect: new Big('0') |
|||
}); |
|||
|
|||
expect(investments).toEqual([ |
|||
{ date: '2021-11-22', investment: new Big('285.8') }, |
|||
{ date: '2021-11-30', investment: new Big('0') } |
|||
]); |
|||
|
|||
expect(investmentsByMonth).toEqual([ |
|||
{ date: '2021-11-01', investment: 0 }, |
|||
{ date: '2021-12-01', investment: 0 } |
|||
]); |
|||
}); |
|||
}); |
|||
}); |
@ -0,0 +1,157 @@ |
|||
import { Activity } from '@ghostfolio/api/app/order/interfaces/activities.interface'; |
|||
import { |
|||
activityDummyData, |
|||
symbolProfileDummyData, |
|||
userDummyData |
|||
} from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator-test-utils'; |
|||
import { |
|||
PortfolioCalculatorFactory, |
|||
PerformanceCalculationType |
|||
} from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator.factory'; |
|||
import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service'; |
|||
import { CurrentRateServiceMock } from '@ghostfolio/api/app/portfolio/current-rate.service.mock'; |
|||
import { RedisCacheService } from '@ghostfolio/api/app/redis-cache/redis-cache.service'; |
|||
import { RedisCacheServiceMock } from '@ghostfolio/api/app/redis-cache/redis-cache.service.mock'; |
|||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|||
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; |
|||
import { parseDate } from '@ghostfolio/common/helper'; |
|||
|
|||
import { Big } from 'big.js'; |
|||
|
|||
jest.mock('@ghostfolio/api/app/portfolio/current-rate.service', () => { |
|||
return { |
|||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|||
CurrentRateService: jest.fn().mockImplementation(() => { |
|||
return CurrentRateServiceMock; |
|||
}) |
|||
}; |
|||
}); |
|||
|
|||
jest.mock('@ghostfolio/api/app/redis-cache/redis-cache.service', () => { |
|||
return { |
|||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|||
RedisCacheService: jest.fn().mockImplementation(() => { |
|||
return RedisCacheServiceMock; |
|||
}) |
|||
}; |
|||
}); |
|||
|
|||
describe('PortfolioCalculator', () => { |
|||
let configurationService: ConfigurationService; |
|||
let currentRateService: CurrentRateService; |
|||
let exchangeRateDataService: ExchangeRateDataService; |
|||
let factory: PortfolioCalculatorFactory; |
|||
let redisCacheService: RedisCacheService; |
|||
|
|||
beforeEach(() => { |
|||
configurationService = new ConfigurationService(); |
|||
|
|||
currentRateService = new CurrentRateService(null, null, null, null); |
|||
|
|||
exchangeRateDataService = new ExchangeRateDataService( |
|||
null, |
|||
null, |
|||
null, |
|||
null |
|||
); |
|||
|
|||
redisCacheService = new RedisCacheService(null, null); |
|||
|
|||
factory = new PortfolioCalculatorFactory( |
|||
configurationService, |
|||
currentRateService, |
|||
exchangeRateDataService, |
|||
redisCacheService |
|||
); |
|||
}); |
|||
|
|||
describe('compute portfolio snapshot', () => { |
|||
it.only('with fee activity', async () => { |
|||
const spy = jest |
|||
.spyOn(Date, 'now') |
|||
.mockImplementation(() => parseDate('2021-12-18').getTime()); |
|||
|
|||
const activities: Activity[] = [ |
|||
{ |
|||
...activityDummyData, |
|||
date: new Date('2021-09-01'), |
|||
fee: 49, |
|||
quantity: 0, |
|||
SymbolProfile: { |
|||
...symbolProfileDummyData, |
|||
currency: 'USD', |
|||
dataSource: 'MANUAL', |
|||
name: 'Account Opening Fee', |
|||
symbol: '2c463fb3-af07-486e-adb0-8301b3d72141' |
|||
}, |
|||
type: 'FEE', |
|||
unitPrice: 0 |
|||
} |
|||
]; |
|||
|
|||
const portfolioCalculator = factory.createCalculator({ |
|||
activities, |
|||
calculationType: PerformanceCalculationType.TWR, |
|||
currency: 'USD', |
|||
hasFilters: false, |
|||
userId: userDummyData.id |
|||
}); |
|||
|
|||
const portfolioSnapshot = await portfolioCalculator.computeSnapshot( |
|||
parseDate('2021-11-30') |
|||
); |
|||
|
|||
spy.mockRestore(); |
|||
|
|||
expect(portfolioSnapshot).toEqual({ |
|||
currentValueInBaseCurrency: new Big('0'), |
|||
errors: [], |
|||
grossPerformance: new Big('0'), |
|||
grossPerformancePercentage: new Big('0'), |
|||
grossPerformancePercentageWithCurrencyEffect: new Big('0'), |
|||
grossPerformanceWithCurrencyEffect: new Big('0'), |
|||
hasErrors: true, |
|||
netPerformance: new Big('0'), |
|||
netPerformancePercentage: new Big('0'), |
|||
netPerformancePercentageWithCurrencyEffect: new Big('0'), |
|||
netPerformanceWithCurrencyEffect: new Big('0'), |
|||
positions: [ |
|||
{ |
|||
averagePrice: new Big('0'), |
|||
currency: 'USD', |
|||
dataSource: 'MANUAL', |
|||
dividend: new Big('0'), |
|||
dividendInBaseCurrency: new Big('0'), |
|||
fee: new Big('49'), |
|||
firstBuyDate: '2021-09-01', |
|||
grossPerformance: null, |
|||
grossPerformancePercentage: null, |
|||
grossPerformancePercentageWithCurrencyEffect: null, |
|||
grossPerformanceWithCurrencyEffect: null, |
|||
investment: new Big('0'), |
|||
investmentWithCurrencyEffect: new Big('0'), |
|||
marketPrice: null, |
|||
marketPriceInBaseCurrency: 0, |
|||
netPerformance: null, |
|||
netPerformancePercentage: null, |
|||
netPerformancePercentageWithCurrencyEffect: null, |
|||
netPerformanceWithCurrencyEffect: null, |
|||
quantity: new Big('0'), |
|||
symbol: '2c463fb3-af07-486e-adb0-8301b3d72141', |
|||
tags: [], |
|||
timeWeightedInvestment: new Big('0'), |
|||
timeWeightedInvestmentWithCurrencyEffect: new Big('0'), |
|||
transactionCount: 1, |
|||
valueInBaseCurrency: new Big('0') |
|||
} |
|||
], |
|||
totalFeesWithCurrencyEffect: new Big('49'), |
|||
totalInterestWithCurrencyEffect: new Big('0'), |
|||
totalInvestment: new Big('0'), |
|||
totalInvestmentWithCurrencyEffect: new Big('0'), |
|||
totalLiabilitiesWithCurrencyEffect: new Big('0'), |
|||
totalValuablesWithCurrencyEffect: new Big('0') |
|||
}); |
|||
}); |
|||
}); |
|||
}); |
@ -0,0 +1,157 @@ |
|||
import { Activity } from '@ghostfolio/api/app/order/interfaces/activities.interface'; |
|||
import { |
|||
activityDummyData, |
|||
symbolProfileDummyData, |
|||
userDummyData |
|||
} from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator-test-utils'; |
|||
import { |
|||
PortfolioCalculatorFactory, |
|||
PerformanceCalculationType |
|||
} from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator.factory'; |
|||
import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service'; |
|||
import { CurrentRateServiceMock } from '@ghostfolio/api/app/portfolio/current-rate.service.mock'; |
|||
import { RedisCacheService } from '@ghostfolio/api/app/redis-cache/redis-cache.service'; |
|||
import { RedisCacheServiceMock } from '@ghostfolio/api/app/redis-cache/redis-cache.service.mock'; |
|||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|||
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; |
|||
import { parseDate } from '@ghostfolio/common/helper'; |
|||
|
|||
import { Big } from 'big.js'; |
|||
|
|||
jest.mock('@ghostfolio/api/app/portfolio/current-rate.service', () => { |
|||
return { |
|||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|||
CurrentRateService: jest.fn().mockImplementation(() => { |
|||
return CurrentRateServiceMock; |
|||
}) |
|||
}; |
|||
}); |
|||
|
|||
jest.mock('@ghostfolio/api/app/redis-cache/redis-cache.service', () => { |
|||
return { |
|||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|||
RedisCacheService: jest.fn().mockImplementation(() => { |
|||
return RedisCacheServiceMock; |
|||
}) |
|||
}; |
|||
}); |
|||
|
|||
describe('PortfolioCalculator', () => { |
|||
let configurationService: ConfigurationService; |
|||
let currentRateService: CurrentRateService; |
|||
let exchangeRateDataService: ExchangeRateDataService; |
|||
let factory: PortfolioCalculatorFactory; |
|||
let redisCacheService: RedisCacheService; |
|||
|
|||
beforeEach(() => { |
|||
configurationService = new ConfigurationService(); |
|||
|
|||
currentRateService = new CurrentRateService(null, null, null, null); |
|||
|
|||
exchangeRateDataService = new ExchangeRateDataService( |
|||
null, |
|||
null, |
|||
null, |
|||
null |
|||
); |
|||
|
|||
redisCacheService = new RedisCacheService(null, null); |
|||
|
|||
factory = new PortfolioCalculatorFactory( |
|||
configurationService, |
|||
currentRateService, |
|||
exchangeRateDataService, |
|||
redisCacheService |
|||
); |
|||
}); |
|||
|
|||
describe('compute portfolio snapshot', () => { |
|||
it.only('with item activity', async () => { |
|||
const spy = jest |
|||
.spyOn(Date, 'now') |
|||
.mockImplementation(() => parseDate('2022-01-31').getTime()); |
|||
|
|||
const activities: Activity[] = [ |
|||
{ |
|||
...activityDummyData, |
|||
date: new Date('2022-01-01'), |
|||
fee: 0, |
|||
quantity: 1, |
|||
SymbolProfile: { |
|||
...symbolProfileDummyData, |
|||
currency: 'USD', |
|||
dataSource: 'MANUAL', |
|||
name: 'Penthouse Apartment', |
|||
symbol: 'dac95060-d4f2-4653-a253-2c45e6fb5cde' |
|||
}, |
|||
type: 'ITEM', |
|||
unitPrice: 500000 |
|||
} |
|||
]; |
|||
|
|||
const portfolioCalculator = factory.createCalculator({ |
|||
activities, |
|||
calculationType: PerformanceCalculationType.TWR, |
|||
currency: 'USD', |
|||
hasFilters: false, |
|||
userId: userDummyData.id |
|||
}); |
|||
|
|||
const portfolioSnapshot = await portfolioCalculator.computeSnapshot( |
|||
parseDate('2022-01-01') |
|||
); |
|||
|
|||
spy.mockRestore(); |
|||
|
|||
expect(portfolioSnapshot).toEqual({ |
|||
currentValueInBaseCurrency: new Big('0'), |
|||
errors: [], |
|||
grossPerformance: new Big('0'), |
|||
grossPerformancePercentage: new Big('0'), |
|||
grossPerformancePercentageWithCurrencyEffect: new Big('0'), |
|||
grossPerformanceWithCurrencyEffect: new Big('0'), |
|||
hasErrors: true, |
|||
netPerformance: new Big('0'), |
|||
netPerformancePercentage: new Big('0'), |
|||
netPerformancePercentageWithCurrencyEffect: new Big('0'), |
|||
netPerformanceWithCurrencyEffect: new Big('0'), |
|||
positions: [ |
|||
{ |
|||
averagePrice: new Big('500000'), |
|||
currency: 'USD', |
|||
dataSource: 'MANUAL', |
|||
dividend: new Big('0'), |
|||
dividendInBaseCurrency: new Big('0'), |
|||
fee: new Big('0'), |
|||
firstBuyDate: '2022-01-01', |
|||
grossPerformance: null, |
|||
grossPerformancePercentage: null, |
|||
grossPerformancePercentageWithCurrencyEffect: null, |
|||
grossPerformanceWithCurrencyEffect: null, |
|||
investment: new Big('0'), |
|||
investmentWithCurrencyEffect: new Big('0'), |
|||
marketPrice: null, |
|||
marketPriceInBaseCurrency: 500000, |
|||
netPerformance: null, |
|||
netPerformancePercentage: null, |
|||
netPerformancePercentageWithCurrencyEffect: null, |
|||
netPerformanceWithCurrencyEffect: null, |
|||
quantity: new Big('0'), |
|||
symbol: 'dac95060-d4f2-4653-a253-2c45e6fb5cde', |
|||
tags: [], |
|||
timeWeightedInvestment: new Big('0'), |
|||
timeWeightedInvestmentWithCurrencyEffect: new Big('0'), |
|||
transactionCount: 1, |
|||
valueInBaseCurrency: new Big('0') |
|||
} |
|||
], |
|||
totalFeesWithCurrencyEffect: new Big('0'), |
|||
totalInterestWithCurrencyEffect: new Big('0'), |
|||
totalInvestment: new Big('0'), |
|||
totalInvestmentWithCurrencyEffect: new Big('0'), |
|||
totalLiabilitiesWithCurrencyEffect: new Big('0'), |
|||
totalValuablesWithCurrencyEffect: new Big('0') |
|||
}); |
|||
}); |
|||
}); |
|||
}); |
@ -0,0 +1,108 @@ |
|||
import { Activity } from '@ghostfolio/api/app/order/interfaces/activities.interface'; |
|||
import { |
|||
activityDummyData, |
|||
symbolProfileDummyData, |
|||
userDummyData |
|||
} from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator-test-utils'; |
|||
import { |
|||
PortfolioCalculatorFactory, |
|||
PerformanceCalculationType |
|||
} from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator.factory'; |
|||
import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service'; |
|||
import { CurrentRateServiceMock } from '@ghostfolio/api/app/portfolio/current-rate.service.mock'; |
|||
import { RedisCacheService } from '@ghostfolio/api/app/redis-cache/redis-cache.service'; |
|||
import { RedisCacheServiceMock } from '@ghostfolio/api/app/redis-cache/redis-cache.service.mock'; |
|||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|||
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; |
|||
import { parseDate } from '@ghostfolio/common/helper'; |
|||
|
|||
import { Big } from 'big.js'; |
|||
|
|||
jest.mock('@ghostfolio/api/app/portfolio/current-rate.service', () => { |
|||
return { |
|||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|||
CurrentRateService: jest.fn().mockImplementation(() => { |
|||
return CurrentRateServiceMock; |
|||
}) |
|||
}; |
|||
}); |
|||
|
|||
jest.mock('@ghostfolio/api/app/redis-cache/redis-cache.service', () => { |
|||
return { |
|||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|||
RedisCacheService: jest.fn().mockImplementation(() => { |
|||
return RedisCacheServiceMock; |
|||
}) |
|||
}; |
|||
}); |
|||
|
|||
describe('PortfolioCalculator', () => { |
|||
let configurationService: ConfigurationService; |
|||
let currentRateService: CurrentRateService; |
|||
let exchangeRateDataService: ExchangeRateDataService; |
|||
let factory: PortfolioCalculatorFactory; |
|||
let redisCacheService: RedisCacheService; |
|||
|
|||
beforeEach(() => { |
|||
configurationService = new ConfigurationService(); |
|||
|
|||
currentRateService = new CurrentRateService(null, null, null, null); |
|||
|
|||
exchangeRateDataService = new ExchangeRateDataService( |
|||
null, |
|||
null, |
|||
null, |
|||
null |
|||
); |
|||
|
|||
redisCacheService = new RedisCacheService(null, null); |
|||
|
|||
factory = new PortfolioCalculatorFactory( |
|||
configurationService, |
|||
currentRateService, |
|||
exchangeRateDataService, |
|||
redisCacheService |
|||
); |
|||
}); |
|||
|
|||
describe('compute portfolio snapshot', () => { |
|||
it.only('with liability activity', async () => { |
|||
const spy = jest |
|||
.spyOn(Date, 'now') |
|||
.mockImplementation(() => parseDate('2022-01-31').getTime()); |
|||
|
|||
const activities: Activity[] = [ |
|||
{ |
|||
...activityDummyData, |
|||
date: new Date('2023-01-01'), // Date in future
|
|||
fee: 0, |
|||
quantity: 1, |
|||
SymbolProfile: { |
|||
...symbolProfileDummyData, |
|||
currency: 'USD', |
|||
dataSource: 'MANUAL', |
|||
name: 'Loan', |
|||
symbol: '55196015-1365-4560-aa60-8751ae6d18f8' |
|||
}, |
|||
type: 'LIABILITY', |
|||
unitPrice: 3000 |
|||
} |
|||
]; |
|||
|
|||
const portfolioCalculator = factory.createCalculator({ |
|||
activities, |
|||
calculationType: PerformanceCalculationType.TWR, |
|||
currency: 'USD', |
|||
hasFilters: false, |
|||
userId: userDummyData.id |
|||
}); |
|||
|
|||
spy.mockRestore(); |
|||
|
|||
const liabilitiesInBaseCurrency = |
|||
await portfolioCalculator.getLiabilitiesInBaseCurrency(); |
|||
|
|||
expect(liabilitiesInBaseCurrency).toEqual(new Big(3000)); |
|||
}); |
|||
}); |
|||
}); |
@ -0,0 +1,165 @@ |
|||
import { Activity } from '@ghostfolio/api/app/order/interfaces/activities.interface'; |
|||
import { |
|||
activityDummyData, |
|||
symbolProfileDummyData, |
|||
userDummyData |
|||
} from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator-test-utils'; |
|||
import { |
|||
PerformanceCalculationType, |
|||
PortfolioCalculatorFactory |
|||
} from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator.factory'; |
|||
import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service'; |
|||
import { CurrentRateServiceMock } from '@ghostfolio/api/app/portfolio/current-rate.service.mock'; |
|||
import { RedisCacheService } from '@ghostfolio/api/app/redis-cache/redis-cache.service'; |
|||
import { RedisCacheServiceMock } from '@ghostfolio/api/app/redis-cache/redis-cache.service.mock'; |
|||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|||
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; |
|||
import { ExchangeRateDataServiceMock } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service.mock'; |
|||
import { parseDate } from '@ghostfolio/common/helper'; |
|||
|
|||
import { Big } from 'big.js'; |
|||
|
|||
jest.mock('@ghostfolio/api/app/portfolio/current-rate.service', () => { |
|||
return { |
|||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|||
CurrentRateService: jest.fn().mockImplementation(() => { |
|||
return CurrentRateServiceMock; |
|||
}) |
|||
}; |
|||
}); |
|||
|
|||
jest.mock('@ghostfolio/api/app/redis-cache/redis-cache.service', () => { |
|||
return { |
|||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|||
RedisCacheService: jest.fn().mockImplementation(() => { |
|||
return RedisCacheServiceMock; |
|||
}) |
|||
}; |
|||
}); |
|||
|
|||
jest.mock( |
|||
'@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service', |
|||
() => { |
|||
return { |
|||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|||
ExchangeRateDataService: jest.fn().mockImplementation(() => { |
|||
return ExchangeRateDataServiceMock; |
|||
}) |
|||
}; |
|||
} |
|||
); |
|||
|
|||
describe('PortfolioCalculator', () => { |
|||
let configurationService: ConfigurationService; |
|||
let currentRateService: CurrentRateService; |
|||
let exchangeRateDataService: ExchangeRateDataService; |
|||
let factory: PortfolioCalculatorFactory; |
|||
let redisCacheService: RedisCacheService; |
|||
|
|||
beforeEach(() => { |
|||
configurationService = new ConfigurationService(); |
|||
|
|||
currentRateService = new CurrentRateService(null, null, null, null); |
|||
|
|||
exchangeRateDataService = new ExchangeRateDataService( |
|||
null, |
|||
null, |
|||
null, |
|||
null |
|||
); |
|||
|
|||
redisCacheService = new RedisCacheService(null, null); |
|||
|
|||
factory = new PortfolioCalculatorFactory( |
|||
configurationService, |
|||
currentRateService, |
|||
exchangeRateDataService, |
|||
redisCacheService |
|||
); |
|||
}); |
|||
|
|||
describe('get current positions', () => { |
|||
it.only('with MSFT buy', async () => { |
|||
const spy = jest |
|||
.spyOn(Date, 'now') |
|||
.mockImplementation(() => parseDate('2023-07-10').getTime()); |
|||
|
|||
const activities: Activity[] = [ |
|||
{ |
|||
...activityDummyData, |
|||
date: new Date('2021-09-16'), |
|||
fee: 19, |
|||
quantity: 1, |
|||
SymbolProfile: { |
|||
...symbolProfileDummyData, |
|||
currency: 'USD', |
|||
dataSource: 'YAHOO', |
|||
name: 'Microsoft Inc.', |
|||
symbol: 'MSFT' |
|||
}, |
|||
type: 'BUY', |
|||
unitPrice: 298.58 |
|||
}, |
|||
{ |
|||
...activityDummyData, |
|||
date: new Date('2021-11-16'), |
|||
fee: 0, |
|||
quantity: 1, |
|||
SymbolProfile: { |
|||
...symbolProfileDummyData, |
|||
currency: 'USD', |
|||
dataSource: 'YAHOO', |
|||
name: 'Microsoft Inc.', |
|||
symbol: 'MSFT' |
|||
}, |
|||
type: 'DIVIDEND', |
|||
unitPrice: 0.62 |
|||
} |
|||
]; |
|||
|
|||
const portfolioCalculator = factory.createCalculator({ |
|||
activities, |
|||
calculationType: PerformanceCalculationType.TWR, |
|||
currency: 'USD', |
|||
hasFilters: false, |
|||
userId: userDummyData.id |
|||
}); |
|||
|
|||
const portfolioSnapshot = await portfolioCalculator.computeSnapshot( |
|||
parseDate('2023-07-10') |
|||
); |
|||
|
|||
spy.mockRestore(); |
|||
|
|||
expect(portfolioSnapshot).toMatchObject({ |
|||
errors: [], |
|||
hasErrors: false, |
|||
positions: [ |
|||
{ |
|||
averagePrice: new Big('298.58'), |
|||
currency: 'USD', |
|||
dataSource: 'YAHOO', |
|||
dividend: new Big('0.62'), |
|||
dividendInBaseCurrency: new Big('0.62'), |
|||
fee: new Big('19'), |
|||
firstBuyDate: '2021-09-16', |
|||
investment: new Big('298.58'), |
|||
investmentWithCurrencyEffect: new Big('298.58'), |
|||
marketPrice: 331.83, |
|||
marketPriceInBaseCurrency: 331.83, |
|||
quantity: new Big('1'), |
|||
symbol: 'MSFT', |
|||
tags: [], |
|||
transactionCount: 2 |
|||
} |
|||
], |
|||
totalFeesWithCurrencyEffect: new Big('19'), |
|||
totalInterestWithCurrencyEffect: new Big('0'), |
|||
totalInvestment: new Big('298.58'), |
|||
totalInvestmentWithCurrencyEffect: new Big('298.58'), |
|||
totalLiabilitiesWithCurrencyEffect: new Big('0'), |
|||
totalValuablesWithCurrencyEffect: new Big('0') |
|||
}); |
|||
}); |
|||
}); |
|||
}); |
@ -0,0 +1,124 @@ |
|||
import { userDummyData } from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator-test-utils'; |
|||
import { |
|||
PerformanceCalculationType, |
|||
PortfolioCalculatorFactory |
|||
} from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator.factory'; |
|||
import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service'; |
|||
import { CurrentRateServiceMock } from '@ghostfolio/api/app/portfolio/current-rate.service.mock'; |
|||
import { RedisCacheService } from '@ghostfolio/api/app/redis-cache/redis-cache.service'; |
|||
import { RedisCacheServiceMock } from '@ghostfolio/api/app/redis-cache/redis-cache.service.mock'; |
|||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|||
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; |
|||
import { parseDate } from '@ghostfolio/common/helper'; |
|||
|
|||
import { Big } from 'big.js'; |
|||
import { subDays } from 'date-fns'; |
|||
|
|||
jest.mock('@ghostfolio/api/app/portfolio/current-rate.service', () => { |
|||
return { |
|||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|||
CurrentRateService: jest.fn().mockImplementation(() => { |
|||
return CurrentRateServiceMock; |
|||
}) |
|||
}; |
|||
}); |
|||
|
|||
jest.mock('@ghostfolio/api/app/redis-cache/redis-cache.service', () => { |
|||
return { |
|||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|||
RedisCacheService: jest.fn().mockImplementation(() => { |
|||
return RedisCacheServiceMock; |
|||
}) |
|||
}; |
|||
}); |
|||
|
|||
describe('PortfolioCalculator', () => { |
|||
let configurationService: ConfigurationService; |
|||
let currentRateService: CurrentRateService; |
|||
let exchangeRateDataService: ExchangeRateDataService; |
|||
let factory: PortfolioCalculatorFactory; |
|||
let redisCacheService: RedisCacheService; |
|||
|
|||
beforeEach(() => { |
|||
configurationService = new ConfigurationService(); |
|||
|
|||
currentRateService = new CurrentRateService(null, null, null, null); |
|||
|
|||
exchangeRateDataService = new ExchangeRateDataService( |
|||
null, |
|||
null, |
|||
null, |
|||
null |
|||
); |
|||
|
|||
redisCacheService = new RedisCacheService(null, null); |
|||
|
|||
factory = new PortfolioCalculatorFactory( |
|||
configurationService, |
|||
currentRateService, |
|||
exchangeRateDataService, |
|||
redisCacheService |
|||
); |
|||
}); |
|||
|
|||
describe('get current positions', () => { |
|||
it('with no orders', async () => { |
|||
const spy = jest |
|||
.spyOn(Date, 'now') |
|||
.mockImplementation(() => parseDate('2021-12-18').getTime()); |
|||
|
|||
const portfolioCalculator = factory.createCalculator({ |
|||
activities: [], |
|||
calculationType: PerformanceCalculationType.TWR, |
|||
currency: 'CHF', |
|||
hasFilters: false, |
|||
userId: userDummyData.id |
|||
}); |
|||
|
|||
const start = subDays(new Date(Date.now()), 10); |
|||
|
|||
const chartData = await portfolioCalculator.getChartData({ start }); |
|||
|
|||
const portfolioSnapshot = |
|||
await portfolioCalculator.computeSnapshot(start); |
|||
|
|||
const investments = portfolioCalculator.getInvestments(); |
|||
|
|||
const investmentsByMonth = portfolioCalculator.getInvestmentsByGroup({ |
|||
data: chartData, |
|||
groupBy: 'month' |
|||
}); |
|||
|
|||
spy.mockRestore(); |
|||
|
|||
expect(portfolioSnapshot).toEqual({ |
|||
currentValueInBaseCurrency: new Big(0), |
|||
grossPerformance: new Big(0), |
|||
grossPerformancePercentage: new Big(0), |
|||
grossPerformancePercentageWithCurrencyEffect: new Big(0), |
|||
grossPerformanceWithCurrencyEffect: new Big(0), |
|||
hasErrors: false, |
|||
netPerformance: new Big(0), |
|||
netPerformancePercentage: new Big(0), |
|||
netPerformancePercentageWithCurrencyEffect: new Big(0), |
|||
netPerformanceWithCurrencyEffect: new Big(0), |
|||
positions: [], |
|||
totalFeesWithCurrencyEffect: new Big('0'), |
|||
totalInterestWithCurrencyEffect: new Big('0'), |
|||
totalInvestment: new Big(0), |
|||
totalInvestmentWithCurrencyEffect: new Big(0), |
|||
totalLiabilitiesWithCurrencyEffect: new Big('0'), |
|||
totalValuablesWithCurrencyEffect: new Big('0') |
|||
}); |
|||
|
|||
expect(investments).toEqual([]); |
|||
|
|||
expect(investmentsByMonth).toEqual([ |
|||
{ |
|||
date: '2021-12-01', |
|||
investment: 0 |
|||
} |
|||
]); |
|||
}); |
|||
}); |
|||
}); |
@ -0,0 +1,37 @@ |
|||
import { PortfolioCalculatorFactory } from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator.factory'; |
|||
import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service'; |
|||
import { RedisCacheService } from '@ghostfolio/api/app/redis-cache/redis-cache.service'; |
|||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|||
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; |
|||
|
|||
describe('PortfolioCalculator', () => { |
|||
let configurationService: ConfigurationService; |
|||
let currentRateService: CurrentRateService; |
|||
let exchangeRateDataService: ExchangeRateDataService; |
|||
let factory: PortfolioCalculatorFactory; |
|||
let redisCacheService: RedisCacheService; |
|||
|
|||
beforeEach(() => { |
|||
configurationService = new ConfigurationService(); |
|||
|
|||
currentRateService = new CurrentRateService(null, null, null, null); |
|||
|
|||
exchangeRateDataService = new ExchangeRateDataService( |
|||
null, |
|||
null, |
|||
null, |
|||
null |
|||
); |
|||
|
|||
redisCacheService = new RedisCacheService(null, null); |
|||
|
|||
factory = new PortfolioCalculatorFactory( |
|||
configurationService, |
|||
currentRateService, |
|||
exchangeRateDataService, |
|||
redisCacheService |
|||
); |
|||
}); |
|||
|
|||
test.skip('Skip empty test', () => 1); |
|||
}); |
@ -0,0 +1,922 @@ |
|||
import { PortfolioCalculator } from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator'; |
|||
import { PortfolioOrderItem } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-order-item.interface'; |
|||
import { getFactor } from '@ghostfolio/api/helper/portfolio.helper'; |
|||
import { DATE_FORMAT } from '@ghostfolio/common/helper'; |
|||
import { SymbolMetrics, UniqueAsset } from '@ghostfolio/common/interfaces'; |
|||
import { PortfolioSnapshot, TimelinePosition } from '@ghostfolio/common/models'; |
|||
|
|||
import { Logger } from '@nestjs/common'; |
|||
import { Big } from 'big.js'; |
|||
import { |
|||
addDays, |
|||
addMilliseconds, |
|||
differenceInDays, |
|||
format, |
|||
isBefore |
|||
} from 'date-fns'; |
|||
import { cloneDeep, first, last, sortBy } from 'lodash'; |
|||
|
|||
export class TWRPortfolioCalculator extends PortfolioCalculator { |
|||
protected calculateOverallPerformance( |
|||
positions: TimelinePosition[] |
|||
): PortfolioSnapshot { |
|||
let currentValueInBaseCurrency = new Big(0); |
|||
let grossPerformance = new Big(0); |
|||
let grossPerformanceWithCurrencyEffect = new Big(0); |
|||
let hasErrors = false; |
|||
let netPerformance = new Big(0); |
|||
let netPerformanceWithCurrencyEffect = new Big(0); |
|||
let totalFeesWithCurrencyEffect = new Big(0); |
|||
let totalInterestWithCurrencyEffect = new Big(0); |
|||
let totalInvestment = new Big(0); |
|||
let totalInvestmentWithCurrencyEffect = new Big(0); |
|||
let totalTimeWeightedInvestment = new Big(0); |
|||
let totalTimeWeightedInvestmentWithCurrencyEffect = new Big(0); |
|||
|
|||
for (const currentPosition of positions) { |
|||
if (currentPosition.fee) { |
|||
totalFeesWithCurrencyEffect = totalFeesWithCurrencyEffect.plus( |
|||
currentPosition.fee |
|||
); |
|||
} |
|||
|
|||
if (currentPosition.valueInBaseCurrency) { |
|||
currentValueInBaseCurrency = currentValueInBaseCurrency.plus( |
|||
currentPosition.valueInBaseCurrency |
|||
); |
|||
} else { |
|||
hasErrors = true; |
|||
} |
|||
|
|||
if (currentPosition.investment) { |
|||
totalInvestment = totalInvestment.plus(currentPosition.investment); |
|||
|
|||
totalInvestmentWithCurrencyEffect = |
|||
totalInvestmentWithCurrencyEffect.plus( |
|||
currentPosition.investmentWithCurrencyEffect |
|||
); |
|||
} else { |
|||
hasErrors = true; |
|||
} |
|||
|
|||
if (currentPosition.grossPerformance) { |
|||
grossPerformance = grossPerformance.plus( |
|||
currentPosition.grossPerformance |
|||
); |
|||
|
|||
grossPerformanceWithCurrencyEffect = |
|||
grossPerformanceWithCurrencyEffect.plus( |
|||
currentPosition.grossPerformanceWithCurrencyEffect |
|||
); |
|||
|
|||
netPerformance = netPerformance.plus(currentPosition.netPerformance); |
|||
|
|||
netPerformanceWithCurrencyEffect = |
|||
netPerformanceWithCurrencyEffect.plus( |
|||
currentPosition.netPerformanceWithCurrencyEffect |
|||
); |
|||
} else if (!currentPosition.quantity.eq(0)) { |
|||
hasErrors = true; |
|||
} |
|||
|
|||
if (currentPosition.timeWeightedInvestment) { |
|||
totalTimeWeightedInvestment = totalTimeWeightedInvestment.plus( |
|||
currentPosition.timeWeightedInvestment |
|||
); |
|||
|
|||
totalTimeWeightedInvestmentWithCurrencyEffect = |
|||
totalTimeWeightedInvestmentWithCurrencyEffect.plus( |
|||
currentPosition.timeWeightedInvestmentWithCurrencyEffect |
|||
); |
|||
} else if (!currentPosition.quantity.eq(0)) { |
|||
Logger.warn( |
|||
`Missing historical market data for ${currentPosition.symbol} (${currentPosition.dataSource})`, |
|||
'PortfolioCalculator' |
|||
); |
|||
|
|||
hasErrors = true; |
|||
} |
|||
} |
|||
|
|||
return { |
|||
currentValueInBaseCurrency, |
|||
grossPerformance, |
|||
grossPerformanceWithCurrencyEffect, |
|||
hasErrors, |
|||
netPerformance, |
|||
netPerformanceWithCurrencyEffect, |
|||
positions, |
|||
totalFeesWithCurrencyEffect, |
|||
totalInterestWithCurrencyEffect, |
|||
totalInvestment, |
|||
totalInvestmentWithCurrencyEffect, |
|||
netPerformancePercentage: totalTimeWeightedInvestment.eq(0) |
|||
? new Big(0) |
|||
: netPerformance.div(totalTimeWeightedInvestment), |
|||
netPerformancePercentageWithCurrencyEffect: |
|||
totalTimeWeightedInvestmentWithCurrencyEffect.eq(0) |
|||
? new Big(0) |
|||
: netPerformanceWithCurrencyEffect.div( |
|||
totalTimeWeightedInvestmentWithCurrencyEffect |
|||
), |
|||
grossPerformancePercentage: totalTimeWeightedInvestment.eq(0) |
|||
? new Big(0) |
|||
: grossPerformance.div(totalTimeWeightedInvestment), |
|||
grossPerformancePercentageWithCurrencyEffect: |
|||
totalTimeWeightedInvestmentWithCurrencyEffect.eq(0) |
|||
? new Big(0) |
|||
: grossPerformanceWithCurrencyEffect.div( |
|||
totalTimeWeightedInvestmentWithCurrencyEffect |
|||
), |
|||
totalLiabilitiesWithCurrencyEffect: new Big(0), |
|||
totalValuablesWithCurrencyEffect: new Big(0) |
|||
}; |
|||
} |
|||
|
|||
protected getSymbolMetrics({ |
|||
dataSource, |
|||
end, |
|||
exchangeRates, |
|||
isChartMode = false, |
|||
marketSymbolMap, |
|||
start, |
|||
step = 1, |
|||
symbol |
|||
}: { |
|||
end: Date; |
|||
exchangeRates: { [dateString: string]: number }; |
|||
isChartMode?: boolean; |
|||
marketSymbolMap: { |
|||
[date: string]: { [symbol: string]: Big }; |
|||
}; |
|||
start: Date; |
|||
step?: number; |
|||
} & UniqueAsset): SymbolMetrics { |
|||
const currentExchangeRate = exchangeRates[format(new Date(), DATE_FORMAT)]; |
|||
const currentValues: { [date: string]: Big } = {}; |
|||
const currentValuesWithCurrencyEffect: { [date: string]: Big } = {}; |
|||
let fees = new Big(0); |
|||
let feesAtStartDate = new Big(0); |
|||
let feesAtStartDateWithCurrencyEffect = new Big(0); |
|||
let feesWithCurrencyEffect = new Big(0); |
|||
let grossPerformance = new Big(0); |
|||
let grossPerformanceWithCurrencyEffect = new Big(0); |
|||
let grossPerformanceAtStartDate = new Big(0); |
|||
let grossPerformanceAtStartDateWithCurrencyEffect = new Big(0); |
|||
let grossPerformanceFromSells = new Big(0); |
|||
let grossPerformanceFromSellsWithCurrencyEffect = new Big(0); |
|||
let initialValue: Big; |
|||
let initialValueWithCurrencyEffect: Big; |
|||
let investmentAtStartDate: Big; |
|||
let investmentAtStartDateWithCurrencyEffect: Big; |
|||
const investmentValuesAccumulated: { [date: string]: Big } = {}; |
|||
const investmentValuesAccumulatedWithCurrencyEffect: { |
|||
[date: string]: Big; |
|||
} = {}; |
|||
const investmentValuesWithCurrencyEffect: { [date: string]: Big } = {}; |
|||
let lastAveragePrice = new Big(0); |
|||
let lastAveragePriceWithCurrencyEffect = new Big(0); |
|||
const netPerformanceValues: { [date: string]: Big } = {}; |
|||
const netPerformanceValuesWithCurrencyEffect: { [date: string]: Big } = {}; |
|||
const timeWeightedInvestmentValues: { [date: string]: Big } = {}; |
|||
|
|||
const timeWeightedInvestmentValuesWithCurrencyEffect: { |
|||
[date: string]: Big; |
|||
} = {}; |
|||
|
|||
let totalAccountBalanceInBaseCurrency = new Big(0); |
|||
let totalDividend = new Big(0); |
|||
let totalStakeRewards = new Big(0); |
|||
let totalDividendInBaseCurrency = new Big(0); |
|||
let totalInterest = new Big(0); |
|||
let totalInterestInBaseCurrency = new Big(0); |
|||
let totalInvestment = new Big(0); |
|||
let totalInvestmentFromBuyTransactions = new Big(0); |
|||
let totalInvestmentFromBuyTransactionsWithCurrencyEffect = new Big(0); |
|||
let totalInvestmentWithCurrencyEffect = new Big(0); |
|||
let totalLiabilities = new Big(0); |
|||
let totalLiabilitiesInBaseCurrency = new Big(0); |
|||
let totalQuantityFromBuyTransactions = new Big(0); |
|||
let totalUnits = new Big(0); |
|||
let totalValuables = new Big(0); |
|||
let totalValuablesInBaseCurrency = new Big(0); |
|||
let valueAtStartDate: Big; |
|||
let valueAtStartDateWithCurrencyEffect: Big; |
|||
|
|||
// Clone orders to keep the original values in this.orders
|
|||
let orders: PortfolioOrderItem[] = cloneDeep(this.activities).filter( |
|||
({ SymbolProfile }) => { |
|||
return SymbolProfile.symbol === symbol; |
|||
} |
|||
); |
|||
|
|||
if (orders.length <= 0) { |
|||
return { |
|||
currentValues: {}, |
|||
currentValuesWithCurrencyEffect: {}, |
|||
unitPrices: {}, |
|||
feesWithCurrencyEffect: new Big(0), |
|||
grossPerformance: new Big(0), |
|||
grossPerformancePercentage: new Big(0), |
|||
grossPerformancePercentageWithCurrencyEffect: new Big(0), |
|||
grossPerformanceWithCurrencyEffect: new Big(0), |
|||
hasErrors: false, |
|||
initialValue: new Big(0), |
|||
initialValueWithCurrencyEffect: new Big(0), |
|||
investmentValuesAccumulated: {}, |
|||
investmentValuesAccumulatedWithCurrencyEffect: {}, |
|||
investmentValuesWithCurrencyEffect: {}, |
|||
netPerformance: new Big(0), |
|||
netPerformancePercentage: new Big(0), |
|||
netPerformancePercentageWithCurrencyEffect: new Big(0), |
|||
netPerformanceValues: {}, |
|||
netPerformanceValuesWithCurrencyEffect: {}, |
|||
netPerformanceValuesPercentage: {}, |
|||
netPerformanceWithCurrencyEffect: new Big(0), |
|||
timeWeightedInvestment: new Big(0), |
|||
timeWeightedInvestmentValues: {}, |
|||
timeWeightedInvestmentValuesWithCurrencyEffect: {}, |
|||
timeWeightedInvestmentWithCurrencyEffect: new Big(0), |
|||
totalAccountBalanceInBaseCurrency: new Big(0), |
|||
totalDividend: new Big(0), |
|||
totalDividendInBaseCurrency: new Big(0), |
|||
totalInterest: new Big(0), |
|||
totalInterestInBaseCurrency: new Big(0), |
|||
totalInvestment: new Big(0), |
|||
totalInvestmentWithCurrencyEffect: new Big(0), |
|||
totalLiabilities: new Big(0), |
|||
totalLiabilitiesInBaseCurrency: new Big(0), |
|||
totalValuables: new Big(0), |
|||
totalValuablesInBaseCurrency: new Big(0) |
|||
}; |
|||
} |
|||
|
|||
const dateOfFirstTransaction = new Date(first(orders).date); |
|||
|
|||
const unitPriceAtStartDate = |
|||
marketSymbolMap[format(start, DATE_FORMAT)]?.[symbol]; |
|||
|
|||
const unitPriceAtEndDate = |
|||
marketSymbolMap[format(end, DATE_FORMAT)]?.[symbol]; |
|||
|
|||
if ( |
|||
!unitPriceAtEndDate || |
|||
(!unitPriceAtStartDate && isBefore(dateOfFirstTransaction, start)) |
|||
) { |
|||
return { |
|||
currentValues: {}, |
|||
currentValuesWithCurrencyEffect: {}, |
|||
unitPrices: {}, |
|||
feesWithCurrencyEffect: new Big(0), |
|||
grossPerformance: new Big(0), |
|||
grossPerformancePercentage: new Big(0), |
|||
grossPerformancePercentageWithCurrencyEffect: new Big(0), |
|||
grossPerformanceWithCurrencyEffect: new Big(0), |
|||
hasErrors: true, |
|||
initialValue: new Big(0), |
|||
initialValueWithCurrencyEffect: new Big(0), |
|||
investmentValuesAccumulated: {}, |
|||
investmentValuesAccumulatedWithCurrencyEffect: {}, |
|||
investmentValuesWithCurrencyEffect: {}, |
|||
netPerformance: new Big(0), |
|||
netPerformancePercentage: new Big(0), |
|||
netPerformancePercentageWithCurrencyEffect: new Big(0), |
|||
netPerformanceValues: {}, |
|||
netPerformanceValuesWithCurrencyEffect: {}, |
|||
netPerformanceValuesPercentage: {}, |
|||
netPerformanceWithCurrencyEffect: new Big(0), |
|||
timeWeightedInvestment: new Big(0), |
|||
timeWeightedInvestmentValues: {}, |
|||
timeWeightedInvestmentValuesWithCurrencyEffect: {}, |
|||
timeWeightedInvestmentWithCurrencyEffect: new Big(0), |
|||
totalAccountBalanceInBaseCurrency: new Big(0), |
|||
totalDividend: new Big(0), |
|||
totalDividendInBaseCurrency: new Big(0), |
|||
totalInterest: new Big(0), |
|||
totalInterestInBaseCurrency: new Big(0), |
|||
totalInvestment: new Big(0), |
|||
totalInvestmentWithCurrencyEffect: new Big(0), |
|||
totalLiabilities: new Big(0), |
|||
totalLiabilitiesInBaseCurrency: new Big(0), |
|||
totalValuables: new Big(0), |
|||
totalValuablesInBaseCurrency: new Big(0) |
|||
}; |
|||
} |
|||
|
|||
// Add a synthetic order at the start and the end date
|
|||
orders.push({ |
|||
date: format(start, DATE_FORMAT), |
|||
fee: new Big(0), |
|||
feeInBaseCurrency: new Big(0), |
|||
itemType: 'start', |
|||
quantity: new Big(0), |
|||
SymbolProfile: { |
|||
dataSource, |
|||
symbol |
|||
}, |
|||
type: 'BUY', |
|||
unitPrice: unitPriceAtStartDate |
|||
}); |
|||
|
|||
orders.push({ |
|||
date: format(end, DATE_FORMAT), |
|||
fee: new Big(0), |
|||
feeInBaseCurrency: new Big(0), |
|||
itemType: 'end', |
|||
SymbolProfile: { |
|||
dataSource, |
|||
symbol |
|||
}, |
|||
quantity: new Big(0), |
|||
type: 'BUY', |
|||
unitPrice: unitPriceAtEndDate |
|||
}); |
|||
|
|||
let day = start; |
|||
let lastUnitPrice: Big; |
|||
|
|||
if (isChartMode) { |
|||
const datesWithOrders = {}; |
|||
|
|||
for (const { date, type } of orders) { |
|||
if (['BUY', 'SELL', 'STAKE'].includes(type)) { |
|||
datesWithOrders[date] = true; |
|||
} |
|||
} |
|||
|
|||
while (isBefore(day, end)) { |
|||
const hasDate = datesWithOrders[format(day, DATE_FORMAT)]; |
|||
|
|||
if (!hasDate) { |
|||
orders.push({ |
|||
date: format(day, DATE_FORMAT), |
|||
fee: new Big(0), |
|||
feeInBaseCurrency: new Big(0), |
|||
quantity: new Big(0), |
|||
SymbolProfile: { |
|||
dataSource, |
|||
symbol |
|||
}, |
|||
type: 'BUY', |
|||
unitPrice: |
|||
marketSymbolMap[format(day, DATE_FORMAT)]?.[symbol] ?? |
|||
lastUnitPrice |
|||
}); |
|||
} |
|||
|
|||
lastUnitPrice = last(orders).unitPrice; |
|||
|
|||
day = addDays(day, step); |
|||
} |
|||
} |
|||
|
|||
// Sort orders so that the start and end placeholder order are at the correct
|
|||
// position
|
|||
orders = sortBy(orders, ({ date, itemType }) => { |
|||
let sortIndex = new Date(date); |
|||
|
|||
if (itemType === 'end') { |
|||
sortIndex = addMilliseconds(sortIndex, 1); |
|||
} else if (itemType === 'start') { |
|||
sortIndex = addMilliseconds(sortIndex, -1); |
|||
} |
|||
|
|||
return sortIndex.getTime(); |
|||
}); |
|||
|
|||
const indexOfStartOrder = orders.findIndex(({ itemType }) => { |
|||
return itemType === 'start'; |
|||
}); |
|||
|
|||
const indexOfEndOrder = orders.findIndex(({ itemType }) => { |
|||
return itemType === 'end'; |
|||
}); |
|||
|
|||
let totalInvestmentDays = 0; |
|||
let sumOfTimeWeightedInvestments = new Big(0); |
|||
let sumOfTimeWeightedInvestmentsWithCurrencyEffect = new Big(0); |
|||
|
|||
for (let i = 0; i < orders.length; i += 1) { |
|||
const order = orders[i]; |
|||
|
|||
if (PortfolioCalculator.ENABLE_LOGGING) { |
|||
console.log(); |
|||
console.log(); |
|||
console.log( |
|||
i + 1, |
|||
order.date, |
|||
order.type, |
|||
order.itemType ? `(${order.itemType})` : '' |
|||
); |
|||
} |
|||
|
|||
const exchangeRateAtOrderDate = exchangeRates[order.date]; |
|||
|
|||
if (order.type === 'DIVIDEND') { |
|||
const dividend = order.quantity.mul(order.unitPrice); |
|||
|
|||
totalDividend = totalDividend.plus(dividend); |
|||
totalDividendInBaseCurrency = totalDividendInBaseCurrency.plus( |
|||
dividend.mul(exchangeRateAtOrderDate ?? 1) |
|||
); |
|||
} else if (order.type === 'INTEREST') { |
|||
const interest = order.quantity.mul(order.unitPrice); |
|||
|
|||
totalInterest = totalInterest.plus(interest); |
|||
totalInterestInBaseCurrency = totalInterestInBaseCurrency.plus( |
|||
interest.mul(exchangeRateAtOrderDate ?? 1) |
|||
); |
|||
} else if (order.type === 'ITEM') { |
|||
const valuables = order.quantity.mul(order.unitPrice); |
|||
|
|||
totalValuables = totalValuables.plus(valuables); |
|||
totalValuablesInBaseCurrency = totalValuablesInBaseCurrency.plus( |
|||
valuables.mul(exchangeRateAtOrderDate ?? 1) |
|||
); |
|||
} else if (order.type === 'LIABILITY') { |
|||
const liabilities = order.quantity.mul(order.unitPrice); |
|||
|
|||
totalLiabilities = totalLiabilities.plus(liabilities); |
|||
totalLiabilitiesInBaseCurrency = totalLiabilitiesInBaseCurrency.plus( |
|||
liabilities.mul(exchangeRateAtOrderDate ?? 1) |
|||
); |
|||
} |
|||
|
|||
if (order.itemType === 'start') { |
|||
// Take the unit price of the order as the market price if there are no
|
|||
// orders of this symbol before the start date
|
|||
order.unitPrice = |
|||
indexOfStartOrder === 0 |
|||
? orders[i + 1]?.unitPrice |
|||
: unitPriceAtStartDate; |
|||
} |
|||
|
|||
if (order.fee) { |
|||
order.feeInBaseCurrency = order.fee.mul(currentExchangeRate ?? 1); |
|||
order.feeInBaseCurrencyWithCurrencyEffect = order.fee.mul( |
|||
exchangeRateAtOrderDate ?? 1 |
|||
); |
|||
} |
|||
|
|||
if (order.type === 'STAKE') { |
|||
order.unitPrice = marketSymbolMap[order.date]?.[symbol] ?? new Big(0); |
|||
} |
|||
|
|||
if (order.unitPrice) { |
|||
order.unitPriceInBaseCurrency = order.unitPrice.mul( |
|||
currentExchangeRate ?? 1 |
|||
); |
|||
|
|||
order.unitPriceInBaseCurrencyWithCurrencyEffect = order.unitPrice.mul( |
|||
exchangeRateAtOrderDate ?? 1 |
|||
); |
|||
} |
|||
|
|||
const valueOfInvestmentBeforeTransaction = totalUnits.mul( |
|||
order.unitPriceInBaseCurrency |
|||
); |
|||
|
|||
const valueOfInvestmentBeforeTransactionWithCurrencyEffect = |
|||
totalUnits.mul(order.unitPriceInBaseCurrencyWithCurrencyEffect); |
|||
|
|||
if (!investmentAtStartDate && i >= indexOfStartOrder) { |
|||
investmentAtStartDate = totalInvestment ?? new Big(0); |
|||
|
|||
investmentAtStartDateWithCurrencyEffect = |
|||
totalInvestmentWithCurrencyEffect ?? new Big(0); |
|||
|
|||
valueAtStartDate = valueOfInvestmentBeforeTransaction; |
|||
|
|||
valueAtStartDateWithCurrencyEffect = |
|||
valueOfInvestmentBeforeTransactionWithCurrencyEffect; |
|||
} |
|||
|
|||
let transactionInvestment = new Big(0); |
|||
let transactionInvestmentWithCurrencyEffect = new Big(0); |
|||
|
|||
if (order.type === 'BUY') { |
|||
transactionInvestment = order.quantity |
|||
.mul(order.unitPriceInBaseCurrency) |
|||
.mul(getFactor(order.type)); |
|||
|
|||
transactionInvestmentWithCurrencyEffect = order.quantity |
|||
.mul(order.unitPriceInBaseCurrencyWithCurrencyEffect) |
|||
.mul(getFactor(order.type)); |
|||
|
|||
totalQuantityFromBuyTransactions = |
|||
totalQuantityFromBuyTransactions.plus(order.quantity); |
|||
|
|||
totalInvestmentFromBuyTransactions = |
|||
totalInvestmentFromBuyTransactions.plus(transactionInvestment); |
|||
|
|||
totalInvestmentFromBuyTransactionsWithCurrencyEffect = |
|||
totalInvestmentFromBuyTransactionsWithCurrencyEffect.plus( |
|||
transactionInvestmentWithCurrencyEffect |
|||
); |
|||
} else if (order.type === 'SELL') { |
|||
if (totalUnits.gt(0)) { |
|||
transactionInvestment = totalInvestment |
|||
.div(totalUnits) |
|||
.mul(order.quantity) |
|||
.mul(getFactor(order.type)); |
|||
transactionInvestmentWithCurrencyEffect = |
|||
totalInvestmentWithCurrencyEffect |
|||
.div(totalUnits) |
|||
.mul(order.quantity) |
|||
.mul(getFactor(order.type)); |
|||
} |
|||
} |
|||
|
|||
if (PortfolioCalculator.ENABLE_LOGGING) { |
|||
console.log('order.quantity', order.quantity.toNumber()); |
|||
console.log('transactionInvestment', transactionInvestment.toNumber()); |
|||
|
|||
console.log( |
|||
'transactionInvestmentWithCurrencyEffect', |
|||
transactionInvestmentWithCurrencyEffect.toNumber() |
|||
); |
|||
} |
|||
|
|||
const totalInvestmentBeforeTransaction = totalInvestment; |
|||
|
|||
const totalInvestmentBeforeTransactionWithCurrencyEffect = |
|||
totalInvestmentWithCurrencyEffect; |
|||
|
|||
totalInvestment = totalInvestment.plus(transactionInvestment); |
|||
|
|||
totalInvestmentWithCurrencyEffect = |
|||
totalInvestmentWithCurrencyEffect.plus( |
|||
transactionInvestmentWithCurrencyEffect |
|||
); |
|||
|
|||
if (i >= indexOfStartOrder && !initialValue) { |
|||
if ( |
|||
i === indexOfStartOrder && |
|||
!valueOfInvestmentBeforeTransaction.eq(0) |
|||
) { |
|||
initialValue = valueOfInvestmentBeforeTransaction; |
|||
|
|||
initialValueWithCurrencyEffect = |
|||
valueOfInvestmentBeforeTransactionWithCurrencyEffect; |
|||
} else if (transactionInvestment.gt(0)) { |
|||
initialValue = transactionInvestment; |
|||
|
|||
initialValueWithCurrencyEffect = |
|||
transactionInvestmentWithCurrencyEffect; |
|||
} |
|||
} |
|||
|
|||
fees = fees.plus(order.feeInBaseCurrency ?? 0); |
|||
|
|||
feesWithCurrencyEffect = feesWithCurrencyEffect.plus( |
|||
order.feeInBaseCurrencyWithCurrencyEffect ?? 0 |
|||
); |
|||
|
|||
totalUnits = totalUnits.plus(order.quantity.mul(getFactor(order.type))); |
|||
|
|||
const valueOfInvestment = totalUnits.mul(order.unitPriceInBaseCurrency); |
|||
|
|||
const valueOfInvestmentWithCurrencyEffect = totalUnits.mul( |
|||
order.unitPriceInBaseCurrencyWithCurrencyEffect |
|||
); |
|||
|
|||
const grossPerformanceFromSell = |
|||
order.type === 'SELL' |
|||
? order.unitPriceInBaseCurrency |
|||
.minus(lastAveragePrice) |
|||
.mul(order.quantity) |
|||
: new Big(0); |
|||
|
|||
const grossPerformanceFromSellWithCurrencyEffect = |
|||
order.type === 'SELL' |
|||
? order.unitPriceInBaseCurrencyWithCurrencyEffect |
|||
.minus(lastAveragePriceWithCurrencyEffect) |
|||
.mul(order.quantity) |
|||
: new Big(0); |
|||
|
|||
grossPerformanceFromSells = grossPerformanceFromSells.plus( |
|||
grossPerformanceFromSell |
|||
); |
|||
|
|||
grossPerformanceFromSellsWithCurrencyEffect = |
|||
grossPerformanceFromSellsWithCurrencyEffect.plus( |
|||
grossPerformanceFromSellWithCurrencyEffect |
|||
); |
|||
|
|||
lastAveragePrice = totalQuantityFromBuyTransactions.eq(0) |
|||
? new Big(0) |
|||
: totalInvestmentFromBuyTransactions.div( |
|||
totalQuantityFromBuyTransactions |
|||
); |
|||
|
|||
lastAveragePriceWithCurrencyEffect = totalQuantityFromBuyTransactions.eq( |
|||
0 |
|||
) |
|||
? new Big(0) |
|||
: totalInvestmentFromBuyTransactionsWithCurrencyEffect.div( |
|||
totalQuantityFromBuyTransactions |
|||
); |
|||
|
|||
if (PortfolioCalculator.ENABLE_LOGGING) { |
|||
console.log( |
|||
'grossPerformanceFromSells', |
|||
grossPerformanceFromSells.toNumber() |
|||
); |
|||
console.log( |
|||
'grossPerformanceFromSellWithCurrencyEffect', |
|||
grossPerformanceFromSellWithCurrencyEffect.toNumber() |
|||
); |
|||
} |
|||
|
|||
const newGrossPerformance = valueOfInvestment |
|||
.minus(totalInvestment) |
|||
.plus(grossPerformanceFromSells); |
|||
|
|||
const newGrossPerformanceWithCurrencyEffect = |
|||
valueOfInvestmentWithCurrencyEffect |
|||
.minus(totalInvestmentWithCurrencyEffect) |
|||
.plus(grossPerformanceFromSellsWithCurrencyEffect); |
|||
|
|||
grossPerformance = newGrossPerformance; |
|||
|
|||
grossPerformanceWithCurrencyEffect = |
|||
newGrossPerformanceWithCurrencyEffect; |
|||
|
|||
if (order.itemType === 'start') { |
|||
feesAtStartDate = fees; |
|||
feesAtStartDateWithCurrencyEffect = feesWithCurrencyEffect; |
|||
grossPerformanceAtStartDate = grossPerformance; |
|||
|
|||
grossPerformanceAtStartDateWithCurrencyEffect = |
|||
grossPerformanceWithCurrencyEffect; |
|||
} |
|||
|
|||
if ( |
|||
i > indexOfStartOrder && |
|||
['BUY', 'SELL', 'STAKE'].includes(order.type) |
|||
) { |
|||
// Only consider periods with an investment for the calculation of
|
|||
// the time weighted investment
|
|||
if (valueOfInvestmentBeforeTransaction.gt(0)) { |
|||
// Calculate the number of days since the previous order
|
|||
const orderDate = new Date(order.date); |
|||
const previousOrderDate = new Date(orders[i - 1].date); |
|||
|
|||
let daysSinceLastOrder = differenceInDays( |
|||
orderDate, |
|||
previousOrderDate |
|||
); |
|||
if (daysSinceLastOrder <= 0) { |
|||
// The time between two activities on the same day is unknown
|
|||
// -> Set it to the smallest floating point number greater than 0
|
|||
daysSinceLastOrder = Number.EPSILON; |
|||
} |
|||
|
|||
// Sum up the total investment days since the start date to calculate
|
|||
// the time weighted investment
|
|||
totalInvestmentDays += daysSinceLastOrder; |
|||
|
|||
sumOfTimeWeightedInvestments = sumOfTimeWeightedInvestments.add( |
|||
valueAtStartDate |
|||
.minus(investmentAtStartDate) |
|||
.plus(totalInvestmentBeforeTransaction) |
|||
.mul(daysSinceLastOrder) |
|||
); |
|||
|
|||
sumOfTimeWeightedInvestmentsWithCurrencyEffect = |
|||
sumOfTimeWeightedInvestmentsWithCurrencyEffect.add( |
|||
valueAtStartDateWithCurrencyEffect |
|||
.minus(investmentAtStartDateWithCurrencyEffect) |
|||
.plus(totalInvestmentBeforeTransactionWithCurrencyEffect) |
|||
.mul(daysSinceLastOrder) |
|||
); |
|||
} |
|||
|
|||
if (isChartMode) { |
|||
currentValues[order.date] = valueOfInvestment; |
|||
|
|||
currentValuesWithCurrencyEffect[order.date] = |
|||
valueOfInvestmentWithCurrencyEffect; |
|||
|
|||
netPerformanceValues[order.date] = grossPerformance |
|||
.minus(grossPerformanceAtStartDate) |
|||
.minus(fees.minus(feesAtStartDate)); |
|||
|
|||
netPerformanceValuesWithCurrencyEffect[order.date] = |
|||
grossPerformanceWithCurrencyEffect |
|||
.minus(grossPerformanceAtStartDateWithCurrencyEffect) |
|||
.minus( |
|||
feesWithCurrencyEffect.minus(feesAtStartDateWithCurrencyEffect) |
|||
); |
|||
|
|||
investmentValuesAccumulated[order.date] = totalInvestment; |
|||
|
|||
investmentValuesAccumulatedWithCurrencyEffect[order.date] = |
|||
totalInvestmentWithCurrencyEffect; |
|||
|
|||
investmentValuesWithCurrencyEffect[order.date] = ( |
|||
investmentValuesWithCurrencyEffect[order.date] ?? new Big(0) |
|||
).add(transactionInvestmentWithCurrencyEffect); |
|||
|
|||
timeWeightedInvestmentValues[order.date] = |
|||
totalInvestmentDays > 0 |
|||
? sumOfTimeWeightedInvestments.div(totalInvestmentDays) |
|||
: new Big(0); |
|||
|
|||
timeWeightedInvestmentValuesWithCurrencyEffect[order.date] = |
|||
totalInvestmentDays > 0 |
|||
? sumOfTimeWeightedInvestmentsWithCurrencyEffect.div( |
|||
totalInvestmentDays |
|||
) |
|||
: new Big(0); |
|||
} |
|||
} |
|||
|
|||
if (PortfolioCalculator.ENABLE_LOGGING) { |
|||
console.log('totalInvestment', totalInvestment.toNumber()); |
|||
|
|||
console.log( |
|||
'totalInvestmentWithCurrencyEffect', |
|||
totalInvestmentWithCurrencyEffect.toNumber() |
|||
); |
|||
|
|||
console.log( |
|||
'totalGrossPerformance', |
|||
grossPerformance.minus(grossPerformanceAtStartDate).toNumber() |
|||
); |
|||
|
|||
console.log( |
|||
'totalGrossPerformanceWithCurrencyEffect', |
|||
grossPerformanceWithCurrencyEffect |
|||
.minus(grossPerformanceAtStartDateWithCurrencyEffect) |
|||
.toNumber() |
|||
); |
|||
} |
|||
|
|||
if (i === indexOfEndOrder) { |
|||
break; |
|||
} |
|||
} |
|||
|
|||
const totalGrossPerformance = grossPerformance.minus( |
|||
grossPerformanceAtStartDate |
|||
); |
|||
|
|||
const totalGrossPerformanceWithCurrencyEffect = |
|||
grossPerformanceWithCurrencyEffect.minus( |
|||
grossPerformanceAtStartDateWithCurrencyEffect |
|||
); |
|||
|
|||
const totalNetPerformance = grossPerformance |
|||
.minus(grossPerformanceAtStartDate) |
|||
.minus(fees.minus(feesAtStartDate)); |
|||
|
|||
const totalNetPerformanceWithCurrencyEffect = |
|||
grossPerformanceWithCurrencyEffect |
|||
.minus(grossPerformanceAtStartDateWithCurrencyEffect) |
|||
.minus(feesWithCurrencyEffect.minus(feesAtStartDateWithCurrencyEffect)); |
|||
|
|||
const timeWeightedAverageInvestmentBetweenStartAndEndDate = |
|||
totalInvestmentDays > 0 |
|||
? sumOfTimeWeightedInvestments.div(totalInvestmentDays) |
|||
: new Big(0); |
|||
|
|||
const timeWeightedAverageInvestmentBetweenStartAndEndDateWithCurrencyEffect = |
|||
totalInvestmentDays > 0 |
|||
? sumOfTimeWeightedInvestmentsWithCurrencyEffect.div( |
|||
totalInvestmentDays |
|||
) |
|||
: new Big(0); |
|||
|
|||
const grossPerformancePercentage = |
|||
timeWeightedAverageInvestmentBetweenStartAndEndDate.gt(0) |
|||
? totalGrossPerformance.div( |
|||
timeWeightedAverageInvestmentBetweenStartAndEndDate |
|||
) |
|||
: new Big(0); |
|||
|
|||
const grossPerformancePercentageWithCurrencyEffect = |
|||
timeWeightedAverageInvestmentBetweenStartAndEndDateWithCurrencyEffect.gt( |
|||
0 |
|||
) |
|||
? totalGrossPerformanceWithCurrencyEffect.div( |
|||
timeWeightedAverageInvestmentBetweenStartAndEndDateWithCurrencyEffect |
|||
) |
|||
: new Big(0); |
|||
|
|||
const feesPerUnit = totalUnits.gt(0) |
|||
? fees.minus(feesAtStartDate).div(totalUnits) |
|||
: new Big(0); |
|||
|
|||
const feesPerUnitWithCurrencyEffect = totalUnits.gt(0) |
|||
? feesWithCurrencyEffect |
|||
.minus(feesAtStartDateWithCurrencyEffect) |
|||
.div(totalUnits) |
|||
: new Big(0); |
|||
|
|||
const netPerformancePercentage = |
|||
timeWeightedAverageInvestmentBetweenStartAndEndDate.gt(0) |
|||
? totalNetPerformance.div( |
|||
timeWeightedAverageInvestmentBetweenStartAndEndDate |
|||
) |
|||
: new Big(0); |
|||
|
|||
const netPerformancePercentageWithCurrencyEffect = |
|||
timeWeightedAverageInvestmentBetweenStartAndEndDateWithCurrencyEffect.gt( |
|||
0 |
|||
) |
|||
? totalNetPerformanceWithCurrencyEffect.div( |
|||
timeWeightedAverageInvestmentBetweenStartAndEndDateWithCurrencyEffect |
|||
) |
|||
: new Big(0); |
|||
|
|||
if (PortfolioCalculator.ENABLE_LOGGING) { |
|||
console.log( |
|||
` |
|||
${symbol} |
|||
Unit price: ${orders[indexOfStartOrder].unitPrice.toFixed( |
|||
2 |
|||
)} -> ${unitPriceAtEndDate.toFixed(2)} |
|||
Total investment: ${totalInvestment.toFixed(2)} |
|||
Total investment with currency effect: ${totalInvestmentWithCurrencyEffect.toFixed( |
|||
2 |
|||
)} |
|||
Time weighted investment: ${timeWeightedAverageInvestmentBetweenStartAndEndDate.toFixed( |
|||
2 |
|||
)} |
|||
Time weighted investment with currency effect: ${timeWeightedAverageInvestmentBetweenStartAndEndDateWithCurrencyEffect.toFixed( |
|||
2 |
|||
)} |
|||
Total dividend: ${totalDividend.toFixed(2)} |
|||
Gross performance: ${totalGrossPerformance.toFixed( |
|||
2 |
|||
)} / ${grossPerformancePercentage.mul(100).toFixed(2)}% |
|||
Gross performance with currency effect: ${totalGrossPerformanceWithCurrencyEffect.toFixed( |
|||
2 |
|||
)} / ${grossPerformancePercentageWithCurrencyEffect |
|||
.mul(100) |
|||
.toFixed(2)}% |
|||
Fees per unit: ${feesPerUnit.toFixed(2)} |
|||
Fees per unit with currency effect: ${feesPerUnitWithCurrencyEffect.toFixed( |
|||
2 |
|||
)} |
|||
Net performance: ${totalNetPerformance.toFixed( |
|||
2 |
|||
)} / ${netPerformancePercentage.mul(100).toFixed(2)}% |
|||
Net performance with currency effect: ${totalNetPerformanceWithCurrencyEffect.toFixed( |
|||
2 |
|||
)} / ${netPerformancePercentageWithCurrencyEffect.mul(100).toFixed(2)}%` |
|||
); |
|||
} |
|||
|
|||
let unitPrices = Object.keys(marketSymbolMap) |
|||
.map((date) => { |
|||
return { [date]: marketSymbolMap[date][symbol] }; |
|||
}) |
|||
.reduce((map, u) => { |
|||
return { ...u, ...map }; |
|||
}, {}); |
|||
|
|||
return { |
|||
currentValues, |
|||
currentValuesWithCurrencyEffect, |
|||
unitPrices, |
|||
feesWithCurrencyEffect, |
|||
grossPerformancePercentage, |
|||
grossPerformancePercentageWithCurrencyEffect, |
|||
initialValue, |
|||
initialValueWithCurrencyEffect, |
|||
investmentValuesAccumulated, |
|||
investmentValuesAccumulatedWithCurrencyEffect, |
|||
investmentValuesWithCurrencyEffect, |
|||
netPerformancePercentage, |
|||
netPerformancePercentageWithCurrencyEffect, |
|||
netPerformanceValues, |
|||
netPerformanceValuesWithCurrencyEffect, |
|||
netPerformanceValuesPercentage: {}, |
|||
timeWeightedInvestmentValues, |
|||
timeWeightedInvestmentValuesWithCurrencyEffect, |
|||
totalAccountBalanceInBaseCurrency, |
|||
totalDividend, |
|||
totalDividendInBaseCurrency, |
|||
totalInterest, |
|||
totalInterestInBaseCurrency, |
|||
totalInvestment, |
|||
totalInvestmentWithCurrencyEffect, |
|||
totalLiabilities, |
|||
totalLiabilitiesInBaseCurrency, |
|||
totalValuables, |
|||
totalValuablesInBaseCurrency, |
|||
grossPerformance: totalGrossPerformance, |
|||
grossPerformanceWithCurrencyEffect: |
|||
totalGrossPerformanceWithCurrencyEffect, |
|||
hasErrors: totalUnits.gt(0) && (!initialValue || !unitPriceAtEndDate), |
|||
netPerformance: totalNetPerformance, |
|||
netPerformanceWithCurrencyEffect: totalNetPerformanceWithCurrencyEffect, |
|||
timeWeightedInvestment: |
|||
timeWeightedAverageInvestmentBetweenStartAndEndDate, |
|||
timeWeightedInvestmentWithCurrencyEffect: |
|||
timeWeightedAverageInvestmentBetweenStartAndEndDateWithCurrencyEffect |
|||
}; |
|||
} |
|||
} |
@ -1,19 +0,0 @@ |
|||
import { ResponseError, TimelinePosition } from '@ghostfolio/common/interfaces'; |
|||
|
|||
import Big from 'big.js'; |
|||
|
|||
export interface CurrentPositions extends ResponseError { |
|||
positions: TimelinePosition[]; |
|||
grossPerformance: Big; |
|||
grossPerformanceWithCurrencyEffect: Big; |
|||
grossPerformancePercentage: Big; |
|||
grossPerformancePercentageWithCurrencyEffect: Big; |
|||
netAnnualizedPerformance?: Big; |
|||
netAnnualizedPerformanceWithCurrencyEffect?: Big; |
|||
netPerformance: Big; |
|||
netPerformanceWithCurrencyEffect: Big; |
|||
netPerformancePercentage: Big; |
|||
netPerformancePercentageWithCurrencyEffect: Big; |
|||
currentValue: Big; |
|||
totalInvestment: Big; |
|||
} |
@ -1,11 +1,11 @@ |
|||
import Big from 'big.js'; |
|||
import { Big } from 'big.js'; |
|||
|
|||
import { PortfolioOrder } from './portfolio-order.interface'; |
|||
|
|||
export interface PortfolioOrderItem extends PortfolioOrder { |
|||
feeInBaseCurrency?: Big; |
|||
feeInBaseCurrencyWithCurrencyEffect?: Big; |
|||
itemType?: '' | 'start' | 'end'; |
|||
itemType?: 'end' | 'start'; |
|||
unitPriceInBaseCurrency?: Big; |
|||
unitPriceInBaseCurrencyWithCurrencyEffect?: Big; |
|||
} |
@ -1,15 +1,12 @@ |
|||
import { DataSource, Tag, Type as TypeOfOrder } from '@prisma/client'; |
|||
import Big from 'big.js'; |
|||
import { Activity } from '@ghostfolio/api/app/order/interfaces/activities.interface'; |
|||
|
|||
export interface PortfolioOrder { |
|||
currency: string; |
|||
export interface PortfolioOrder extends Pick<Activity, 'tags' | 'type'> { |
|||
date: string; |
|||
dataSource: DataSource; |
|||
fee: Big; |
|||
name: string; |
|||
quantity: Big; |
|||
symbol: string; |
|||
tags?: Tag[]; |
|||
type: TypeOfOrder; |
|||
SymbolProfile: Pick< |
|||
Activity['SymbolProfile'], |
|||
'currency' | 'dataSource' | 'name' | 'symbol' |
|||
>; |
|||
unitPrice: Big; |
|||
} |
|||
|
@ -1,5 +0,0 @@ |
|||
import { Position } from '@ghostfolio/common/interfaces'; |
|||
|
|||
export interface PortfolioPositions { |
|||
positions: Position[]; |
|||
} |
@ -1,6 +1,12 @@ |
|||
import { Big } from 'big.js'; |
|||
|
|||
import { TransactionPointSymbol } from './transaction-point-symbol.interface'; |
|||
|
|||
export interface TransactionPoint { |
|||
date: string; |
|||
fees: Big; |
|||
interest: Big; |
|||
items: TransactionPointSymbol[]; |
|||
liabilities: Big; |
|||
valuables: Big; |
|||
} |
|||
|
@ -1,86 +0,0 @@ |
|||
import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service'; |
|||
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; |
|||
import { parseDate } from '@ghostfolio/common/helper'; |
|||
|
|||
import Big from 'big.js'; |
|||
|
|||
import { CurrentRateServiceMock } from './current-rate.service.mock'; |
|||
import { PortfolioCalculator } from './portfolio-calculator'; |
|||
|
|||
jest.mock('@ghostfolio/api/app/portfolio/current-rate.service', () => { |
|||
return { |
|||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|||
CurrentRateService: jest.fn().mockImplementation(() => { |
|||
return CurrentRateServiceMock; |
|||
}) |
|||
}; |
|||
}); |
|||
|
|||
describe('PortfolioCalculator', () => { |
|||
let currentRateService: CurrentRateService; |
|||
let exchangeRateDataService: ExchangeRateDataService; |
|||
|
|||
beforeEach(() => { |
|||
currentRateService = new CurrentRateService(null, null, null, null); |
|||
|
|||
exchangeRateDataService = new ExchangeRateDataService( |
|||
null, |
|||
null, |
|||
null, |
|||
null |
|||
); |
|||
}); |
|||
|
|||
describe('get current positions', () => { |
|||
it('with no orders', async () => { |
|||
const portfolioCalculator = new PortfolioCalculator({ |
|||
currentRateService, |
|||
exchangeRateDataService, |
|||
currency: 'CHF', |
|||
orders: [] |
|||
}); |
|||
|
|||
portfolioCalculator.computeTransactionPoints(); |
|||
|
|||
const spy = jest |
|||
.spyOn(Date, 'now') |
|||
.mockImplementation(() => parseDate('2021-12-18').getTime()); |
|||
|
|||
const chartData = await portfolioCalculator.getChartData({ |
|||
start: new Date() |
|||
}); |
|||
|
|||
const currentPositions = await portfolioCalculator.getCurrentPositions( |
|||
new Date() |
|||
); |
|||
|
|||
const investments = portfolioCalculator.getInvestments(); |
|||
|
|||
const investmentsByMonth = portfolioCalculator.getInvestmentsByGroup({ |
|||
data: chartData, |
|||
groupBy: 'month' |
|||
}); |
|||
|
|||
spy.mockRestore(); |
|||
|
|||
expect(currentPositions).toEqual({ |
|||
currentValue: new Big(0), |
|||
grossPerformance: new Big(0), |
|||
grossPerformancePercentage: new Big(0), |
|||
grossPerformancePercentageWithCurrencyEffect: new Big(0), |
|||
grossPerformanceWithCurrencyEffect: new Big(0), |
|||
hasErrors: false, |
|||
netPerformance: new Big(0), |
|||
netPerformancePercentage: new Big(0), |
|||
netPerformancePercentageWithCurrencyEffect: new Big(0), |
|||
netPerformanceWithCurrencyEffect: new Big(0), |
|||
positions: [], |
|||
totalInvestment: new Big(0) |
|||
}); |
|||
|
|||
expect(investments).toEqual([]); |
|||
|
|||
expect(investmentsByMonth).toEqual([]); |
|||
}); |
|||
}); |
|||
}); |
@ -1,152 +0,0 @@ |
|||
import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service'; |
|||
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; |
|||
import { parseDate } from '@ghostfolio/common/helper'; |
|||
|
|||
import Big from 'big.js'; |
|||
|
|||
import { CurrentRateServiceMock } from './current-rate.service.mock'; |
|||
import { PortfolioCalculator } from './portfolio-calculator'; |
|||
|
|||
jest.mock('@ghostfolio/api/app/portfolio/current-rate.service', () => { |
|||
return { |
|||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|||
CurrentRateService: jest.fn().mockImplementation(() => { |
|||
return CurrentRateServiceMock; |
|||
}) |
|||
}; |
|||
}); |
|||
|
|||
describe('PortfolioCalculator', () => { |
|||
let currentRateService: CurrentRateService; |
|||
let exchangeRateDataService: ExchangeRateDataService; |
|||
|
|||
beforeEach(() => { |
|||
currentRateService = new CurrentRateService(null, null, null, null); |
|||
|
|||
exchangeRateDataService = new ExchangeRateDataService( |
|||
null, |
|||
null, |
|||
null, |
|||
null |
|||
); |
|||
}); |
|||
|
|||
describe('get current positions', () => { |
|||
it.only('with NOVN.SW and BALN.SW buy and sell', async () => { |
|||
const portfolioCalculator = new PortfolioCalculator({ |
|||
currentRateService, |
|||
exchangeRateDataService, |
|||
currency: 'CHF', |
|||
orders: [ |
|||
{ |
|||
currency: 'CHF', |
|||
date: '2022-03-07', |
|||
dataSource: 'YAHOO', |
|||
fee: new Big(0), |
|||
name: 'Novartis AG', |
|||
quantity: new Big(2), |
|||
symbol: 'NOVN.SW', |
|||
type: 'BUY', |
|||
unitPrice: new Big(75.8) |
|||
}, |
|||
{ |
|||
currency: 'CHF', |
|||
date: '2022-04-01', |
|||
dataSource: 'YAHOO', |
|||
fee: new Big(0), |
|||
name: 'Novartis AG', |
|||
quantity: new Big(0), |
|||
symbol: 'NOVN.SW', |
|||
type: 'BUY', |
|||
unitPrice: new Big(80.0) |
|||
}, |
|||
{ |
|||
currency: 'CHF', |
|||
date: '2022-04-08', |
|||
dataSource: 'YAHOO', |
|||
fee: new Big(0), |
|||
name: 'Novartis AG', |
|||
quantity: new Big(2), |
|||
symbol: 'NOVN.SW', |
|||
type: 'SELL', |
|||
unitPrice: new Big(85.73) |
|||
}, |
|||
{ |
|||
currency: 'CHF', |
|||
date: '2022-03-22', |
|||
dataSource: 'YAHOO', |
|||
fee: new Big(1.55), |
|||
name: 'Bâloise Holding AG', |
|||
quantity: new Big(2), |
|||
symbol: 'BALN.SW', |
|||
type: 'BUY', |
|||
unitPrice: new Big(142.9) |
|||
}, |
|||
{ |
|||
currency: 'CHF', |
|||
date: '2022-04-01', |
|||
dataSource: 'YAHOO', |
|||
fee: new Big(0), |
|||
name: 'Bâloise Holding AG', |
|||
quantity: new Big(0), |
|||
symbol: 'BALN.SW', |
|||
type: 'BUY', |
|||
unitPrice: new Big(138) |
|||
}, |
|||
{ |
|||
currency: 'CHF', |
|||
date: '2022-04-10', |
|||
dataSource: 'YAHOO', |
|||
fee: new Big(1.65), |
|||
name: 'Bâloise Holding AG', |
|||
quantity: new Big(2), |
|||
symbol: 'BALN.SW', |
|||
type: 'SELL', |
|||
unitPrice: new Big(136.6) |
|||
} |
|||
] |
|||
}); |
|||
|
|||
portfolioCalculator.computeTransactionPoints(); |
|||
|
|||
const spy = jest |
|||
.spyOn(Date, 'now') |
|||
.mockImplementation(() => parseDate('2022-04-11').getTime()); |
|||
|
|||
const chartData = await portfolioCalculator.getChartData({ |
|||
start: parseDate('2022-03-07'), |
|||
calculateTimeWeightedPerformance: true |
|||
}); |
|||
|
|||
spy.mockRestore(); |
|||
|
|||
expect(chartData[0]).toEqual({ |
|||
date: '2022-03-07', |
|||
investmentValueWithCurrencyEffect: 151.6, |
|||
netPerformance: 0, |
|||
netPerformanceInPercentage: 0, |
|||
netPerformanceInPercentageWithCurrencyEffect: 0, |
|||
netPerformanceWithCurrencyEffect: 0, |
|||
timeWeightedPerformance: 0, |
|||
totalInvestment: 151.6, |
|||
totalInvestmentValueWithCurrencyEffect: 151.6, |
|||
value: 151.6, |
|||
valueWithCurrencyEffect: 151.6 |
|||
}); |
|||
|
|||
expect(chartData[chartData.length - 1]).toEqual({ |
|||
date: '2022-04-11', |
|||
investmentValueWithCurrencyEffect: 0, |
|||
netPerformance: 19.86, |
|||
netPerformanceInPercentage: 13.100263852242744, |
|||
netPerformanceInPercentageWithCurrencyEffect: 13.100263852242744, |
|||
netPerformanceWithCurrencyEffect: 19.86, |
|||
timeWeightedPerformance: 0, |
|||
totalInvestment: 0, |
|||
totalInvestmentValueWithCurrencyEffect: 0, |
|||
value: 0, |
|||
valueWithCurrencyEffect: 0 |
|||
}); |
|||
}); |
|||
}); |
|||
}); |
File diff suppressed because it is too large
File diff suppressed because it is too large
@ -0,0 +1,13 @@ |
|||
import { RedisCacheService } from './redis-cache.service'; |
|||
|
|||
export const RedisCacheServiceMock = { |
|||
get: (key: string): Promise<string> => { |
|||
return Promise.resolve(null); |
|||
}, |
|||
getPortfolioSnapshotKey: (userId: string): string => { |
|||
return `portfolio-snapshot-${userId}`; |
|||
}, |
|||
set: (key: string, value: string, ttlInSeconds?: number): Promise<string> => { |
|||
return Promise.resolve(value); |
|||
} |
|||
}; |
@ -1,4 +1,4 @@ |
|||
export const environment = { |
|||
production: true, |
|||
version: `v${require('../../../../package.json').version}` |
|||
version: `${require('../../../../package.json').version}` |
|||
}; |
|||
|
@ -0,0 +1,11 @@ |
|||
import { RedisCacheModule } from '@ghostfolio/api/app/redis-cache/redis-cache.module'; |
|||
|
|||
import { Module } from '@nestjs/common'; |
|||
|
|||
import { PortfolioChangedListener } from './portfolio-changed.listener'; |
|||
|
|||
@Module({ |
|||
imports: [RedisCacheModule], |
|||
providers: [PortfolioChangedListener] |
|||
}) |
|||
export class EventsModule {} |
@ -0,0 +1,15 @@ |
|||
export class PortfolioChangedEvent { |
|||
private userId: string; |
|||
|
|||
public constructor({ userId }: { userId: string }) { |
|||
this.userId = userId; |
|||
} |
|||
|
|||
public static getName() { |
|||
return 'portfolio.changed'; |
|||
} |
|||
|
|||
public getUserId() { |
|||
return this.userId; |
|||
} |
|||
} |
@ -0,0 +1,25 @@ |
|||
import { RedisCacheService } from '@ghostfolio/api/app/redis-cache/redis-cache.service'; |
|||
|
|||
import { Injectable, Logger } from '@nestjs/common'; |
|||
import { OnEvent } from '@nestjs/event-emitter'; |
|||
|
|||
import { PortfolioChangedEvent } from './portfolio-changed.event'; |
|||
|
|||
@Injectable() |
|||
export class PortfolioChangedListener { |
|||
public constructor(private readonly redisCacheService: RedisCacheService) {} |
|||
|
|||
@OnEvent(PortfolioChangedEvent.getName()) |
|||
handlePortfolioChangedEvent(event: PortfolioChangedEvent) { |
|||
Logger.log( |
|||
`Portfolio of user '${event.getUserId()}' has changed`, |
|||
'PortfolioChangedListener' |
|||
); |
|||
|
|||
this.redisCacheService.remove( |
|||
this.redisCacheService.getPortfolioSnapshotKey({ |
|||
userId: event.getUserId() |
|||
}) |
|||
); |
|||
} |
|||
} |
@ -0,0 +1,91 @@ |
|||
import { resetHours } from '@ghostfolio/common/helper'; |
|||
import { DateRange } from '@ghostfolio/common/types'; |
|||
|
|||
import { Type as ActivityType } from '@prisma/client'; |
|||
import { |
|||
endOfDay, |
|||
max, |
|||
subDays, |
|||
startOfMonth, |
|||
startOfWeek, |
|||
startOfYear, |
|||
subYears, |
|||
endOfYear |
|||
} from 'date-fns'; |
|||
|
|||
export function getFactor(activityType: ActivityType) { |
|||
let factor: number; |
|||
|
|||
switch (activityType) { |
|||
case 'BUY': |
|||
case 'STAKE': |
|||
factor = 1; |
|||
break; |
|||
case 'SELL': |
|||
factor = -1; |
|||
break; |
|||
default: |
|||
factor = 0; |
|||
break; |
|||
} |
|||
|
|||
return factor; |
|||
} |
|||
|
|||
export function getInterval( |
|||
aDateRange: DateRange, |
|||
portfolioStart = new Date(0) |
|||
) { |
|||
let endDate = endOfDay(new Date(Date.now())); |
|||
let startDate = portfolioStart; |
|||
|
|||
switch (aDateRange) { |
|||
case '1d': |
|||
startDate = max([ |
|||
startDate, |
|||
subDays(resetHours(new Date(Date.now())), 1) |
|||
]); |
|||
break; |
|||
case 'mtd': |
|||
startDate = max([ |
|||
startDate, |
|||
subDays(startOfMonth(resetHours(new Date(Date.now()))), 1) |
|||
]); |
|||
break; |
|||
case 'wtd': |
|||
startDate = max([ |
|||
startDate, |
|||
subDays( |
|||
startOfWeek(resetHours(new Date(Date.now())), { weekStartsOn: 1 }), |
|||
1 |
|||
) |
|||
]); |
|||
break; |
|||
case 'ytd': |
|||
startDate = max([ |
|||
startDate, |
|||
subDays(startOfYear(resetHours(new Date(Date.now()))), 1) |
|||
]); |
|||
break; |
|||
case '1y': |
|||
startDate = max([ |
|||
startDate, |
|||
subYears(resetHours(new Date(Date.now())), 1) |
|||
]); |
|||
break; |
|||
case '5y': |
|||
startDate = max([ |
|||
startDate, |
|||
subYears(resetHours(new Date(Date.now())), 5) |
|||
]); |
|||
break; |
|||
case 'max': |
|||
break; |
|||
default: |
|||
// '2024', '2023', '2022', etc.
|
|||
endDate = endOfYear(new Date(aDateRange)); |
|||
startDate = max([startDate, new Date(aDateRange)]); |
|||
} |
|||
|
|||
return { endDate, startDate }; |
|||
} |
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue