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