adaq-data-stock-us
A Rust reimplementation of Python's yfinance
for fetching US (and global) equity market data from Yahoo Finance.
- Async-first, with a fully-featured blocking facade for non-async callers.
- Strongly-typed return values (compile-time guarantees); tabular consumers can
convert history to a
polarsDataFrame(optionalpolarsfeature) or to JSON viaserde(always on). - Chrome TLS impersonation via
primpto avoid Yahoo rate-limiting, with a shared, thread-safe HTTP session (cookie jar, crumb, consent handling, retry/backoff). - Faithful yfinance parity: every method mirrors a yfinance surface (
Ticker.info,Ticker.option_chain,download,screen,Search,Lookup,Calendars,AsyncWebSocket,Auth, …). See Parity.
📖 中文文档 / Chinese docs: README.zh-CN.md
Table of Contents
- Feature Overview
- Requirements
- Installation
- Quick Start
- Configuration
- Usage Guide
- Feature Flags
- Caching
- Error Handling
- Parity with yfinance
- Examples
- Project Layout
- Changelog
- License
Feature Overview
All phases (P1–P4) of the yfinance surface are implemented. Grouped by module:
P1 — HTTP core, history & bulk download
- Typed price
History/Barparsed from thev8/finance/chartendpoint. - Intervals:
1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo. - Period/start/end ranges, pre/post-market bars (
prepost). - Corporate actions: dividends, stock splits, and capital gains (
actions). - Dividend/split price adjustment — auto-adjust (default) or back-adjust.
keepnato retain rows with missing OHLC;repairfor split-continuous price repair.- Concurrent bulk
downloadof many tickers, with lenient (collect-errors) mode.
P2 — Quote, fundamentals, options, analysis
infoblob (flattened common fields + full raw JSON preserved onInfo::raw).fast_infosubset derived from price history (last price, averages, 52-week range…).holders(major / institutional / mutual-fund / insider purchases, transactions, roster).sustainability(ESG scores).analyst_price_targets,recommendation_trend,recommendations,upgrades_downgrades.- Three financial statements (
income/balance-sheet/cash-flow) × annual / quarterly. - Full
option_chain(expirations, strikes, calls & puts). - Estimates tables:
earnings_estimate,revenue_estimate,earnings_history,eps_trend,eps_revisions,growth_estimates,valuation_measures. - Per-ticker
calendar,sec_filings, current & fullshares/shares_full,funds_data. - Per-ticker
news,earnings_dates, reverseisin.
P3 — Domain, search, calendars, screener
domain: sector / industry snapshots and market summaries by region.search(free-text) andlookup(by type: equity / etf / mutualfund / index / …).- Calendars: earnings, IPO, economic, and splits between two dates.
screener: predefined screens (day_gainers,most_actives, …) plus a typed query-builder DSL (EquityQuery/FundQuery/ETFQuery).
P4 — Live streaming & auth
- WebSocket live stream decoding Yahoo's
PricingDataprotobuf feed (15s heartbeat). Auth: inject YahooT/Ylogin cookies and inspect subscription tier / user.
Requirements
| Tool | Version |
|---|---|
| Rust | ≥ 1.85 (the crate uses the 2024 edition) |
| Cargo | ships with the Rust toolchain |
| Network | outbound HTTPS to query1.finance.yahoo.com, query2.finance.yahoo.com, and the streamer |
No system libraries are required — sqlite (rusqlite bundled) and TLS (rustls) are
compiled in. A C compiler is not needed.
Installation
Add the crate to your Cargo.toml. For tabular output also enable the polars feature:
[]
= "0.1"
# optional: DataFrame conversion for History
= { = "0.1", = ["polars"] }
Or with cargo add:
The crate is used as a library. A small runnable demo lives in src/main.rs
(ticker-identifier resolution) and the examples/ directory (see Examples).
Quick Start
Blocking API (no async needed)
use Client;
use ;
Async API
use ;
async
Tip: both APIs expose the same method set. The blocking client internally runs the async call on a shared multi-thread Tokio runtime, so you can pick whichever fits your application.
Configuration
Tune the HTTP session via Config and Client::with_config (or blocking::Client::with_config):
use ;
use PathBuf;
| Field | Default | Description |
|---|---|---|
proxy |
None |
Optional HTTP proxy URL. |
retries |
0 |
Retry count on transient failures. |
timeout_secs |
30 |
Per-request timeout in seconds. |
user_agent |
Chrome UA | User-Agent sent with every request. |
locale |
en / US |
Locale for quoteSummary / visualization requests. |
lenient |
true |
Bulk download swallows per-ticker errors (mirrors yfinance hide_exceptions). |
cache_dir |
temp dir | Directory for the sqlite cache file. |
cookie_t / cookie_y |
None |
Yahoo T / Y login cookies (see Authentication). |
Usage Guide
Price History
use Client;
use ;
- Intervals are the
Intervalenum (Min1…Month3). Intraday intervals (1m/2m/…) are subject to Yahoo's range limits. actions: trueattachesHistory::actions(dividends, splits, capital gains).auto_adjust(default) rescales OHLC and keeps raw close;back_adjustkeeps Adj Close and rescales the rest; set bothfalsefor raw prices.repair: truedrops non-positive OHLC bars and makes the series split-continuous using declared split events (mirrors yfinancerepair=True).
Ticker Identifiers (symbol / MIC pair / ISIN)
A security can be addressed by a bare symbol, a (symbol, MIC) pair, or an ISIN —
mirroring yfinance's Ticker constructor forms.
use Client;
use TickerId;
The (symbol, MIC) pair is resolved through the MIC_TO_YAHOO_SUFFIX map (e.g.
("OR", "XPAR") → "OR.PA"; US exchanges XNYS/XNAS carry no suffix). ISIN→ticker
resolution mirrors utils.get_ticker_by_isin and is cached.
Quote, Fundamentals & Options
use Client;
use ;
Analysis & Estimates
use Client;
NamedTable (returned by the estimate methods) is a labelled matrix with a
index (rows) × columns shape and a get(row, col) lookup, mirroring the
DataFrame shape yfinance returns.
Search, Lookup, Domain & Calendars
use Client;
use MarketRegion;
Screener
Use a predefined screen by name, or build a custom query with the typed DSL.
use Client;
use ;
Available predefined screens include day_gainers, day_losers, most_actives,
aggressive_small_caps, growth_technology_stocks, most_shorted_stocks, and more
(embedded from yfinance 1.6.0).
Per-Ticker News, Earnings Dates & ISIN
use Client;
Live Streaming
use ;
async
For blocking callers, blocking::Client::stream_live(symbols, handler) runs the same
stream to completion on the shared runtime.
Authentication
use Client;
async
Bulk Download
Download history for many tickers concurrently. In lenient mode (the default), a
failing ticker is collected into errors rather than aborting the batch.
use Client;
use ;
Feature Flags
| Flag | Default | Effect |
|---|---|---|
polars |
off | Adds History::to_polars() → polars::prelude::DataFrame for tabular consumers. |
= { = "0.1", = ["polars"] }
let df = hist.to_polars?; // requires the `polars` feature
Caching
A single on-disk sqlite file (adaq-yfinance.db) caches the crumb, per-ticker
timezone, and ISIN→ticker mappings. By default it lives in a temp directory; set a
persistent location with Config::cache_dir:
use ;
use PathBuf;
Error Handling
All fallible calls return adaq_data_stock_us::Result<T> =
Result<T, YfError>. The YfError taxonomy mirrors yfinance's exception hierarchy:
| Variant | Meaning |
|---|---|
Http |
Network/transport failure from the HTTP client. |
Status { status, body } |
Yahoo returned a non-success HTTP status. |
RateLimited |
Yahoo rate-limited the request (HTTP 429). |
Parse |
JSON (de)serialization failure. |
TickerMissing |
The ticker could not be found / resolved. |
InvalidPeriod |
Invalid period / interval / range combination. |
DataMissing |
Expected data was missing from the response. |
NotSupported |
Feature not yet implemented / not supported. |
Cache |
Local sqlite cache failure. |
Io |
Filesystem / IO failure. |
Msg |
Generic message error. |
use Client;
use ;
Parity with yfinance
The crate tracks yfinance 1.6.0 (pinned at vendor/yfinance commit 93eb4c2;
see PARITY_PIN). Per-module status is recorded in docs/PARITY.md,
and the alignment mechanism is documented in docs/adr/0003-parity-mechanism.md.
- Phases P1–P4:
done— HTTP core, history, download, quote, fundamentals, options, analysis, domain, search, lookup, calendars, screener, live, auth. - Price-repair:
partial— split-continuous repair (drop non-positive bars + scale pre-split bars by the split factor) is implemented; the full upstream multi-endpoint reconciliation is not reproduced.
Run the parity drift checker against the vendored submodule:
Examples
Runnable examples live in examples/ (also src/main.rs):
| Example | Covers |
|---|---|
main.rs |
Ticker-identifier resolution (symbol / MIC / ISIN). |
quick |
History + corporate actions via the blocking API. |
smoke |
History, info, fast_info, financials, option chain. |
p3 |
Search, lookup, domain, calendars, screener. |
p4 |
Live WebSocket streaming + authentication. |
ticker_id |
MIC/ISIN resolution + per-ticker news / earnings / reverse ISIN. |
realtime |
Realtime ticker: live-stream price ticks over the Yahoo WebSocket. |
history_by_date |
History by date: fetch a symbol's OHLCV bars for a given date range. |
multi_history |
Concurrent bulk download of several symbols via download. |
fundamentals_demo |
info, fast_info, holders, analyst targets, financial statements. |
news_calendar |
Per-ticker news / earnings dates + the four market calendars. |
Run any of them:
Every example file begins with a //! doc comment describing what it
demonstrates — cargo doc --no-deps renders those, and they double as the
per-example说明 surfaced by cargo run --example.
Project Layout
src/
lib.rs public API surface (re-exports)
client.rs Client + Ticker handle + download (async)
blocking.rs blocking facade over the async Client/Ticker
http.rs YfSession: cookies, crumb, consent, retry
config.rs Config + builder
cache.rs sqlite cache (crumb / tz / isin)
error.rs YfError taxonomy
history.rs History / Bar / HistoryOptions / Interval / actions / repair
quote.rs info, fast_info, holders, analysis, estimates, valuation, calendar, sec_filings, funds, shares
fundamentals.rs income / balance-sheet / cash-flow statements
options.rs option chain
news.rs per-ticker news
earnings.rs per-ticker earnings dates
isin.rs ISIN <-> ticker resolution
mic.rs MIC -> Yahoo suffix map
search.rs free-text search
lookup.rs typed lookup
domain.rs sector / industry / market
calendars.rs earnings / IPO / economic / splits
screener.rs predefined + custom query DSL
live.rs WebSocket live stream (PricingData protobuf)
auth.rs login cookies + subscription tier
docs/
PARITY.md per-module yfinance parity status
adr/ architecture decision records
agents/ agent collaboration docs
vendor/yfinance/ vendored yfinance submodule (pinned)
xtask/ cargo xtask parity drift checker
Changelog
See CHANGELOG.md for the full bilingual (English / 简体中文) release history.
License
Licensed under the Apache License 2.0.