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