๐ Yahoo Finance Provider (yfinance)
The Yahoo Finance provider fetches stock, ETF, crypto, and index prices using the yfinance library. It is the primary market data provider for LibreFolio.
Implementation: backend/app/services/asset_source_providers/yahoo_finance/plugin.py
๐ User Guide: Yahoo Finance โ User Manual
โ๏ธ How it Works
- Identifier: A Yahoo Finance ticker symbol (e.g.,
AAPL,BTC-USD,IE00B4L5Y983). - Identifier Types:
TICKERandISINare both accepted. ISIN is resolved by yfinance internally. - No
provider_params: Yahoo Finance does not require any additional configuration.
๐ฐ Current Value (get_current_value)
- The asset-source service checks its core current-value cache (120s TTL) before invoking the provider.
- Calls
ticker.infoโ the YahooquoteSummaryendpoint. ReturnsregularMarketPrice,currency, andregularMarketTimein a single lightweight call. - Fallback price:
currentPriceโpreviousClose(ifregularMarketPriceis null). as_of_dateis the date ofregularMarketTimein the exchange's timezone,info["exchangeTimezoneName"], which the plugin's private_exchange_zone()turns into aZoneInfo: UTC when Yahoo gives none or one the server's timezone database does not know (see Limitations), and the server's today withoutregularMarketTime. Up to 1.2.1 the date was always UTC's, the day before for the part of a session that falls before UTC midnight, such as Sydney's or Auckland's (Z-33).- No
history()call at all โ current value polling never touches the chart API.
Avoid history() and fast_info for current price
ticker.history()calls the chart API and logs noisyEntering history()lines.ticker.fast_infointernally triggers 2 heavy HTTP calls (range=1y+range=5d).ticker.infouses thequoteSummaryendpoint โ lighter, returns price + currency together.
Cache TTL vs Polling Interval
Frontend polls every 30s for responsive UI, while the core cache has a 120s TTL. Repeated polls for the same provider key can therefore return without another Yahoo call.
๐ Historical Data (get_history_value)
The public method now delegates its local work to focused helpers without changing its contract:
- Acquire โ
_acquire_history_data() start_date == "min"callsticker.history(period="max", auto_adjust=False).- A finite range calls
ticker.history(start=start_date, end=end_date + 1 day, auto_adjust=False), preserving LibreFolio's inclusive end date over yfinance's exclusiveend. - The closes are the exchange's own (
auto_adjust=False, Z-35):Closeis not rewritten for the dividends paid since. yfinance's default would rewrite it as of the day it is read, so rows saved on different days carried different adjustments, and a return counted a dividend twice (in the price and in its event). Yahoo'sClosestays adjusted for splits in either mode (checked on AAPL's 4:1 of 31 Aug 2020: the raw close of 28 Aug is 124.81, not about 499); the splits come as events too. The extraAdj Closecolumn of the raw frame is ignored. - Currency metadata falls back to
USD. - Otherwise the currency is Yahoo's own code (
ticker.info["currency"]), passed on unchanged asFAHistoricalData.currency:GBpfor a London line quoted in pence, whose price points and dividends carryGBP(their schemas upper-case the code) with the numbers in pence. Two guards intest_yahoo_finance_errors.pypin it: no validator may fold that field, and the plugin converts nothing. Such an asset needs a quote base of 100, which the plugin suggests (Quote Base Suggestion). - Dividend and split series are acquired independently and best-effort; one failing does not suppress the other or the prices.
- Map โ
_map_history_prices() - Each row takes the calendar date of its own index value (
_normalize_yahoo_date()): yfinance 1.7.0 stamps a daily bar, a dividend and a split at midnight in the exchange's timezone (scrapers/history.py,tz_localize(tz_exchange)), so that date is the session's. Up to 1.2.1 the plugin converted the index to UTC first, which gave the day before the session for every exchange east of UTC: Milan all year, London in summer time, Tokyo (Z-33). The rows stored that way stay as they are (Dates on the Exchange's Own Day). - Rows are filtered to the requested inclusive range.
- A row with
Close = NaNis skipped. OptionalOpen,High,Low, orVolumeNaNs becomeNone. - The provider returns only actual trading days; the query layer performs backward fill.
- Events โ
_parse_dividend_events()and_parse_split_events() - Positive in-range dividends and non-trivial in-range split ratios become typed asset events,
dated by
_normalize_yahoo_date()as the prices. - A dividend of a minor-unit line is divided by the unit's factor (Z-32 a/b): Yahoo gives a London
line's dividends in pence like its closes, so
1.9542on aGBpline becomes0.019542GBP (minor_unit_factor(),utils/currency_units.py). The prices keep their pence (the asset's quote base divides them) and a split ratio is a number of shares, never scaled. - The two parsers are also isolated best-effort, so either event family can survive a failure in the other.
Validation and data failures remain typed AssetSourceErrors: unsupported identifier types use
INVALID_IDENTIFIER_TYPE, a missing optional dependency uses NOT_AVAILABLE, empty/unusable
history uses NO_DATA, and malformed or unexpected Yahoo responses use FETCH_ERROR.
No provider-internal thread hop
Yahoo's yfinance calls remain synchronous and direct. The provider does not call
asyncio.to_thread(); the asset-source service invokes the whole provider coroutine through
assets.core._run_provider_in_thread() in a dedicated thread with a new event loop.
๐ Search (search)
- Uses
yfinance.Search(query)for real-time ticker search. - Minimum query length: 2 characters.
- Results limited to top 20 quotes.
quoteTypeis normalized to LibreFolio asset types:equity โ STOCK,etf โ ETF,mutualfund โ FUND,cryptocurrency โ CRYPTO, etc.- Currency is fetched per-symbol via
_fetch_currency()(fast_info), cached separately for 24 hours. Only an answer is cached: a currency, or Yahoo answering without one (Z-39).- A refusal for too many requests (
_is_rate_limited()) raisesAssetRateLimitedErrorat once, with no retry and nothing cached: the whole search leaves as rate limited at that result, the remaining results' currencies are not asked, and the core pauses Yahoo. - Any other error gives that result no currency and is not cached: the next search asks again.
- A refusal for too many requests (
- A result whose currency is a minor unit carries a
quote_base_suggestion:GBpgives{"quantity": 100, "quote_currency": "GBp"}; any other currency, or none, adds no key (Quote Base Suggestion).
๐ Metadata (fetch_asset_metadata)
- Fetches full
ticker.infofrom Yahoo Finance. - Extracts:
asset_type,currency,short_description(fromlongBusinessSummary),sector(single-sector distribution),identifier_ticker,identifier_isin. - ISIN is obtained via
ticker.isin(not available for all markets). - Unknown sectors are logged as warnings and mapped to "Other".
Fund data (quoteType etf / mutualfund)
For a fund the plugin also reads Ticker.funds_data (_read_fund_extras), one more Yahoo request in the same
cached metadata call. An equity never touches it.
| Piece | Source | Goes to |
|---|---|---|
| Sector breakdown | sector_weightings |
classification_params.sector_area, replacing the single info["sector"] |
| Description | description |
short_description, only when longBusinessSummary is empty |
| Expense ratio | fund_operations (ยซAnnual Report Expense Ratioยป) |
\| TER: x% after the description |
| Issuer | fund_overview["family"] |
\| Issuer: <family> after the TER |
- Sector keys are Yahoo's own spellings (
consumer_cyclical,realestate,financial_servicesโฆ), whichFinancialSector.from_stringdoes not know:_YAHOO_FUND_SECTORSmaps the eleven explicitly. A key outside the table goes to ยซOtherยป with the unknown-sector warning. The weights are renormalised to 1, as justETF's are. - The expense ratio is a fraction (
0.0003= 0.03 %): it is shown as a percentage rounded to two decimals. A missing,NaNor non-positive value is left out (VWCE.DE has none). - The 500-character cap cuts the head of the description, never the tail, so the TER and the issuer always survive.
- Error policy: every piece is read apart (
_read_fund_piece), so one that Yahoo lacks or that cannot be read costs only itself and is logged as a warning; the metadata still comes back. A ยซtoo many requestsยป refusal is the exception and leaves asAssetRateLimitedError, like every other Yahoo call. - The country breakdown, the holdings and the asset classes are not read: Yahoo gives no countries, and the rest has no
field to land in yet (
TODO_FUTURI.md, ยซProfilo dei dati dell'assetยป).
๐ข Quote Base Suggestion (suggest_quote_base)
The prices of a London line quoted in pence (GBp) are stored in pence as GBP (see Historical Data above), so its
asset needs a quote base (quote_base_quantity, Units per single price) of 100. The plugin suggests it in two
places, both through _quote_base_suggestion(currency):
- Search: from the currency each result already reads, as listed above.
suggest_quote_base(): from the currency offast_info, read through_fetch_currency(identifier)and its 24-hour cache, shared with the search. AGBpline givesFAQuoteBaseSuggestion(quantity=100, quote_currency="GBp"); any other currency, none, an empty identifier or a missing yfinance givesNone. The core asks it in the probe'smetadataoperation only, afterfetch_asset_metadata()has answered, with 5 s of its own (Asset Plugin Guide).
_quote_base_suggestion() reads the factor from minor_unit_factor(), whose list is MINOR_UNIT_FACTORS
(backend/app/utils/currency_units.py): the codes are matched as reported, whitespace stripped, so GBP or gbp
get no suggestion. Only GBp, 100, is listed: ZAC and ILA, the cents of Johannesburg and the agorot of Tel Aviv,
are not ISO 4217 codes, and the schemas refuse them (Currency.validate_code() and iso_currency_code() in
backend/app/schemas/common.py). The portfolio data-quality report reads the same list
(Data Quality Banner).
๐ get_asset_url
Returns https://finance.yahoo.com/quote/{identifier}.
๐ Asset Events
During sync, the provider generates:
DIVIDENDevents fromticker.dividendsโ ex-dividend date + per-share amount.SPLITevents fromticker.splitsโ split date + ratio value (e.g.,4.0for a 4:1 split).
Event acquisition and parsing are best-effort and independent. Events that are returned are
persisted by assets/event_store.py::_upsert_asset_events(), keyed by
provider_assignment_id. They are dated on the exchange's day, as the prices; one an older
version stored a day early stays, beside the one a sync fetches again
(Dates on the Exchange's Own Day).
โก Caching Strategy
| Owner / Cache | Key | TTL | Max Size | Purpose |
|---|---|---|---|---|
| Core current value | Provider code + identifier + identifier type (refresh also includes the provider-parameter hash) | 120 sec | 300 | Avoid repeated ticker.info calls during current-price polling and refresh. |
| Core history | Provider code + identifier + identifier type + provider-parameter hash | 15 min | 500 | Reuse fetched date ranges during provider-driven refresh. |
| Core search query | Provider code + normalized query | 15 min | 500 | Avoid repeating the same provider search. |
| Yahoo currency lookup | symbol |
24 hours | 2000 | Cache the provider's fast_info currency sub-operation used by search() and suggest_quote_base(). Only answers are cached, never a refusal or an error. |
All are in-memory, per-process TTL caches created with get_ttl_cache(). The shared result caches
are owned by assets/core.py; Yahoo owns only its currency sub-operation cache.
No provider-level history cache
Yahoo has no provider-level history cache. The outer refresh layer may reuse its core history
cache and persists fetched prices to the database. get_prices_bulk() is DB-only; it never
calls Yahoo while serving a historical query (see
Architecture โ Price Query).
๐งช Test Configuration
| Property | Value |
|---|---|
test_cases |
[{identifier: "AAPL", identifier_type: TICKER}] |
test_search_query |
"Apple" |
โ ๏ธ Limitations
- Rate limits: Yahoo Finance may refuse for too many requests.
_is_rate_limited()recognises yfinance'sYFRateLimitErrorand, in any error message, ยซ429ยป as a whole word, ยซtoo many requestsยป or ยซrate limitยป;_yf_with_retry()then raisesAssetRateLimitedErrorat once, without retrying in the thread, and search and metadata let it through instead of answering[]orNone. The core pauses the provider (Provider Pauses); yfinance gives noRetry-After, so the pause is the core's own. A false positive costs a pause of about a minute. Other transient errors (timeouts, reset connections,503โฆ) are still retried: at most three attempts, 1.5 s and then 3 s apart. - ISIN resolution: Not all ISINs are resolvable by yfinance (depends on market coverage).
- Data gaps: Some tickers may have missing days or delayed data.
- Rows dated a day early by 1.2.1 or earlier stay as they are: a sync rewrites only the session days it fetches, and an event it fetches again is stored beside the old one (Dates on the Exchange's Own Day).
- No timezone database (Windows outside Docker without the PyPI
tzdatapackage, a minimal container):_exchange_zone()gives None, so the current value is dated in UTC, and an Area/Location name (Europe/Rome) is logged as a warning once per name and process, Exchange timezone unknown to this server's timezone database: the current value is dated in UTC. A fixed offset or a name without an area is not logged. Addingtzdatais Z-36, a developer decision. - Splits rewrite the past (known limitation, MF-SPL1, option C for 1.3). Yahoo's
Closeandticker.dividendsare both expressed in the share count after every later split: AAPL's close of 28 Aug 2020 is 124.81 (the real one was about 499) and its dividend of 7 Aug 2020 is 0.205 (the real one was 0.82), the 4:1 of 31 Aug 2020; NVDA's 2023 dividends are 0.004 (paid 0.04) after the 10:1 of June 2024.auto_adjust=Falsedoes not undo it: the raw frame is split-adjusted too. The engine changes a quantity only with the adjustment linked to theSPLITevent, on the day of the split, and reads the quotation as it is, so a position held before a split is valued at its pre-split quantity times a post-split price (10 ร 124.81 = 1,248 instead of 4,990; the TWRR jumps and a false loss appears), and a dividend event times the pre-split quantity comes out short. Nothing in the plugin can fix it (Yahoo offers no unadjusted close); the correction belongs to the engine, from theSPLITevents, after 1.3 (TODO_FUTURI.md). - Rows saved before Z-35 stay adjusted (developer decision of 23 Oct 2026: no clean-up of saved data). The history is stored as it was read: a row written before the change keeps the dividend adjustment of the day it was fetched, and the scheduler re-reads only the last 14 days. The user who notices re-reads the whole history with the full Sync (the dialog of C-66 warns before it overwrites). The same holds for the dividends of a pence line saved before Z-32, still in pence until that Sync.
๐ฆ Dependency
- Library:
yfinanceโ installed viapipenv install yfinance. - Optional import: If
yfinanceis not installed, current/history/search calls raise anAssetSourceErrorwith error codeNOT_AVAILABLE; metadata refresh degrades toNone. - Transitive:
pandas(required by yfinance).
๐ Related Documentation
- ๐ Yahoo Finance โ User Guide โ End-user configuration guide
- ๐ฆ Providers Overview โ All available providers
- ๐ฐ Asset Architecture โ Sync pipeline and price queries
- ๐ Asset Plugin Guide โ How to create a new provider