Skip to main content

finance_query/
lib.rs

1//! # finance-query
2//!
3//! A Rust library for querying financial data.
4//! Inspired by yfinance, with smart lazy loading for efficient data fetching.
5//!
6//! ## Quick Start
7//!
8//! ```no_run
9//! use finance_query::Ticker;
10//!
11//! #[tokio::main]
12//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
13//!     // Simple: Create a ticker with default configuration
14//!     let ticker = Ticker::new("AAPL").await?;
15//!
16//!     // First access to any quote property fetches ALL quote modules in one request
17//!     if let Some(financials) = ticker.financial_data().await? {
18//!         println!("Financial data: {:?}", financials);
19//!     }
20//!
21//!     // Subsequent accesses use cached data (no additional network calls)
22//!     if let Some(profile) = ticker.asset_profile().await? {
23//!         println!("Company profile: {:?}", profile);
24//!     }
25//!
26//!     // Chart data is fetched separately and cached by interval/range
27//!     let chart = ticker.chart(
28//!         finance_query::Interval::OneDay,
29//!         finance_query::TimeRange::OneMonth
30//!     ).await?;
31//!     println!("Candles: {}", chart.candles.len());
32//!
33//!     // Builder pattern: Fluent configuration
34//!     let ticker_jp = Ticker::builder("7203.T")
35//!         .lang("ja-JP")
36//!         .region_code("JP")
37//!         .timeout(std::time::Duration::from_secs(30))
38//!         .build()
39//!         .await?;
40//!
41//!     Ok(())
42//! }
43//! ```
44//!
45//! ## Lazy Loading
46//!
47//! The library uses lazy loading:
48//! - **Quote data**: All ~30 quote modules fetched together on first property access
49//! - **Chart data**: Fetched per (interval, range) combination and cached
50//! - **Recommendations**: Fetched once and cached
51//!
52//! This approach minimizes network requests while keeping memory usage efficient.
53
54#![warn(missing_docs)]
55#![warn(rustdoc::missing_crate_level_docs)]
56
57// === Modules ===
58// Public modules
59/// External data source adapters (internal — use the public API modules).
60pub(crate) mod adapters;
61/// Error types and result definitions.
62pub mod error;
63/// Non-symbol-specific operations (search, lookup, screeners, market data, etc.).
64pub mod finance;
65pub mod edgar {
66    //! SEC EDGAR API client (keyless — always available, no feature flag needed).
67    //!
68    //!
69    //! Requires a one-time [`init`] call with a contact email address.
70    pub use crate::adapters::edgar::{
71        company_facts, filing_index, init, init_with_config, resolve_cik, search, submissions,
72    };
73}
74
75// Internal modules
76mod constants;
77mod models;
78mod providers;
79pub(crate) mod rate_limiter;
80mod scrapers;
81mod ticker;
82mod tickers;
83mod utils;
84
85// Feature-gated external data source modules
86#[cfg(feature = "fred")]
87pub mod fred {
88    //! FRED economic data API (requires `fred` feature).
89    //!
90    //! Access 800k+ macroeconomic time series and US Treasury yield curve data.
91    pub use crate::adapters::fred::{init, init_with_timeout, series, treasury_yields};
92    pub use crate::models::economic::{MacroObservation, MacroSeries, TreasuryYield};
93}
94
95#[cfg(feature = "crypto")]
96pub mod crypto {
97    //! CoinGecko cryptocurrency data (requires `crypto` feature).
98    pub use crate::adapters::coingecko::{CoinQuote, coin, coins};
99}
100
101#[cfg(feature = "rss")]
102pub mod feeds;
103
104#[cfg(feature = "risk")]
105pub mod risk;
106
107// ============================================================================
108// High-level API - Primary interface for most use cases
109// ============================================================================
110pub mod domains;
111pub use providers::config::{Providers, ProvidersBuilder};
112pub use providers::{Capability, Fetch, Provider};
113pub use ticker::{ClientHandle, Ticker, TickerBuilder};
114
115// Domain-specific query handles — constructable via Providers factory methods.
116#[cfg(any(
117    feature = "alphavantage",
118    feature = "crypto",
119    feature = "fmp",
120    feature = "polygon"
121))]
122pub use domains::CryptoCoin;
123#[cfg(any(feature = "alphavantage", feature = "polygon", feature = "fred"))]
124pub use domains::EconomicIndicator;
125#[cfg(any(feature = "alphavantage", feature = "fmp", feature = "polygon"))]
126pub use domains::ForexPair;
127
128// Remaining Capability handles — indices, futures, commodities, filings
129#[cfg(any(feature = "fmp", feature = "alphavantage"))]
130pub use domains::Commodity;
131pub use domains::Filings;
132#[cfg(feature = "polygon")]
133pub use domains::FuturesContract;
134#[cfg(any(feature = "polygon", feature = "fmp"))]
135pub use domains::Index;
136
137// Provider-specific financial data functions
138// (FMP, Polygon, Alpha Vantage — defined in the finance module)
139#[cfg(feature = "polygon")]
140pub use finance::symbol_sentiment;
141#[cfg(feature = "fmp")]
142pub use finance::{
143    AnalystEstimate, AnalystRecommendation, InsiderTransaction, Period, analyst_estimates,
144    analyst_recommendations, insider_trading,
145};
146#[cfg(feature = "alphavantage")]
147pub use finance::{EarningsCalendarEntry, IpoCalendarEntry, earnings_calendar, ipo_calendar};
148
149pub use tickers::{
150    BatchCapitalGainsResponse, BatchChartsResponse, BatchDividendsResponse,
151    BatchFinancialsResponse, BatchNewsResponse, BatchOptionsResponse, BatchQuotesResponse,
152    BatchRecommendationsResponse, BatchSparksResponse, BatchSplitsResponse, Tickers,
153    TickersBuilder,
154};
155
156#[cfg(feature = "indicators")]
157pub use tickers::BatchIndicatorsResponse;
158
159// ============================================================================
160// Error types and results
161// ============================================================================
162pub use error::{ErrorCategory, FinanceError, Result};
163
164// ============================================================================
165// Options - Configure API requests
166// ============================================================================
167pub use finance::{LookupOptions, LookupType, SearchOptions};
168
169// ============================================================================
170// Parameter enums - Used with Ticker and finance methods
171// ============================================================================
172pub use constants::indices::Region as IndicesRegion;
173pub use constants::screeners::Screener;
174pub use constants::sectors::Sector;
175pub use constants::{Frequency, Interval, Region, StatementType, TimeRange, ValueFormat};
176
177// ============================================================================
178// Response types - Top-level types returned by API methods
179// ============================================================================
180pub use models::{
181    chart::Chart,
182    chart::spark::Spark,
183    corporate::news::News,
184    corporate::recommendation::Recommendation,
185    corporate::transcript::{Transcript, TranscriptWithMeta},
186    discovery::lookup::LookupResults,
187    discovery::screeners::ScreenerResults,
188    discovery::search::SearchResults,
189    discovery::trending::TrendingQuote,
190    filings::{
191        CompanyFacts, EdgarSearchResults, EdgarSubmissions, ProviderFiling, ProviderFilings,
192    },
193    fundamentals::FinancialStatement,
194    market::currencies::Currency,
195    market::exchanges::Exchange,
196    market::hours::MarketHours,
197    market::industries::IndustryData,
198    market::market_summary::MarketSummaryQuote,
199    market::sectors::SectorData,
200    options::Options,
201    quote::Quote,
202    sentiment::{FearAndGreed, FearGreedLabel, SymbolSentiment},
203};
204// Multi-provider capability response types (feature-gated)
205#[cfg(any(feature = "fmp", feature = "alphavantage"))]
206pub use models::commodities::CommodityQuote;
207#[cfg(any(
208    feature = "crypto",
209    feature = "alphavantage",
210    feature = "fmp",
211    feature = "polygon"
212))]
213pub use models::crypto::CryptoQuote;
214#[cfg(any(feature = "fred", feature = "alphavantage", feature = "polygon"))]
215pub use models::economic::EconomicSeries;
216#[cfg(any(feature = "alphavantage", feature = "fmp", feature = "polygon"))]
217pub use models::forex::ForexQuote;
218#[cfg(feature = "polygon")]
219pub use models::futures::FuturesQuote;
220#[cfg(any(feature = "polygon", feature = "fmp"))]
221pub use models::indices::IndexQuote;
222
223// ============================================================================
224// Nested types - Commonly accessed fields within response types
225// ============================================================================
226pub use models::{
227    chart::{Candle, CapitalGain, ChartMeta, Dividend, DividendAnalytics, Split},
228    corporate::recommendation::SimilarSymbol,
229    discovery::lookup::LookupQuote,
230    discovery::screeners::ScreenerQuote,
231    discovery::search::{
232        ResearchReport, ResearchReports, SearchNews, SearchNewsList, SearchQuote, SearchQuotes,
233    },
234    filings::filing_index::{EdgarFilingIndex, EdgarFilingIndexItem},
235    filings::{
236        CikEntry, EdgarFiling, EdgarFilingFile, EdgarFilingRecent, EdgarFilings, EdgarSearchHit,
237        EdgarSearchHitsContainer, EdgarSearchSource, EdgarSearchTotal, FactConcept, FactUnit,
238        FactsByTaxonomy,
239    },
240    market::hours::MarketTime,
241    market::market_summary::SparkData,
242    options::{Contracts, OptionChain, OptionContract, OptionsQuote},
243    quote::FormattedValue,
244};
245
246// ============================================================================
247// Query builders - Types for constructing custom screener queries
248// ============================================================================
249pub use constants::exchange_codes::ExchangeCode;
250pub use constants::industries::Industry;
251pub use models::discovery::screeners::{
252    ConditionValue, EquityField, EquityScreenerQuery, FundField, FundScreenerQuery,
253    LogicalOperator, Operator, QueryCondition, QueryGroup, QueryOperand, QuoteType, ScreenerField,
254    ScreenerFieldExt, ScreenerFundCategory, ScreenerPeerGroup, ScreenerQuery, SortType,
255};
256
257// ============================================================================
258// Real-time streaming
259// ============================================================================
260// WebSocket-based real-time price streaming with a Flow-like Stream API.
261pub mod streaming;
262
263// ============================================================================
264// DataFrame support (requires "dataframe" feature)
265// ============================================================================
266// When enabled, structs with #[derive(ToDataFrame)] get a to_dataframe() method.
267// The derive macro auto-generates DataFrame conversion for all scalar fields.
268#[cfg(feature = "dataframe")]
269pub use finance_query_derive::ToDataFrame;
270
271// ============================================================================
272// Technical Indicators (requires "indicators" feature)
273// ============================================================================
274// Technical analysis indicators for price data (SMA, EMA, RSI, MACD, Bollinger Bands).
275// When enabled, Chart gets extension methods: chart.sma(), chart.ema(), chart.rsi(), etc.
276#[cfg(feature = "indicators")]
277pub mod indicators;
278
279#[cfg(feature = "indicators")]
280pub use indicators::{
281    // Summary types
282    AroonData,
283    // Individual indicator types
284    BollingerBands,
285    BollingerBandsData,
286    BullBearPowerData,
287    // Candlestick pattern types
288    CandlePattern,
289    DonchianChannelsData,
290    ElderRayData,
291    IchimokuData,
292    Indicator,
293    IndicatorError,
294    IndicatorResult,
295    IndicatorsSummary,
296    KeltnerChannelsData,
297    MacdData,
298    MacdResult,
299    PatternSentiment,
300    StochasticData,
301    SuperTrendData,
302    atr,
303    patterns,
304};
305
306// ============================================================================
307// Backtesting Engine (requires "backtesting" feature)
308// ============================================================================
309// Strategy backtesting with pre-built and custom strategies, position tracking,
310// stop-loss/take-profit, comprehensive performance metrics, parameter optimization,
311// walk-forward validation, Monte Carlo simulation, and multi-symbol portfolio.
312#[cfg(feature = "backtesting")]
313pub mod backtesting;
314
315// ============================================================================
316// Compile-time thread-safety assertions
317// ============================================================================
318// Ticker and Tickers must be Send + Sync so they can be shared across
319// async tasks and held across .await points (e.g., in Arc, tokio::spawn).
320const _: () = {
321    const fn assert_send_sync<T: Send + Sync>() {}
322    let _ = assert_send_sync::<Ticker>;
323    let _ = assert_send_sync::<Tickers>;
324};