Skip to main content

Crate yfinance_rs

Crate yfinance_rs 

Source
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 tokio and reqwest for non-blocking I/O.
  • High-Level Ticker Interface: 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-exports paft DataFrame 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:

[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 YfClient and YfError. Core components of the yfinance-rs client.
dataframe
DataFrame conversion traits re-exported from paft.
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 WebSockets or polling.
ticker
A high-level interface for a single ticker, providing access to all data types.

Structs§

Address
Postal address details.
BalanceSheetRow
Balance sheet row.
Calendar
Corporate calendar entries (earnings/dividends).
CashflowRow
Cashflow statement row.
Company
Company profile details (provider-agnostic; maps well to common models).
CorporateActionAdjustmentCauses
Non-empty set of corporate-action classes included in an adjusted price.
Decimal
Decimal represents a 128 bit representation of a fixed-precision decimal number. The finite set of values of type Decimal are 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.
EarningsQuarter
Quarterly earnings summary for a period key (e.g., 2023Q4 or 2023-10-01).
EarningsQuarterEps
Quarterly EPS actual vs estimate for a period key.
EarningsTrendRow
Represents a single row of earnings trend data for a specific period.
EarningsYear
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.
HistoryMeta
Optional metadata describing the history series.
IncomeStatementRow
Income statement row.
InsiderRosterHolder
Represents a single insider on the company’s roster.
InsiderTransaction
Represents a single insider transaction.
InstitutionalHolder
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.
MajorHolder
Summary percentages for major holder categories.
MonetaryAmount
Full-precision currency-denominated amount for totals and intermediate values.
Money
Represents a financial value with its currency, enforcing safe operations.
NetSharePurchaseActivity
A summary of net share purchase activity by insiders over a specific period.
NonNegativeDecimal
Decimal constrained to x >= 0.
Ohlc
Open, high, low, and close price amounts for one denominated bar.
OptionContractKey
Identity of an option contract.
OptionGreeks
Primary first-order greeks for an option contract.
PeriodYear
Valid year component for structured financial periods.
Price
Full-precision currency price for per-unit quoted values.
PriceAmount
Full-precision price amount whose currency is supplied by surrounding context.
PriceTarget
Analyst price target summary.
QuantityAmount
Full-precision non-negative quantity whose unit is supplied by surrounding context.
Ratio
Decimal constrained to 0 <= x <= 1.
RecommendationRow
Distribution of analyst recommendations for a period.
RecommendationSummary
Summary of analyst recommendations and mean scoring.
ShareCount
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.
UpgradeDowngradeRow
Broker action history for an instrument.

Enums§

Action
Corporate action attached to a history series.
AdjustmentAnchor
Anchor basis used by adjusted prices.
AdjustmentMethod
Method used to adjust prices across discontinuities.
AssetKind
Kinds of financial instruments.
CorporateActionAdjustmentCause
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.
FundKind
Fund types with canonical variants and extensible fallback.
InsiderPosition
Insider positions in a company with canonical variants and extensible fallback.
Interval
Supported resolution intervals.
IsoCurrency
MarketState
Market state enumeration.
OhlcPriceBasis
Price basis of the primary OHLC fields in a history response.
OptionSide
Whether an option contract gives the right to buy or sell the underlying.
PriceBasis
Basis of a returned price value.
Profile
Union of supported profile kinds.
Range
Logical lookback range presets.
RecommendationAction
Analyst recommendation actions with canonical variants and extensible fallback.
RecommendationGrade
Analyst recommendation grades with canonical variants and extensible fallback.
ReportingPeriod
Reporting or fiscal period label with structured variants and extensible fallback.
TransactionType
Transaction types for insider activities with canonical variants and extensible fallback.

Traits§

Columnar
Columnar batch trait implemented by the derive macro.
Decimal128Encode
Encodes a decimal value into the i128 mantissa expected by polars DataType::Decimal(_, _) columns.
ToDataFrame
ToDataFrameVec
Extension trait enabling .to_dataframe() on slices (and Vec via auto-deref)

Type Aliases§

BookLevel
Standard BookLevel with no extra provider metadata.
Candle
Standard Candle with no extra provider metadata.
DownloadEntry
Standard DownloadEntry with no extra provider metadata.
DownloadResponse
Standard DownloadResponse with no extra provider metadata.
HistoryResponse
Standard HistoryResponse with no extra provider metadata.
NewsArticle
Standard NewsArticle with no extra provider metadata.
OptionChain
Standard OptionChain with no extra provider metadata.
OptionContract
Standard OptionContract with no extra provider metadata.
Quote
Standard Quote with no extra provider metadata.
QuoteUpdate
Standard QuoteUpdate with no extra provider metadata.
SearchResponse
Standard SearchResponse with no extra provider metadata.
SearchResult
Standard SearchResult with no extra provider metadata.
Snapshot
Standard Snapshot with no extra provider metadata.