Browse Source

Bugfix/market condition of benchmarks and watchlist items without market data

Without a quote or without the all time high (e.g. if the market data
has not been gathered yet or the data provider did not respond), the
change from the all time high was 0 and thus the benchmark or watchlist
item was reported as at its all time high.

Give no change and a neutral market condition instead, in the markets
overview, the watchlist, the portfolio table and the twitter bot.
pull/8480/head
RupeshMaster 2 days ago
parent
commit
45abd87508
  1. 1
      CHANGELOG.md
  2. 23
      apps/api/src/app/endpoints/watchlist/watchlist.service.ts
  3. 131
      apps/api/src/services/benchmark/benchmark.service.spec.ts
  4. 58
      apps/api/src/services/benchmark/benchmark.service.ts
  5. 16
      apps/api/src/services/portfolio-table/portfolio-table.service.spec.ts
  6. 5
      apps/api/src/services/portfolio-table/portfolio-table.service.ts
  7. 6
      apps/api/src/services/twitter-bot/twitter-bot.service.ts
  8. 2
      libs/common/src/lib/interfaces/benchmark.interface.ts

1
CHANGELOG.md

@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Fixed the case-insensitive sorting in the tag management of the admin control panel
- Fixed the missing localization of the range label in the paginator
- Fixed the requests of the twitter bot service with dummy credentials
- Fixed the market condition of benchmarks and watchlist items without market data (no longer reported as all time high)
## 3.100.0 - 2026-11-15

23
apps/api/src/app/endpoints/watchlist/watchlist.service.ts

@ -125,26 +125,23 @@ export class WatchlistService {
this.benchmarkService.getBenchmarkTrends({ dataSource, symbol })
]);
const performancePercent =
this.benchmarkService.calculateChangeInPercentage(
allTimeHigh?.marketPrice,
quotes[getAssetProfileIdentifier({ dataSource, symbol })]
?.marketPrice
);
const { marketCondition, performancePercent } =
this.benchmarkService.getAllTimeHighPerformance({
allTimeHighMarketPrice: allTimeHigh?.marketPrice,
marketPrice:
quotes[getAssetProfileIdentifier({ dataSource, symbol })]
?.marketPrice
});
return {
dataSource,
marketCondition,
symbol,
marketCondition:
this.benchmarkService.getMarketCondition(performancePercent),
name: assetProfile?.name,
performances: {
allTimeHigh: {
date: allTimeHigh?.date,
performancePercent:
this.benchmarkService.getPerformancePercentFromAllTimeHigh(
performancePercent
)
performancePercent,
date: allTimeHigh?.date
}
},
trend50d: trends.trend50d,

131
apps/api/src/services/benchmark/benchmark.service.spec.ts

@ -1,6 +1,9 @@
import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service';
import { MarketDataService } from '@ghostfolio/api/services/market-data/market-data.service';
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service';
import { PropertyService } from '@ghostfolio/api/services/property/property.service';
import { RedisCacheService } from '@ghostfolio/api/services/redis-cache/redis-cache.service';
import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service';
import { PROPERTY_BENCHMARKS } from '@ghostfolio/common/config';
import { DataSource } from '@prisma/client';
@ -36,6 +39,134 @@ describe('BenchmarkService', () => {
expect(benchmarkService.calculateChangeInPercentage(2, 1)).toEqual(-0.5);
});
describe('getAllTimeHighPerformance', () => {
it('gives the performance from the all time high and the market condition', () => {
expect(
benchmarkService.getAllTimeHighPerformance({
allTimeHighMarketPrice: 100,
marketPrice: 100
})
).toEqual({ marketCondition: 'ALL_TIME_HIGH', performancePercent: 0 });
expect(
benchmarkService.getAllTimeHighPerformance({
allTimeHighMarketPrice: 100,
marketPrice: 110
})
).toEqual({ marketCondition: 'ALL_TIME_HIGH', performancePercent: 0 });
expect(
benchmarkService.getAllTimeHighPerformance({
allTimeHighMarketPrice: 100,
marketPrice: 90
})
).toEqual({
marketCondition: 'NEUTRAL_MARKET',
performancePercent: -0.1
});
expect(
benchmarkService.getAllTimeHighPerformance({
allTimeHighMarketPrice: 100,
marketPrice: 75
})
).toEqual({ marketCondition: 'BEAR_MARKET', performancePercent: -0.25 });
});
it.each([
{ allTimeHighMarketPrice: undefined, marketPrice: 100 },
{ allTimeHighMarketPrice: 100, marketPrice: undefined },
{ allTimeHighMarketPrice: undefined, marketPrice: undefined },
{ allTimeHighMarketPrice: 100, marketPrice: 0 }
])(
'gives no all time high without market data (all time high: $allTimeHighMarketPrice, market price: $marketPrice)',
({ allTimeHighMarketPrice, marketPrice }) => {
expect(
benchmarkService.getAllTimeHighPerformance({
allTimeHighMarketPrice,
marketPrice
})
).toEqual({
marketCondition: 'NEUTRAL_MARKET',
performancePercent: undefined
});
}
);
});
describe('getBenchmarks', () => {
const createBenchmarkService = ({
quotes
}: {
quotes: { [assetProfileIdentifier: string]: { marketPrice: number } };
}) => {
const set = jest.fn().mockResolvedValue(undefined);
return {
set,
benchmarkService: new BenchmarkService(
{
getQuotes: jest.fn().mockResolvedValue(quotes)
} as unknown as DataProviderService,
{
getMax: jest.fn().mockResolvedValue({
date: new Date('2026-10-01T00:00:00.000Z'),
marketPrice: 100
}),
marketDataItems: jest.fn().mockResolvedValue([])
} as unknown as MarketDataService,
null,
{
getByKey: jest
.fn()
.mockResolvedValue([{ symbolProfileId: 'profile-id' }])
} as unknown as PropertyService,
{ set } as unknown as RedisCacheService,
{
getSymbolProfilesByIds: jest.fn().mockResolvedValue([
{
dataSource: DataSource.YAHOO,
id: 'profile-id',
name: 'S&P 500',
symbol: '^GSPC'
}
])
} as unknown as SymbolProfileService
)
};
};
it('gives the market condition of a benchmark', async () => {
const { benchmarkService, set } = createBenchmarkService({
quotes: { 'YAHOO-^GSPC': { marketPrice: 75 } }
});
const [benchmark] = await benchmarkService.getBenchmarks({
useCache: false
});
expect(benchmark).toMatchObject({
marketCondition: 'BEAR_MARKET',
performances: { allTimeHigh: { performancePercent: -0.25 } }
});
expect(set).toHaveBeenCalledTimes(1);
});
it('does not give the all time high of a benchmark without a quote', async () => {
const { benchmarkService, set } = createBenchmarkService({ quotes: {} });
const [benchmark] = await benchmarkService.getBenchmarks({
useCache: false
});
expect(benchmark.marketCondition).toEqual('NEUTRAL_MARKET');
expect(
benchmark.performances.allTimeHigh.performancePercent
).toBeUndefined();
expect(set).not.toHaveBeenCalled();
});
});
it('getMarketCondition', async () => {
expect(benchmarkService.getMarketCondition(0)).toEqual('ALL_TIME_HIGH');
expect(benchmarkService.getMarketCondition(-5.90736454893e-9)).toEqual(

58
apps/api/src/services/benchmark/benchmark.service.ts

@ -52,6 +52,41 @@ export class BenchmarkService {
return 0;
}
/**
* Gives the performance from the all time high together with the market
* condition. Without the all time high or the current market price (e.g. if
* the market data has not been gathered yet or the data provider did not
* respond) the performance is unknown instead of at the all time high.
*/
public getAllTimeHighPerformance({
allTimeHighMarketPrice,
marketPrice
}: {
allTimeHighMarketPrice?: number;
marketPrice?: number;
}): {
marketCondition: Benchmark['marketCondition'];
performancePercent?: number;
} {
if (!allTimeHighMarketPrice || !marketPrice) {
return {
marketCondition: 'NEUTRAL_MARKET',
performancePercent: undefined
};
}
const performancePercent = this.calculateChangeInPercentage(
allTimeHighMarketPrice,
marketPrice
);
return {
marketCondition: this.getMarketCondition(performancePercent),
performancePercent:
this.getPerformancePercentFromAllTimeHigh(performancePercent)
};
}
public async getBenchmarkTrends({
dataSource,
symbol
@ -279,29 +314,24 @@ export class BenchmarkService {
const { marketPrice } =
quotes[getAssetProfileIdentifier({ dataSource, symbol })] ?? {};
let performancePercentFromAllTimeHigh = 0;
const { marketCondition, performancePercent } =
this.getAllTimeHighPerformance({
marketPrice,
allTimeHighMarketPrice: allTimeHigh?.marketPrice
});
if (allTimeHigh?.marketPrice && marketPrice) {
performancePercentFromAllTimeHigh = this.calculateChangeInPercentage(
allTimeHigh.marketPrice,
marketPrice
);
} else {
if (performancePercent === undefined) {
storeInCache = false;
}
return {
marketCondition,
dataSource: benchmarkAssetProfiles[index].dataSource,
marketCondition: this.getMarketCondition(
performancePercentFromAllTimeHigh
),
name: benchmarkAssetProfiles[index].name,
performances: {
allTimeHigh: {
date: allTimeHigh?.date as Date,
performancePercent: this.getPerformancePercentFromAllTimeHigh(
performancePercentFromAllTimeHigh
)
performancePercent,
date: allTimeHigh?.date as Date
}
},
symbol: benchmarkAssetProfiles[index].symbol,

16
apps/api/src/services/portfolio-table/portfolio-table.service.spec.ts

@ -846,6 +846,22 @@ describe('PortfolioTableService', () => {
expect(row).toContain('-25.000%');
});
it('gives no change of the all time high if it is unknown', async () => {
const watchlistItem = createWatchlistItem();
watchlistItem.marketCondition = 'NEUTRAL_MARKET';
watchlistItem.performances.allTimeHigh.performancePercent = undefined;
const result = await getWatchlistTable([watchlistItem]);
const [row] = result.split('\n').filter((line) => {
return line.startsWith('| Name of AAPL');
});
expect(row).toContain('NEUTRAL_MARKET');
expect(row).not.toContain('%');
expect(row).not.toContain('NaN');
});
it('tells that no watchlist items are found if the result is empty', async () => {
const result = await getWatchlistTable([]);

5
apps/api/src/services/portfolio-table/portfolio-table.service.ts

@ -27,6 +27,7 @@ import {
Type as ActivityType
} from '@prisma/client';
import { format } from 'date-fns';
import { isNumber } from 'lodash-es';
import { DataSourceTableContext } from './interfaces/data-source-table-context.interface';
import { HoldingsTableColumnDefinition } from './types/holdings-table-column-definition.type';
@ -421,7 +422,9 @@ export class PortfolioTableService {
{
align: 'right',
getValue: ({ performances }) => {
return getPercentage(performances.allTimeHigh.performancePercent);
return isNumber(performances.allTimeHigh.performancePercent)
? getPercentage(performances.allTimeHigh.performancePercent)
: '';
},
name: 'Change from All Time High'
},

6
apps/api/src/services/twitter-bot/twitter-bot.service.ts

@ -10,7 +10,7 @@ import {
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { isWeekend } from 'date-fns';
import { round } from 'lodash-es';
import { isNumber, round } from 'lodash-es';
import { TwitterApi, TwitterApiReadWrite } from 'twitter-api-v2';
@Injectable()
@ -112,6 +112,10 @@ export class TwitterBotService implements OnModuleInit {
});
return benchmarks
.filter(({ performances }) => {
// The performance is unknown without market data
return isNumber(performances.allTimeHigh.performancePercent);
})
.map(({ name, performances }) => {
const performancePercent = round(
performances.allTimeHigh.performancePercent,

2
libs/common/src/lib/interfaces/benchmark.interface.ts

@ -9,7 +9,7 @@ export interface Benchmark {
performances: {
allTimeHigh: {
date: Date;
performancePercent: number;
performancePercent?: number;
};
};
symbol: EnhancedAssetProfile['symbol'];

Loading…
Cancel
Save