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/// SEC EDGAR API client for filing history, XBRL data, and full-text search.
60pub mod edgar;
61/// Error types and result definitions.
62pub mod error;
63/// Non-symbol-specific operations (search, lookup, screeners, market data, etc.).
64pub mod finance;
65
66// Internal modules
67mod auth;
68mod client;
69mod constants;
70mod endpoints;
71mod models;
72pub(crate) mod rate_limiter;
73mod scrapers;
74mod ticker;
75mod tickers;
76mod utils;
77
78// Feature-gated external data source modules
79#[cfg(feature = "fred")]
80pub mod fred;
81
82#[cfg(feature = "crypto")]
83pub mod crypto {
84    //! CoinGecko cryptocurrency data (requires `crypto` feature).
85    pub use crate::coingecko::{CoinQuote, coin, coins};
86}
87
88#[cfg(feature = "crypto")]
89mod coingecko;
90
91#[cfg(feature = "rss")]
92pub mod feeds;
93
94#[cfg(feature = "risk")]
95pub mod risk;
96
97// ============================================================================
98// High-level API - Primary interface for most use cases
99// ============================================================================
100pub use ticker::{ClientHandle, Ticker, TickerBuilder};
101pub use tickers::{
102    BatchCapitalGainsResponse, BatchChartsResponse, BatchDividendsResponse,
103    BatchFinancialsResponse, BatchNewsResponse, BatchOptionsResponse, BatchQuotesResponse,
104    BatchRecommendationsResponse, BatchSparksResponse, Tickers, TickersBuilder,
105};
106
107#[cfg(feature = "indicators")]
108pub use tickers::BatchIndicatorsResponse;
109
110// ============================================================================
111// Error types and results
112// ============================================================================
113pub use error::{FinanceError, Result};
114
115// ============================================================================
116// Options - Configure API requests
117// ============================================================================
118pub use finance::{LookupOptions, LookupType, SearchOptions};
119
120// ============================================================================
121// Parameter enums - Used with Ticker and finance methods
122// ============================================================================
123pub use constants::indices::Region as IndicesRegion;
124pub use constants::screeners::Screener;
125pub use constants::sectors::Sector;
126pub use constants::{Frequency, Interval, Region, StatementType, TimeRange, ValueFormat};
127
128// ============================================================================
129// Response types - Top-level types returned by API methods
130// ============================================================================
131pub use models::{
132    chart::Chart,
133    currencies::Currency,
134    edgar::{CompanyFacts, EdgarSearchResults, EdgarSubmissions},
135    exchanges::Exchange,
136    financials::FinancialStatement,
137    hours::MarketHours,
138    industries::IndustryData,
139    lookup::LookupResults,
140    market_summary::MarketSummaryQuote,
141    news::News,
142    options::Options,
143    quote::Quote,
144    recommendation::Recommendation,
145    screeners::ScreenerResults,
146    search::SearchResults,
147    sectors::SectorData,
148    sentiment::{FearAndGreed, FearGreedLabel},
149    spark::Spark,
150    transcript::Transcript,
151    transcript::TranscriptWithMeta,
152    trending::TrendingQuote,
153};
154
155// ============================================================================
156// Nested types - Commonly accessed fields within response types
157// ============================================================================
158pub use models::{
159    chart::{Candle, CapitalGain, ChartMeta, Dividend, DividendAnalytics, Split},
160    edgar::filing_index::{EdgarFilingIndex, EdgarFilingIndexItem},
161    edgar::{
162        CikEntry, EdgarFiling, EdgarFilingFile, EdgarFilingRecent, EdgarFilings, EdgarSearchHit,
163        EdgarSearchHitsContainer, EdgarSearchSource, EdgarSearchTotal, FactConcept, FactUnit,
164        FactsByTaxonomy,
165    },
166    hours::MarketTime,
167    lookup::LookupQuote,
168    market_summary::SparkData,
169    options::{Contracts, OptionChain, OptionContract, OptionsQuote},
170    quote::FormattedValue,
171    recommendation::SimilarSymbol,
172    screeners::ScreenerQuote,
173    search::{
174        ResearchReport, ResearchReports, SearchNews, SearchNewsList, SearchQuote, SearchQuotes,
175    },
176};
177
178// ============================================================================
179// Query builders - Types for constructing custom screener queries
180// ============================================================================
181pub use constants::exchange_codes::ExchangeCode;
182pub use constants::industries::Industry;
183pub use models::screeners::{
184    ConditionValue, EquityField, EquityScreenerQuery, FundField, FundScreenerQuery,
185    LogicalOperator, Operator, QueryCondition, QueryGroup, QueryOperand, QuoteType, ScreenerField,
186    ScreenerFieldExt, ScreenerFundCategory, ScreenerPeerGroup, ScreenerQuery, SortType,
187};
188
189// ============================================================================
190// Real-time streaming
191// ============================================================================
192// WebSocket-based real-time price streaming with a Flow-like Stream API.
193pub mod streaming;
194
195// ============================================================================
196// DataFrame support (requires "dataframe" feature)
197// ============================================================================
198// When enabled, structs with #[derive(ToDataFrame)] get a to_dataframe() method.
199// The derive macro auto-generates DataFrame conversion for all scalar fields.
200#[cfg(feature = "dataframe")]
201pub use finance_query_derive::ToDataFrame;
202
203// ============================================================================
204// Technical Indicators (requires "indicators" feature)
205// ============================================================================
206// Technical analysis indicators for price data (SMA, EMA, RSI, MACD, Bollinger Bands).
207// When enabled, Chart gets extension methods: chart.sma(), chart.ema(), chart.rsi(), etc.
208#[cfg(feature = "indicators")]
209pub mod indicators;
210
211#[cfg(feature = "indicators")]
212pub use indicators::{
213    // Summary types
214    AroonData,
215    // Individual indicator types
216    BollingerBands,
217    BollingerBandsData,
218    BullBearPowerData,
219    // Candlestick pattern types
220    CandlePattern,
221    DonchianChannelsData,
222    ElderRayData,
223    IchimokuData,
224    Indicator,
225    IndicatorError,
226    IndicatorResult,
227    IndicatorsSummary,
228    KeltnerChannelsData,
229    MacdData,
230    MacdResult,
231    PatternSentiment,
232    StochasticData,
233    SuperTrendData,
234    atr,
235    patterns,
236};
237
238// ============================================================================
239// Backtesting Engine (requires "backtesting" feature)
240// ============================================================================
241// Strategy backtesting with pre-built and custom strategies, position tracking,
242// stop-loss/take-profit, and comprehensive performance metrics.
243#[cfg(feature = "backtesting")]
244pub mod backtesting;
245
246// ============================================================================
247// Compile-time thread-safety assertions
248// ============================================================================
249// Ticker and Tickers must be Send + Sync so they can be shared across
250// async tasks and held across .await points (e.g., in Arc, tokio::spawn).
251const _: () = {
252    const fn assert_send_sync<T: Send + Sync>() {}
253    let _ = assert_send_sync::<Ticker>;
254    let _ = assert_send_sync::<Tickers>;
255};