Files
token-circles/backend/services/yahooFinanceService.js
T
KomediruzeckiandGitHub 16c4928a0d fix(portfolio): live prices never load — every holding reports a gain of 0.00 (#403)
* fix(portfolio): instantiate the yahoo-finance2 v3 client

backend/package.json has been on yahoo-finance2 ^3.14.0 for a while, but
getClient() still uses the v2 convention and calls .quote() on the
default export. In v3 that export is the class, so the call throws
"Call `const yahooFinance = new YahooFinance()` first" -- straight into
this module's own catch, which returns {} as a "fallback".

Nothing surfaces the failure. routes/portfolio.js reads
`prices[h.ticker] || h.purchase_price`, so an empty map degrades to cost
basis for every ticker: current price equals purchase price, market
value equals cost basis, and gain/loss is exactly 0.00 (+0.00%) for
every holding, for every user, on the holdings table, the summary
totals, and the allocation chart alike. "Refresh Prices" changes
nothing, and a portfolio that has never moved a cent looks plausible
enough to go unreported.

Verified against the seeded demo profile: before, 8 holdings at 0.00
across the board; after, live quotes for all 8 and no fallback warnings
in the log.

* test(portfolio): pin the price client against the v2/v3 regression

The bug this guards had no symptom to test for: the service catches
everything and returns {}, and the route degrades to cost basis, so a
total failure to reach Yahoo renders as a portfolio where every gain is
0.00. Nothing logs, and a flat portfolio looks plausible.

So the assertion is that a price actually arrives. Used as a bare class
again, `quote` is undefined, the throw is swallowed, and five of these
seven fail -- verified by restoring the old getClient() and re-running.

* test(portfolio): guard fetchQuotes the same way fetchPrices is now guarded

fetchQuotes backs POST /api/portfolio/prices and goes through the same getClient(), so it
failed in exactly the same way and was left with no test. Its fallback is an empty array
rather than an empty map, which the route turns into an empty price response and the page
into a "Refresh Prices" button that does nothing at all.

Verified as a real guard rather than a passing formality: restoring the bare-class client
fails nine of the thirteen, four of them from this block.
2026-08-23 01:26:20 +02:00

56 lines
1.7 KiB
JavaScript

/**
* Yahoo Finance Service — wraps yahoo-finance2 with lazy loading and error handling.
*/
let _yahooFinance = null;
function getClient() {
if (!_yahooFinance) {
// yahoo-finance2 v3 exports the class, not a ready-made singleton. Calling `.quote()` on
// the class throws "Call `const yahooFinance = new YahooFinance()` first", which this
// module swallows into the empty-price fallback -- so every holding silently reports
// currentPrice === purchase_price and a gain of exactly 0.
const YahooFinance = require('yahoo-finance2').default;
_yahooFinance = new YahooFinance();
}
return _yahooFinance;
}
/**
* Fetch current prices for an array of tickers.
* Returns { [symbol]: price } map. Silently returns empty object on failure.
*/
async function fetchPrices(tickers) {
if (!tickers || tickers.length === 0) return {};
try {
const quotes = await getClient().quote(tickers);
const quoteList = Array.isArray(quotes) ? quotes : [quotes];
const prices = {};
for (const q of quoteList) {
if (q && q.symbol && q.regularMarketPrice != null) {
prices[q.symbol] = q.regularMarketPrice;
}
}
return prices;
} catch (err) {
console.error('Failed to fetch live prices, using fallback:', err.message);
return {};
}
}
/**
* Fetch full quotes for arbitrary tickers.
* Returns the raw quote array, or empty array on failure.
*/
async function fetchQuotes(tickers) {
if (!tickers || tickers.length === 0) return [];
try {
const quotes = await getClient().quote(tickers);
return Array.isArray(quotes) ? quotes : [quotes];
} catch (err) {
console.error('Failed to fetch quotes, using fallback:', err.message);
return [];
}
}
module.exports = { fetchPrices, fetchQuotes };