Expand description
§finance-query
A Rust library for querying financial data. Inspired by yfinance, with smart lazy loading for efficient data fetching.
§Quick Start
use finance_query::Ticker;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Simple: Create a ticker with default configuration
let ticker = Ticker::new("AAPL").await?;
// First access to any quote property fetches ALL quote modules in one request
if let Some(financials) = ticker.financial_data().await? {
println!("Financial data: {:?}", financials);
}
// Subsequent accesses use cached data (no additional network calls)
if let Some(profile) = ticker.asset_profile().await? {
println!("Company profile: {:?}", profile);
}
// Chart data is fetched separately and cached by interval/range
let chart = ticker.chart(
finance_query::Interval::OneDay,
finance_query::TimeRange::OneMonth
).await?;
println!("Candles: {}", chart.candles.len());
// Builder pattern: Fluent configuration
let ticker_jp = Ticker::builder("7203.T")
.lang("ja-JP")
.region_code("JP")
.timeout(std::time::Duration::from_secs(30))
.build()
.await?;
Ok(())
}§Lazy Loading and Caching
The library fetches on demand and caches by default:
- Quote data: all quote modules fetched together on first property access, then reused
- Chart data: fetched and cached per (interval, range) combination
- Recommendations: fetched once and cached
A handle caches each response for 60 seconds by default. Use .cache(ttl)
on the builder to change that window, or .no_cache() to fetch fresh on
every call.
Re-exports§
pub use domains::CryptoCoin;pub use domains::ForexPair;pub use domains::EconomicCatalog;pub use domains::EconomicIndicator;pub use domains::Commodity;pub use domains::Discovery;pub use domains::Filings;pub use domains::FuturesContract;pub use domains::Index;pub use domains::Snapshot;pub use domains::Market;pub use domains::MarketCalendar;pub use finance::symbol_sentiment;pub use finance::AnalystEstimate;pub use finance::AnalystRecommendation;pub use finance::InsiderTransaction;pub use finance::Period;pub use finance::analyst_estimates;pub use finance::analyst_recommendations;pub use finance::insider_trading;pub use finance::EarningsCalendarEntry;pub use finance::IpoCalendarEntry;pub use finance::earnings_calendar;pub use finance::ipo_calendar;pub use error::ErrorCategory;pub use error::FinanceError;pub use error::Result;pub use finance::LookupOptions;pub use finance::LookupType;pub use finance::SearchOptions;pub use indicators::AroonData;pub use indicators::BollingerBands;pub use indicators::BollingerBandsData;pub use indicators::BullBearPowerData;pub use indicators::CandlePattern;pub use indicators::DonchianChannelsData;pub use indicators::ElderRayData;pub use indicators::IchimokuData;pub use indicators::Indicator;pub use indicators::IndicatorError;pub use indicators::IndicatorResult;pub use indicators::IndicatorsSummary;pub use indicators::KeltnerChannelsData;pub use indicators::MacdData;pub use indicators::MacdResult;pub use indicators::PatternSentiment;pub use indicators::StochasticData;pub use indicators::SuperTrendData;pub use indicators::atr;pub use indicators::patterns;
Modules§
- alphavantage
- Alpha Vantage configuration (requires the
alphavantagefeature). - backtesting
- Backtesting engine for trading strategy simulation.
- cftc
- CFTC Commitments of Traders positioning (requires
cftcfeature, keyless). - crypto
- CoinGecko cryptocurrency data (requires
cryptofeature). - defi
- Market-wide DeFi data via DefiLlama (requires
defifeature, keyless). - domains
- Domain-specific query handles — non-equity asset classes.
- edgar
- SEC EDGAR API client (keyless — always available, no feature flag needed).
- error
- Error types and result definitions.
- feeds
- RSS/Atom news feed aggregation.
- finance
- Non-symbol-specific operations (search, lookup, screeners, market data, etc.). Non-symbol-specific Yahoo Finance operations
- fmp
- Financial Modeling Prep configuration (requires the
fmpfeature). - format
- Compile-time format type parameters for
Quoteand otherFormattedValue-bearing structs. - fred
- FRED economic data API (requires
fredfeature). - gdelt
- GDELT global news search (requires
gdeltfeature, keyless). - indicators
- Technical analysis indicators for financial data.
- openfigi
- Security-identifier resolution via OpenFIGI (requires
openfigifeature, keyless). - polygon
- Massive (formerly Polygon.io) configuration (requires the
polygonfeature). - quote
- Yahoo
quoteSummarymodule types carried byQuoteSummaryResponse. - risk
- Standalone risk analytics.
- streaming
- Real-time price streaming with pluggable provider backends.
- translation
- Offline-friendly translation of human-readable response fields.
Structs§
- Batch
Capital Gains Response - Response containing capital gains for multiple symbols.
- Batch
Charts Response - Response containing charts for multiple symbols.
- Batch
Dividends Response - Response containing dividends for multiple symbols.
- Batch
Financials Response - Response containing financial statements for multiple symbols.
- Batch
Indicators Response - Response containing technical indicators for multiple symbols.
- Batch
News Response - Response containing news articles for multiple symbols.
- Batch
Options Response - Response containing options chains for multiple symbols.
- Batch
Quotes Response - Response containing quotes for multiple symbols.
- Batch
Recommendations Response - Response containing recommendations for multiple symbols.
- Batch
Sparks Response - Response containing spark data for multiple symbols.
- Batch
Splits Response - Response containing splits for multiple symbols.
- Calendar
Event - A single upcoming financial event.
- Candle
- A single OHLCV candle/bar
- Capability
- Capability bits that a provider can declare.
- Capital
Gain - Public capital gain data
- Chart
- Fully typed chart data
- Chart
Events - Chart events containing dividends, splits, and capital gains
- Chart
Meta - Metadata for chart data
- CikEntry
- An entry from the SEC ticker-to-CIK mapping.
- Client
Handle - Opaque handle to a shared Yahoo Finance client session.
- Commitments
OfTraders - Weekly Commitments of Traders positioning for one futures market.
- Commodity
Quote - A commodity price quote (e.g., gold, silver, crude oil).
- Company
Facts - Complete company facts response containing all XBRL financial data.
- Company
Profile - A company’s identity and classification profile.
- Congressional
Trade - One legislator stock-trade disclosure filed under the STOCK Act.
- Contracts
- A collection of option contracts with DataFrame support.
- CotObservation
- One weekly report row, broken down by trader category.
- Crypto
Quote - A provider-agnostic cryptocurrency quote.
- Currency
- A single currency with its properties
- Custom
Id - Index of a custom provider id, obtained from
Provider::custom. - Dividend
- Public dividend data
- Dividend
Analytics - Computed analytics derived from a symbol’s dividend history.
- Earnings
Surprise - One reported earnings result versus the analyst estimate.
- Earnings
Transcript - One earnings call transcript.
- Economic
Category - A node in the provider’s series category tree.
- Economic
Release - A publication that releases economic series on a schedule.
- Economic
Series - A provider-agnostic economic data series with metadata.
- Economic
Series Match - A series matching a catalog search.
- Edgar
Filing - A single SEC filing with metadata.
- Edgar
Filing File - Reference to an additional filing history file for older filings.
- Edgar
Filing Index - Filing index response for a specific EDGAR accession.
- Edgar
Filing Index Item - Single file entry within an EDGAR filing index.
- Edgar
Filing Recent - Recent filings data stored as parallel arrays.
- Edgar
Filings - Container for recent filings and links to older filing history files.
- Edgar
Search Hit - A single search result hit from EDGAR full-text search (Elasticsearch format).
- Edgar
Search Hits Container - Container for search hits with metadata.
- Edgar
Search Results - Full-text search results from SEC EDGAR.
- Edgar
Search Source - Source data for a search hit containing the actual filing information.
- Edgar
Search Total - Total count information for search results.
- Edgar
Submissions - Full submissions response for a company from SEC EDGAR.
- Employee
Count - Employee headcount as reported on one filing.
- EtfCountry
Weighting - One country’s weight inside an ETF’s portfolio.
- EtfHolding
- One position inside an ETF’s portfolio.
- EtfProfile
- Profile and composition of an exchange-traded fund.
- EtfSector
Weighting - One sector’s weight inside an ETF’s portfolio.
- Exchange
- Information about a supported exchange.
- Exchange
Info - A tradable exchange.
- Executive
Compensation - One executive’s reported compensation for one fiscal year.
- Fact
Concept - A single XBRL concept (e.g., “Revenue”) with all reported values.
- Fact
Unit - A single data point for an XBRL fact.
- Facts
ByTaxonomy - Facts within a single taxonomy (e.g., “us-gaap”).
- Fail
ToDeliver - One SEC fails-to-deliver record for a settlement date.
- Fear
AndGreed - The current CNN Fear & Greed Index reading from Alternative.me.
- Filing
Search Filters - Which parts of a full-text search to constrain.
- Filing
Search Hit - One filing matching a full-text search.
- Filing
Section - One section of an SEC filing’s text.
- Financial
Ratios Ttm - Margin, turnover, liquidity, coverage, valuation, and per-share ratios over the trailing twelve months.
- Financial
Statement - A flattened, user-friendly financial statement
- Forex
Quote - A forex currency pair quote (e.g., EUR/USD).
- Formatted
Value - A generic type representing Yahoo Finance’s formatted value pattern
- Futures
Quote - A futures contract quote.
- Grading
Action - A single analyst upgrade/downgrade/initiation action.
- Index
Constituent - A constituent (member) of a major stock market index.
- Index
Constituent Change - A historical change in a major index’s constituency.
- Index
Quote - A stock market index quote (e.g., S&P 500, NASDAQ, Dow Jones).
- Industry
Data - Industry data from Yahoo Finance
- Industry
Pe - An industry’s aggregate price/earnings ratio.
- Insider
Trade - One transaction line from a Form 3, 4, or 5.
- Institutional
Holding - One position from a 13F-HR information table.
- KeyMetrics
Ttm - Valuation, capital-efficiency, and working-capital metrics over the trailing twelve months.
- Lookup
Quote - A quote/document result from symbol lookup
- Lookup
Results - Response wrapper for lookup endpoint
- Market
Calendar Entry - One market-wide calendar entry.
- Market
Hours - Flattened response for market hours
- Market
Snapshot - One symbol’s current market state, flattened across asset classes.
- Market
Summary Quote - A single market summary quote (index, currency, commodity, etc.)
- Market
Time - Market time information for a specific market
- Mover
Quote - A symbol appearing in a market-movers list.
- News
- A news article
- Option
Chain - Options chain data for a specific expiration
- Option
Contract - An options contract (call or put)
- Options
- Response wrapper for options endpoint
- Options
Quote - Quote data included with options response
- Press
Release - A company press release.
- Price
Target Consensus - Consensus analyst price target for a symbol.
- Price
Target Summary - Price-target activity over trailing windows: how many targets were published and their average, per window.
- Provider
Filing - A single SEC filing entry from a provider.
- Provider
Filings - A collection of SEC filings from a provider (e.g., Polygon EDGAR).
- Provider
Health - Snapshot of one provider’s recent health and (where derivable) remaining rate-limit budget.
- Providers
- Central provider configuration shared across query handles.
- Providers
Builder - Builder for
Providers. - Query
Condition - A typed filter condition for a screener query.
- Query
Group - A group of query operands combined with a logical operator.
- Quote
- Flattened quote data with deduplicated fields
- Quote
Summary Response - Response from the quoteSummary endpoint
- Rating
Consensus - Consensus rating rollup — the analyst panel’s grade distribution plus the provider’s headline recommendation.
- Recommendation
- Fully typed recommendation data
- Research
Report - A research report result from search
- Research
Reports - A collection of research reports with DataFrame support.
- Retry
Policy - Retry policy for [
super::ProviderSet] dispatch, opt-in viacrate::Providers::builder().retry(..). - Risk
Factor - A risk factor extracted from SEC filings.
- Routes
- Per-capability provider routing table.
- Screener
Filters - Filters for a provider-routed screener query.
- Screener
Match - A symbol matched by a screener query.
- Screener
Query - A typed custom screener query for Yahoo Finance.
- Screener
Quote - Quote data from a Yahoo Finance screener
- Screener
Results - Flattened, user-friendly response for screener results
- Search
News - A news result from search
- Search
News List - A collection of search news with DataFrame support.
- Search
Quote - A quote result from symbol search
- Search
Quotes - A collection of search quotes with DataFrame support.
- Search
Results - Response wrapper for search endpoint
- Sector
Data - Complete sector data with all available information
- Sector
Pe - A sector’s aggregate price/earnings ratio.
- Sector
Performance - A sector’s aggregate performance.
- Sector
Performance History - One day of aggregate performance across every sector and exchange.
- Sentiment
- Sentiment score for a news article or transcript segment.
- Share
Float - Share float and shares outstanding.
- Short
Interest - A short-interest data point (bi-monthly settlement report).
- Short
Volume - A daily short-volume data point.
- Similar
Symbol - A similar/recommended symbol with score
- Spark
- Sparkline data for a single symbol.
- Spark
Data - Spark chart mini-data for market summary
- Split
- Public stock split data
- Symbol
Details - Detailed reference data for a single symbol.
- Symbol
Match - A symbol matched by a search or listing query.
- Symbol
Sentiment - Per-symbol sentiment from provider news analysis (Polygon, etc.).
- Ticker
- The primary entry point for querying financial data for a single symbol.
- Ticker
Builder - Builder for constructing a
Tickerwith optional configuration. - Tickers
- Multi-symbol ticker for efficient batch operations.
- Tickers
Builder - Builder for Tickers
- Transcript
- Full transcript response from Yahoo Finance.
- Transcript
With Meta - Transcript with metadata from the earnings call list.
- Trending
Quote - A trending stock/symbol quote
Enums§
- Asset
Class - Which market a snapshot row belongs to.
- Calendar
Detail - The event-specific payload of a
MarketCalendarEntry. - Calendar
Kind - Which market-wide calendar to fetch.
- Condition
Value - The value portion of a typed screener condition.
- Equity
Field - Typed field names for equity custom screener queries.
- Event
Kind - The kind of financial event, with its event-specific payload.
- Exchange
Code - Typed exchange code for screener queries.
- Fear
Greed Label - Classification label for the Fear & Greed Index value.
- Fetch
- How providers are queried.
- Filing
Section Form - Which filing form to fetch sectioned text for.
- Frequency
- Frequency for financial data (annual or quarterly)
- Fund
Field - Typed field names for mutual fund custom screener queries.
- Indices
Region - Region categories for world indices
- Industry
- Typed industry identifier for the industry endpoint and custom screener queries.
- Interval
- Chart intervals
- Logical
Operator - Logical operator for combining multiple screener conditions.
- Major
Index - A major stock market index whose constituent lists providers can serve.
- Mover
Direction - Which set of market movers to fetch.
- Operation
- A single provider-adapter operation — finer-grained than
Capability(e.g.Chart,ChartRange, andSparkall fall underCapability::CHART). - Operator
- Comparison operator for screener query conditions.
- Provider
- Typed identifier for a financial data provider.
- Query
Operand - An operand within a query group — either a leaf condition or a nested group.
- Quote
Type - Quote type for custom screener queries.
- Region
- Supported regions for Yahoo Finance regional APIs
- Screener
- Predefined Yahoo Finance screener selector
- Screener
Fund Category - Morningstar fund category for mutual fund screener queries.
- Screener
Peer Group - Equity peer group for screener queries.
- Sector
- Market sector types available on Yahoo Finance
- Sentiment
Label - Directional sentiment classification for a piece of text.
- Sort
Type - Sort direction for screener results.
- Statement
Type - Statement types for financial data
- Time
Range - Time ranges for chart data
- Value
Format - Value format for API responses
Traits§
- Calendar
Provider crate::Capability::CALENDAR— market-wide calendars.- Chart
Provider crate::Capability::CHART— historical OHLCV candles and sparklines.- Commodities
Provider crate::Capability::COMMODITIES— commodity price quotes.- Corporate
Provider crate::Capability::CORPORATE— news, corporate events, similar-symbol recommendations.- Crypto
Provider crate::Capability::CRYPTO— cryptocurrency quotes.- Discovery
Provider crate::Capability::DISCOVERY— symbol search, reference data, exchanges, screeners.- Economic
Provider crate::Capability::ECONOMIC— macro-economic data series.- Filings
Provider crate::Capability::FILINGS— SEC filing data.- Forex
Provider crate::Capability::FOREX— currency-pair quotes.- Fundamentals
Provider crate::Capability::FUNDAMENTALS— financial statements and share-supply data.- Futures
Provider crate::Capability::FUTURES— futures contract quotes.- Indices
Provider crate::Capability::INDICES— stock market index quotes.- Market
Provider crate::Capability::MARKET— sector/industry performance and movers.- Options
Provider crate::Capability::OPTIONS— options chains.- Provider
Adapter - A configured provider as seen by [
crate::ProviderSet] dispatch: lifecycle plus oneas_*accessor per capability. Override an accessor toSome(self)for each capability trait the provider implements. - Provider
Core - Identity shared by every capability trait: the provider id and the
NotSupportederror constructor used by default method bodies. - Quote
Provider crate::Capability::QUOTE— single and batch equity quotes.- Screener
Field - A typed screener field usable in custom query conditions, sorting, and response field selection.
- Screener
Field Ext - Fluent condition-building methods on any
ScreenerFieldtype.
Functions§
- analyze_
sentiment - Score a single piece of text.
Type Aliases§
- Equity
Screener Query - Type alias for equity (stock) screener queries.
- Fund
Screener Query - Type alias for mutual fund screener queries.
Attribute Macros§
- async_
trait - The attribute every capability trait implementation needs.
Derive Macros§
- ToData
Frame - Derive macro for automatic DataFrame conversion.