From 3a99b81ade8cb90f4929143120ec8190eda5a76f Mon Sep 17 00:00:00 2001 From: Thomas Kaul <4159106+dtslvr@users.noreply.github.com> Date: Sat, 6 May 2023 11:17:41 +0200 Subject: [PATCH] Bugfix/add fallback in yahoo finance service (#1935) * Add fallback to use quoteSummary(symbol) if quote(symbols) fails * Update changelog --- CHANGELOG.md | 1 + .../yahoo-finance/yahoo-finance.service.ts | 41 ++++++++++++++++++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1436d3e90..d65817d14 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Added a fallback to use `quoteSummary(symbol)` if `quote(symbols)` fails in the _Yahoo Finance_ service - Added the missing `dataSource` attribute to the activities import ## 1.265.0 - 2023-05-01 diff --git a/apps/api/src/services/data-provider/yahoo-finance/yahoo-finance.service.ts b/apps/api/src/services/data-provider/yahoo-finance/yahoo-finance.service.ts index 0671cf8c8..b0d94baf6 100644 --- a/apps/api/src/services/data-provider/yahoo-finance/yahoo-finance.service.ts +++ b/apps/api/src/services/data-provider/yahoo-finance/yahoo-finance.service.ts @@ -14,6 +14,7 @@ import { DataSource, SymbolProfile } from '@prisma/client'; import Big from 'big.js'; import { addDays, format, isSameDay } from 'date-fns'; import yahooFinance from 'yahoo-finance2'; +import { Quote } from 'yahoo-finance2/dist/esm/src/modules/quote'; @Injectable() export class YahooFinanceService implements DataProviderInterface { @@ -175,7 +176,23 @@ export class YahooFinanceService implements DataProviderInterface { try { const response: { [symbol: string]: IDataProviderResponse } = {}; - const quotes = await yahooFinance.quote(yahooFinanceSymbols); + let quotes: Pick< + Quote, + 'currency' | 'marketState' | 'regularMarketPrice' | 'symbol' + >[] = []; + + try { + quotes = await yahooFinance.quote(yahooFinanceSymbols); + } catch (error) { + Logger.error(error, 'YahooFinanceService'); + + Logger.warn( + 'Fallback to yahooFinance.quoteSummary()', + 'YahooFinanceService' + ); + + quotes = await this.getQuotesWithQuoteSummary(yahooFinanceSymbols); + } for (const quote of quotes) { // Convert symbols back @@ -358,4 +375,26 @@ export class YahooFinanceService implements DataProviderInterface { return value; } + + private async getQuotesWithQuoteSummary(aYahooFinanceSymbols: string[]) { + const quoteSummaryPromises = aYahooFinanceSymbols.map((symbol) => { + return yahooFinance.quoteSummary(symbol).catch(() => { + Logger.error( + `Could not get quote summary for ${symbol}`, + 'YahooFinanceService' + ); + return null; + }); + }); + + const quoteSummaryItems = await Promise.all(quoteSummaryPromises); + + return quoteSummaryItems + .filter((item) => { + return item !== null; + }) + .map(({ price }) => { + return price; + }); + } }