Expand description
§yfinance-rs
An ergonomic, async-first Rust client for the unofficial Yahoo Finance API.
This crate provides a simple and efficient way to fetch financial data from Yahoo Finance.
It is designed to feel familiar to users of the popular Python yfinance library, but
leverages Rust’s powerful type system and async capabilities 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 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.
§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.
§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-exportspaftDataFrameconversion 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:
[dependencies]
yfinance-rs = "0.9.1"
tokio = { version = "1", features = ["full"] }Then, create a YfClient and use a Ticker to fetch data.
use yfinance_rs::{Interval, Range, Ticker, YfClient};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = YfClient::default();
let ticker = Ticker::new(&client, "AAPL");
// Get the latest quote
let quote = ticker.quote().await?;
if let Some(price) = quote.price.as_ref() {
println!("Latest price for AAPL: {price}");
}
// Get historical data for the last 6 months
let history = ticker.history(Some(Range::M6), Some(Interval::D1), false).await?;
if let Some(last_bar) = history.last() {
println!("Last closing price: {} on timestamp {}", last_bar.ohlc.close, last_bar.ts);
}
// Get analyst recommendations
let recs = ticker.recommendations().await?;
if let Some(latest_rec) = recs.first() {
println!("Latest recommendation period: {}", latest_rec.period);
}
Ok(())
}Re-exports§
pub use core::Backoff;pub use core::CacheEndpoint;pub use core::CacheMode;pub use core::DataQuality;pub use core::HistoryRequest;pub use core::HistoryService;pub use core::ProjectionIssue;pub use core::RetryConfig;pub use core::YfClient;pub use core::YfClientBuilder;pub use core::YfCurrencyInference;pub use core::YfCurrencyPurpose;pub use core::YfDiagnostics;pub use core::YfError;pub use core::YfResponse;pub use core::YfWarning;pub use analysis::AnalysisBuilder;pub use download::DownloadAdjustment;pub use download::DownloadBuilder;pub use download::DownloadConcurrency;pub use esg::EsgBuilder;pub use fundamentals::FundamentalsBuilder;pub use history::HistoryBuilder;pub use holders::HoldersBuilder;pub use news::NewsBuilder;pub use news::NewsTab;pub use quote::QuotesBuilder;pub use quote::quotes;pub use quote::quotes_with_diagnostics;pub use screener::EquityQuery;pub use screener::EquitySector;pub use screener::EtfCategory;pub use screener::EtfQuery;pub use screener::FundCategory;pub use screener::FundQuery;pub use screener::PercentPoints;pub use screener::PredefinedScreener;pub use screener::Rating;pub use screener::Region;pub use screener::ResultOffset;pub use screener::ScreenerBuilder;pub use screener::ScreenerCount;pub use screener::ScreenerNumber;pub use screener::ScreenerQuery;pub use screener::ScreenerResponse;pub use screener::ScreenerResult;pub use screener::SortDirection;pub use screener::YahooExchangeCode;pub use screener::YahooQuoteType;pub use screener::equity_fields;pub use screener::etf_fields;pub use screener::fund_fields;pub use screener::screen;pub use screener::screen_with_diagnostics;pub use search::SearchBuilder;pub use search::search;pub use stream::StreamBuilder;pub use stream::StreamConfig;pub use stream::StreamHandle;pub use stream::StreamMethod;pub use ticker::FastInfo;pub use ticker::Info;pub use ticker::MovingAverages;pub use ticker::Ticker;
Modules§
- analysis
- Fetch analyst ratings, price targets, and upgrade/downgrade history.
- core
- Core components, including the
YfClientandYfError. Core components of theyfinance-rsclient. - dataframe
DataFrameconversion traits re-exported frompaft.- download
- Download historical data for multiple symbols concurrently.
- esg
- Fetch ESG (Environmental, Social, Governance) scores and involvement data.
- fundamentals
- Fetch financial statements (income, balance sheet, cash flow) and earnings data.
- history
- Fetch historical OHLCV data for a single symbol.
- holders
- Fetch holder information, including major, institutional, and insider holders.
- news
- Fetch news articles for a ticker.
- profile
- Retrieve company or fund profile information. Public profile types + loading strategy.
- quote
- Fetch quotes for multiple symbols.
- screener
- Run Yahoo Finance predefined and custom screeners. Yahoo Finance screener support.
- search
- Search for tickers by name or keyword.
- stream
- Stream real-time quote updates via
WebSocketsor polling. - ticker
- A high-level interface for a single ticker, providing access to all data types.
Structs§
- Address
- Postal address details.
- Balance
Sheet Row - Balance sheet row.
- Calendar
- Corporate calendar entries (earnings/dividends).
- Cashflow
Row - Cashflow statement row.
- Company
- Company profile details (provider-agnostic; maps well to common models).
- Corporate
Action Adjustment Causes - Non-empty set of corporate-action classes included in an adjusted price.
- Decimal
Decimalrepresents a 128 bit representation of a fixed-precision decimal number. The finite set of values of typeDecimalare of the form m / 10e, where m is an integer such that -296 < m < 296, and e is an integer between 0 and 28 inclusive.- Earnings
- Earnings datasets: yearly summaries and quarterly breakdowns.
- Earnings
Quarter - Quarterly earnings summary for a period key (e.g., 2023Q4 or 2023-10-01).
- Earnings
Quarter Eps - Quarterly EPS actual vs estimate for a period key.
- Earnings
Trend Row - Represents a single row of earnings trend data for a specific period.
- Earnings
Year - Yearly earnings summary.
- EsgInvolvement
- ESG involvement details for controversial activities or sectors.
- EsgScores
- ESG scores summary.
- EsgSummary
- ESG summary including scores and involvement details.
- Fund
- Fund profile details.
- History
Meta - Optional metadata describing the history series.
- Income
Statement Row - Income statement row.
- Insider
Roster Holder - Represents a single insider on the company’s roster.
- Insider
Transaction - Represents a single insider transaction.
- Institutional
Holder - Represents a single institutional or mutual fund holder.
- Instrument
- Logical instrument identity for a security.
- Isin
- Opaque wrapper for validated ISIN values.
- KeyStatistics
- Slow-moving valuation, dividend, and risk metrics for an instrument.
- Major
Holder - Summary percentages for major holder categories.
- Monetary
Amount - Full-precision currency-denominated amount for totals and intermediate values.
- Money
- Represents a financial value with its currency, enforcing safe operations.
- NetShare
Purchase Activity - A summary of net share purchase activity by insiders over a specific period.
- NonNegative
Decimal - Decimal constrained to
x >= 0. - Ohlc
- Open, high, low, and close price amounts for one denominated bar.
- Option
Contract Key - Identity of an option contract.
- Option
Greeks - Primary first-order greeks for an option contract.
- Period
Year - Valid year component for structured financial periods.
- Price
- Full-precision currency price for per-unit quoted values.
- Price
Amount - Full-precision price amount whose currency is supplied by surrounding context.
- Price
Target - Analyst price target summary.
- Quantity
Amount - Full-precision non-negative quantity whose unit is supplied by surrounding context.
- Ratio
- Decimal constrained to
0 <= x <= 1. - Recommendation
Row - Distribution of analyst recommendations for a period.
- Recommendation
Summary - Summary of analyst recommendations and mean scoring.
- Share
Count - Represents a single data point in a time series of shares outstanding.
- Symbol
- Opaque wrapper for validated symbol strings used by markets and data providers.
- Upgrade
Downgrade Row - Broker action history for an instrument.
Enums§
- Action
- Corporate action attached to a history series.
- Adjustment
Anchor - Anchor basis used by adjusted prices.
- Adjustment
Method - Method used to adjust prices across discontinuities.
- Asset
Kind - Kinds of financial instruments.
- Corporate
Action Adjustment Cause - Corporate-action class included in an adjusted price.
- Currency
- Currency enumeration with major currencies and extensible fallback.
- Exchange
- Exchange enumeration with major exchanges and extensible fallback.
- Fund
Kind - Fund types with canonical variants and extensible fallback.
- Insider
Position - Insider positions in a company with canonical variants and extensible fallback.
- Interval
- Supported resolution intervals.
- IsoCurrency
- Market
State - Market state enumeration.
- Ohlc
Price Basis - Price basis of the primary OHLC fields in a history response.
- Option
Side - Whether an option contract gives the right to buy or sell the underlying.
- Price
Basis - Basis of a returned price value.
- Profile
- Union of supported profile kinds.
- Range
- Logical lookback range presets.
- Recommendation
Action - Analyst recommendation actions with canonical variants and extensible fallback.
- Recommendation
Grade - Analyst recommendation grades with canonical variants and extensible fallback.
- Reporting
Period - Reporting or fiscal period label with structured variants and extensible fallback.
- Transaction
Type - Transaction types for insider activities with canonical variants and extensible fallback.
Traits§
- Columnar
- Columnar batch trait implemented by the derive macro.
- Decimal128
Encode - Encodes a decimal value into the i128 mantissa expected by polars
DataType::Decimal(_, _)columns. - ToData
Frame - ToData
Frame Vec - Extension trait enabling
.to_dataframe()on slices (andVecvia auto-deref)
Type Aliases§
- Book
Level - Standard
BookLevelwith no extra provider metadata. - Candle
- Standard
Candlewith no extra provider metadata. - Download
Entry - Standard
DownloadEntrywith no extra provider metadata. - Download
Response - Standard
DownloadResponsewith no extra provider metadata. - History
Response - Standard
HistoryResponsewith no extra provider metadata. - News
Article - Standard
NewsArticlewith no extra provider metadata. - Option
Chain - Standard
OptionChainwith no extra provider metadata. - Option
Contract - Standard
OptionContractwith no extra provider metadata. - Quote
- Standard
Quotewith no extra provider metadata. - Quote
Update - Standard
QuoteUpdatewith no extra provider metadata. - Search
Response - Standard
SearchResponsewith no extra provider metadata. - Search
Result - Standard
SearchResultwith no extra provider metadata. - Snapshot
- Standard
Snapshotwith no extra provider metadata.