Skip to main content

Crate finance_query

Crate finance_query 

Source
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 alphavantage feature).
backtesting
Backtesting engine for trading strategy simulation.
cftc
CFTC Commitments of Traders positioning (requires cftc feature, keyless).
crypto
CoinGecko cryptocurrency data (requires crypto feature).
defi
Market-wide DeFi data via DefiLlama (requires defi feature, 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 fmp feature).
format
Compile-time format type parameters for Quote and other FormattedValue-bearing structs.
fred
FRED economic data API (requires fred feature).
gdelt
GDELT global news search (requires gdelt feature, keyless).
indicators
Technical analysis indicators for financial data.
openfigi
Security-identifier resolution via OpenFIGI (requires openfigi feature, keyless).
polygon
Massive (formerly Polygon.io) configuration (requires the polygon feature).
quote
Yahoo quoteSummary module types carried by QuoteSummaryResponse.
risk
Standalone risk analytics.
streaming
Real-time price streaming with pluggable provider backends.
translation
Offline-friendly translation of human-readable response fields.

Structs§

BatchCapitalGainsResponse
Response containing capital gains for multiple symbols.
BatchChartsResponse
Response containing charts for multiple symbols.
BatchDividendsResponse
Response containing dividends for multiple symbols.
BatchFinancialsResponse
Response containing financial statements for multiple symbols.
BatchIndicatorsResponse
Response containing technical indicators for multiple symbols.
BatchNewsResponse
Response containing news articles for multiple symbols.
BatchOptionsResponse
Response containing options chains for multiple symbols.
BatchQuotesResponse
Response containing quotes for multiple symbols.
BatchRecommendationsResponse
Response containing recommendations for multiple symbols.
BatchSparksResponse
Response containing spark data for multiple symbols.
BatchSplitsResponse
Response containing splits for multiple symbols.
CalendarEvent
A single upcoming financial event.
Candle
A single OHLCV candle/bar
Capability
Capability bits that a provider can declare.
CapitalGain
Public capital gain data
Chart
Fully typed chart data
ChartEvents
Chart events containing dividends, splits, and capital gains
ChartMeta
Metadata for chart data
CikEntry
An entry from the SEC ticker-to-CIK mapping.
ClientHandle
Opaque handle to a shared Yahoo Finance client session.
CommitmentsOfTraders
Weekly Commitments of Traders positioning for one futures market.
CommodityQuote
A commodity price quote (e.g., gold, silver, crude oil).
CompanyFacts
Complete company facts response containing all XBRL financial data.
CompanyProfile
A company’s identity and classification profile.
CongressionalTrade
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.
CryptoQuote
A provider-agnostic cryptocurrency quote.
Currency
A single currency with its properties
CustomId
Index of a custom provider id, obtained from Provider::custom.
Dividend
Public dividend data
DividendAnalytics
Computed analytics derived from a symbol’s dividend history.
EarningsSurprise
One reported earnings result versus the analyst estimate.
EarningsTranscript
One earnings call transcript.
EconomicCategory
A node in the provider’s series category tree.
EconomicRelease
A publication that releases economic series on a schedule.
EconomicSeries
A provider-agnostic economic data series with metadata.
EconomicSeriesMatch
A series matching a catalog search.
EdgarFiling
A single SEC filing with metadata.
EdgarFilingFile
Reference to an additional filing history file for older filings.
EdgarFilingIndex
Filing index response for a specific EDGAR accession.
EdgarFilingIndexItem
Single file entry within an EDGAR filing index.
EdgarFilingRecent
Recent filings data stored as parallel arrays.
EdgarFilings
Container for recent filings and links to older filing history files.
EdgarSearchHit
A single search result hit from EDGAR full-text search (Elasticsearch format).
EdgarSearchHitsContainer
Container for search hits with metadata.
EdgarSearchResults
Full-text search results from SEC EDGAR.
EdgarSearchSource
Source data for a search hit containing the actual filing information.
EdgarSearchTotal
Total count information for search results.
EdgarSubmissions
Full submissions response for a company from SEC EDGAR.
EmployeeCount
Employee headcount as reported on one filing.
EtfCountryWeighting
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.
EtfSectorWeighting
One sector’s weight inside an ETF’s portfolio.
Exchange
Information about a supported exchange.
ExchangeInfo
A tradable exchange.
ExecutiveCompensation
One executive’s reported compensation for one fiscal year.
FactConcept
A single XBRL concept (e.g., “Revenue”) with all reported values.
FactUnit
A single data point for an XBRL fact.
FactsByTaxonomy
Facts within a single taxonomy (e.g., “us-gaap”).
FailToDeliver
One SEC fails-to-deliver record for a settlement date.
FearAndGreed
The current CNN Fear & Greed Index reading from Alternative.me.
FilingSearchFilters
Which parts of a full-text search to constrain.
FilingSearchHit
One filing matching a full-text search.
FilingSection
One section of an SEC filing’s text.
FinancialRatiosTtm
Margin, turnover, liquidity, coverage, valuation, and per-share ratios over the trailing twelve months.
FinancialStatement
A flattened, user-friendly financial statement
ForexQuote
A forex currency pair quote (e.g., EUR/USD).
FormattedValue
A generic type representing Yahoo Finance’s formatted value pattern
FuturesQuote
A futures contract quote.
GradingAction
A single analyst upgrade/downgrade/initiation action.
IndexConstituent
A constituent (member) of a major stock market index.
IndexConstituentChange
A historical change in a major index’s constituency.
IndexQuote
A stock market index quote (e.g., S&P 500, NASDAQ, Dow Jones).
IndustryData
Industry data from Yahoo Finance
IndustryPe
An industry’s aggregate price/earnings ratio.
InsiderTrade
One transaction line from a Form 3, 4, or 5.
InstitutionalHolding
One position from a 13F-HR information table.
KeyMetricsTtm
Valuation, capital-efficiency, and working-capital metrics over the trailing twelve months.
LookupQuote
A quote/document result from symbol lookup
LookupResults
Response wrapper for lookup endpoint
MarketCalendarEntry
One market-wide calendar entry.
MarketHours
Flattened response for market hours
MarketSnapshot
One symbol’s current market state, flattened across asset classes.
MarketSummaryQuote
A single market summary quote (index, currency, commodity, etc.)
MarketTime
Market time information for a specific market
MoverQuote
A symbol appearing in a market-movers list.
News
A news article
OptionChain
Options chain data for a specific expiration
OptionContract
An options contract (call or put)
Options
Response wrapper for options endpoint
OptionsQuote
Quote data included with options response
PressRelease
A company press release.
PriceTargetConsensus
Consensus analyst price target for a symbol.
PriceTargetSummary
Price-target activity over trailing windows: how many targets were published and their average, per window.
ProviderFiling
A single SEC filing entry from a provider.
ProviderFilings
A collection of SEC filings from a provider (e.g., Polygon EDGAR).
ProviderHealth
Snapshot of one provider’s recent health and (where derivable) remaining rate-limit budget.
Providers
Central provider configuration shared across query handles.
ProvidersBuilder
Builder for Providers.
QueryCondition
A typed filter condition for a screener query.
QueryGroup
A group of query operands combined with a logical operator.
Quote
Flattened quote data with deduplicated fields
QuoteSummaryResponse
Response from the quoteSummary endpoint
RatingConsensus
Consensus rating rollup — the analyst panel’s grade distribution plus the provider’s headline recommendation.
Recommendation
Fully typed recommendation data
ResearchReport
A research report result from search
ResearchReports
A collection of research reports with DataFrame support.
RetryPolicy
Retry policy for [super::ProviderSet] dispatch, opt-in via crate::Providers::builder().retry(..).
RiskFactor
A risk factor extracted from SEC filings.
Routes
Per-capability provider routing table.
ScreenerFilters
Filters for a provider-routed screener query.
ScreenerMatch
A symbol matched by a screener query.
ScreenerQuery
A typed custom screener query for Yahoo Finance.
ScreenerQuote
Quote data from a Yahoo Finance screener
ScreenerResults
Flattened, user-friendly response for screener results
SearchNews
A news result from search
SearchNewsList
A collection of search news with DataFrame support.
SearchQuote
A quote result from symbol search
SearchQuotes
A collection of search quotes with DataFrame support.
SearchResults
Response wrapper for search endpoint
SectorData
Complete sector data with all available information
SectorPe
A sector’s aggregate price/earnings ratio.
SectorPerformance
A sector’s aggregate performance.
SectorPerformanceHistory
One day of aggregate performance across every sector and exchange.
Sentiment
Sentiment score for a news article or transcript segment.
ShareFloat
Share float and shares outstanding.
ShortInterest
A short-interest data point (bi-monthly settlement report).
ShortVolume
A daily short-volume data point.
SimilarSymbol
A similar/recommended symbol with score
Spark
Sparkline data for a single symbol.
SparkData
Spark chart mini-data for market summary
Split
Public stock split data
SymbolDetails
Detailed reference data for a single symbol.
SymbolMatch
A symbol matched by a search or listing query.
SymbolSentiment
Per-symbol sentiment from provider news analysis (Polygon, etc.).
Ticker
The primary entry point for querying financial data for a single symbol.
TickerBuilder
Builder for constructing a Ticker with optional configuration.
Tickers
Multi-symbol ticker for efficient batch operations.
TickersBuilder
Builder for Tickers
Transcript
Full transcript response from Yahoo Finance.
TranscriptWithMeta
Transcript with metadata from the earnings call list.
TrendingQuote
A trending stock/symbol quote

Enums§

AssetClass
Which market a snapshot row belongs to.
CalendarDetail
The event-specific payload of a MarketCalendarEntry.
CalendarKind
Which market-wide calendar to fetch.
ConditionValue
The value portion of a typed screener condition.
EquityField
Typed field names for equity custom screener queries.
EventKind
The kind of financial event, with its event-specific payload.
ExchangeCode
Typed exchange code for screener queries.
FearGreedLabel
Classification label for the Fear & Greed Index value.
Fetch
How providers are queried.
FilingSectionForm
Which filing form to fetch sectioned text for.
Frequency
Frequency for financial data (annual or quarterly)
FundField
Typed field names for mutual fund custom screener queries.
IndicesRegion
Region categories for world indices
Industry
Typed industry identifier for the industry endpoint and custom screener queries.
Interval
Chart intervals
LogicalOperator
Logical operator for combining multiple screener conditions.
MajorIndex
A major stock market index whose constituent lists providers can serve.
MoverDirection
Which set of market movers to fetch.
Operation
A single provider-adapter operation — finer-grained than Capability (e.g. Chart, ChartRange, and Spark all fall under Capability::CHART).
Operator
Comparison operator for screener query conditions.
Provider
Typed identifier for a financial data provider.
QueryOperand
An operand within a query group — either a leaf condition or a nested group.
QuoteType
Quote type for custom screener queries.
Region
Supported regions for Yahoo Finance regional APIs
Screener
Predefined Yahoo Finance screener selector
ScreenerFundCategory
Morningstar fund category for mutual fund screener queries.
ScreenerPeerGroup
Equity peer group for screener queries.
Sector
Market sector types available on Yahoo Finance
SentimentLabel
Directional sentiment classification for a piece of text.
SortType
Sort direction for screener results.
StatementType
Statement types for financial data
TimeRange
Time ranges for chart data
ValueFormat
Value format for API responses

Traits§

CalendarProvider
crate::Capability::CALENDAR — market-wide calendars.
ChartProvider
crate::Capability::CHART — historical OHLCV candles and sparklines.
CommoditiesProvider
crate::Capability::COMMODITIES — commodity price quotes.
CorporateProvider
crate::Capability::CORPORATE — news, corporate events, similar-symbol recommendations.
CryptoProvider
crate::Capability::CRYPTO — cryptocurrency quotes.
DiscoveryProvider
crate::Capability::DISCOVERY — symbol search, reference data, exchanges, screeners.
EconomicProvider
crate::Capability::ECONOMIC — macro-economic data series.
FilingsProvider
crate::Capability::FILINGS — SEC filing data.
ForexProvider
crate::Capability::FOREX — currency-pair quotes.
FundamentalsProvider
crate::Capability::FUNDAMENTALS — financial statements and share-supply data.
FuturesProvider
crate::Capability::FUTURES — futures contract quotes.
IndicesProvider
crate::Capability::INDICES — stock market index quotes.
MarketProvider
crate::Capability::MARKET — sector/industry performance and movers.
OptionsProvider
crate::Capability::OPTIONS — options chains.
ProviderAdapter
A configured provider as seen by [crate::ProviderSet] dispatch: lifecycle plus one as_* accessor per capability. Override an accessor to Some(self) for each capability trait the provider implements.
ProviderCore
Identity shared by every capability trait: the provider id and the NotSupported error constructor used by default method bodies.
QuoteProvider
crate::Capability::QUOTE — single and batch equity quotes.
ScreenerField
A typed screener field usable in custom query conditions, sorting, and response field selection.
ScreenerFieldExt
Fluent condition-building methods on any ScreenerField type.

Functions§

analyze_sentiment
Score a single piece of text.

Type Aliases§

EquityScreenerQuery
Type alias for equity (stock) screener queries.
FundScreenerQuery
Type alias for mutual fund screener queries.

Attribute Macros§

async_trait
The attribute every capability trait implementation needs.

Derive Macros§

ToDataFrame
Derive macro for automatic DataFrame conversion.