yfinance-rs
Overview
An ergonomic, async-first Rust client for the unofficial Yahoo Finance API. It provides a simple and efficient way to fetch financial data, with a convenient, yfinance-like API, leveraging Rust's type system and async runtime for performance and safety.
Features
Core Data
- Historical Data: Fetch daily, weekly, or monthly OHLCV data with automatic split/dividend adjustments.
- Real-time Quotes: Get live quote updates with detailed market information.
- Fast Quotes: Optimized quote fetching with essential data only (
fast_info). - Multi-Symbol Downloads: Concurrently download historical data for many symbols at once.
- Batch Quotes: Fetch quotes for multiple symbols efficiently.
Corporate Actions & Dividends
- Typed Corporate Actions: Fetch dividends, splits, and capital gains through one currency-aware action stream.
Financial Statements & Fundamentals
- Income Statements: Access annual and quarterly income statements.
- Balance Sheets: Get annual and quarterly balance sheet data.
- Cash Flow Statements: Fetch annual and quarterly cash flow data.
- Earnings Data: Historical earnings, revenue estimates, and EPS data.
- Shares Outstanding: Historical data on shares outstanding (annual and quarterly).
- Corporate Calendar: Earnings dates, ex-dividend dates, and dividend payment dates.
Options & Derivatives
- Options Chains: Fetch expiration dates and full option chains (calls and puts).
- Option Contracts: Detailed option contract information.
Analysis & Research
- Analyst Ratings: Get price targets, recommendations, and upgrade/downgrade history.
- Earnings Trends: Detailed earnings and revenue estimates from analysts.
- Recommendations Summary: Summary of current analyst recommendations.
- Upgrades/Downgrades: History of analyst rating changes.
Ownership & Holders
- Major Holders: Get major, institutional, and mutual fund holder data.
- Institutional Holders: Top institutional shareholders and their holdings.
- Mutual Fund Holders: Mutual fund ownership breakdown.
- Insider Transactions: Recent insider buying and selling activity.
- Insider Roster: Company insiders and their current holdings.
- Net Share Activity: Summary of insider purchase/sale activity.
ESG & Sustainability
- ESG Scores: Fetch Environmental, Social, and Governance ratings when Yahoo returns them.
- ESG Involvement: Specific ESG involvement and controversy data when Yahoo returns it.
News & Information
- Company News: Retrieve the latest articles and press releases for a ticker.
- Company Profiles: Detailed information about companies, ETFs, and funds.
- Search: Find tickers by name or keyword.
Real-time Streaming (WebSocket/Polling)
Streaming is behind the stream feature:
= { = "0.9.1", = ["stream"] }
- WebSocket Streaming: Get live quote updates using WebSockets (preferred method).
- HTTP Polling: Fallback polling method for real-time data.
- Configurable Streaming: Customize update frequency and change-only filtering.
- Cumulative stream volume:
QuoteUpdate.volumereflects Yahoo's latest cumulative session volume when Yahoo sends it.
Advanced Features
- Data Rounding: Control price precision and rounding.
- Malformed Data Handling: Drops invalid OHLC rows while preserving valid sibling data.
- Back Adjustment: Alternative price adjustment methods.
- Historical Metadata: Timezone and other metadata for historical data.
- ISIN Lookup: Get International Securities Identification Numbers.
- Polars DataFrames: Convert results to Polars DataFrames via
.to_dataframe()(enable thedataframefeature).
Developer Experience
- Async API: Built on
tokioandreqwestfor non-blocking I/O. - High-Level
TickerInterface: A convenient, yfinance-like struct for accessing all data for a single symbol. - Builder Pattern: Fluent builders for constructing complex queries.
- Configurable Retries: Automatic retries with exponential backoff for transient network errors.
- Caching: Configurable caching behavior for API responses.
- Custom Timeouts: Configurable request timeouts and connection settings.
Cargo Features
User-facing optional features:
stream: enables WebSocket streaming support.dataframe: re-exportspaftDataFrame conversion traits.tracing: compiles structured tracing instrumentation.
Internal/unstable features:
test-mode: enables repository test hooks, fixture recording, and doc-hidden plumbing APIs for yfinance-rs' own integration tests.debug-dumps: enables maintainer diagnostics for dumping selected raw Yahoo responses.tracing-subscriber: test/example convenience for initializing a basic subscriber; applications should configure their own subscriber instead.
Internal features are published only because Cargo has no private feature namespace. They are not part of the supported user-facing API.
Quick Start
To get started, add yfinance-rs to your Cargo.toml:
[]
= "0.9.1"
= { = "1", = ["full"] }
To enable DataFrame conversions backed by Polars, turn on the optional dataframe feature and (if you use Polars types in your code) add polars:
[]
= { = "0.9.1", = ["dataframe"] }
= "0.53"
Then, create a YfClient and use a Ticker to fetch data.
use ;
async
Troubleshooting
Possible network or consent issues
Some users have reported encountering errors on first use, such as:
Rate limited at ...HTTP error: error sending request for url (https://fc.yahoo.com/consent)
These are typically environmental (network or regional) issues with Yahoo’s public API.
In some regions, Yahoo may require a one-time consent or session initialization.
Workaround:
Open https://fc.yahoo.com/consent in a web browser from the same network before running your code again.
This usually resolves the issue for that IP/network.
Tracing (optional)
This crate can emit structured tracing spans and key events when the optional tracing feature is enabled. When disabled (default), all instrumentation is compiled out with zero overhead. The library does not configure a subscriber; set one up in your application.
Spans are added at: Ticker public APIs (info, quote, history, etc.), HTTP send_with_retry, quote summary fetch (including invalid-crumb retry), and full history fetch. Key events include retry/backoff, optional module failures, stream decode/fallback diagnostics, currency resolution cache updates, and test fixture/debug dump writes.
Advanced Examples
Yahoo Screeners
Use predefined Yahoo screeners or build strongly typed custom equity, ETF, and fund queries.
use ;
async
See the full example: examples/15_screeners.rs.
Polars DataFrames (to_dataframe)
Enable the dataframe feature to convert returned models into a Polars DataFrame with .to_dataframe().
use ;
async
Works for quotes, historical candles, fundamentals, analyst data, holders, options, and more. Returned model structs implement .to_dataframe() when the dataframe feature is enabled. See the full example: examples/14_polars_dataframes.rs.
Multi-Symbol Data Download
use ;
async
For back-adjusted downloads, use .back_adjust() or
.adjustment(DownloadAdjustment::Back).
Real-time Streaming
Enable the stream feature to use this API:
use ;
use Duration;
async
Volume semantics
Yahoo’s websocket stream provides cumulative intraday volume (day_volume), and v7 quote polling provides the same concept as regularMarketVolume. QuoteUpdate::volume exposes the latest cumulative value directly:
- WebSocket stream: maps Yahoo
day_volumetovolume. - Polling stream: maps Yahoo
regularMarketVolumetovolume. - No per-symbol volume state is kept inside the stream.
diff_only(true)filters on price changes; volume-only changes do not emit a new polling update.
If you need deltas, day-boundary handling, or provider-adjustment detection, derive those from successive cumulative values in application code.
Financial Statements
use ;
async
ticker.shares() and ticker.quarterly_shares() use Yahoo's rolling 548-day
share-count window, matching Python yfinance's get_shares_full(start=None, end=None) default. Use shares_between(start, end) or
quarterly_shares_between(start, end) when you need older points.
💡 Need to force a specific reporting currency? Import
CurrencyandIsoCurrencyfromyfinance_rs, then passSome(Currency::Iso(IsoCurrency::USD))(or another currency) instead ofNonewhen calling the fundamentals/analysis helpers.
Options Trading
use ;
async
Advanced Analysis
use ;
async
Holder Information
use ;
async
ESG Scores & Involvement
Yahoo currently returns empty ESG responses for common symbols. Ticker::sustainability() mirrors
Python yfinance for that provider response by returning an empty summary instead of treating it as
a hard failure.
use Display;
use ;
async
Advanced Client Configuration
use ;
use Duration;
async
Custom Reqwest Client
For full control over HTTP configuration, you can provide your own reqwest client:
YfClient handles Yahoo auth cookies internally, so the custom client does not
need cookie_store(true) unless your own reqwest usage requires it.
use ;
use Client;
use Duration;
async
Proxy Configuration
You can configure general or scheme-specific proxies through fallible builder methods:
use ;
use Duration;
async
License
This project is licensed under the MIT License - see the LICENSE file for details.
Contributing
Please see our Contributing Guide and our Code of Conduct. We welcome pull requests and issues.
Changelog
See CHANGELOG.md for release notes and breaking changes.