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