1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
use super::{
BatchFinancialsResponse, BatchNewsResponse, BatchOptionsResponse, BatchRecommendationsResponse,
Tickers,
};
use crate::constants::{Frequency, StatementType};
use crate::error::Result;
use crate::models::corporate::news::News;
use crate::providers::Capability;
use crate::providers::types::recommendation_from_similar;
use crate::tickers::macros::batch_fetch_cached;
use futures::stream::StreamExt;
impl Tickers {
/// Batch fetch financial statements for all symbols
///
/// Fetches the specified financial statement type for all symbols concurrently.
/// Financial statements are cached per (symbol, statement_type, frequency) tuple.
///
/// # Arguments
///
/// * `statement_type` - Type of statement (Income, Balance, CashFlow)
/// * `frequency` - Annual or Quarterly
///
/// # Example
///
/// ```no_run
/// use finance_query::{Tickers, StatementType, Frequency};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let tickers = Tickers::new(["AAPL", "MSFT", "GOOGL"]).await?;
/// let financials = tickers.financials(StatementType::Income, Frequency::Annual).await?;
///
/// for (symbol, stmt) in &financials.financials {
/// if let Some(revenue) = stmt.statement.get("TotalRevenue") {
/// println!("{}: {:?}", symbol, revenue);
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub async fn financials(
&self,
statement_type: StatementType,
frequency: Frequency,
) -> Result<BatchFinancialsResponse> {
batch_fetch_cached!(self;
cache: financials_cache,
guard: map(financials_fetch, (statement_type, frequency)),
key: |s| (s.clone(), statement_type, frequency),
response: BatchFinancialsResponse.financials,
fetch: |providers, symbol| {
let sym = symbol.to_string();
providers.fetch(Capability::FUNDAMENTALS, move |p| {
let sym = sym.clone();
let p = p.clone();
async move {
p.as_fundamentals()
.ok_or_else(|| p.not_supported(crate::providers::Operation::Financials))?
.fetch_financials(&sym, statement_type, frequency)
.await
}
}).await
},
)
}
/// Batch fetch news articles for all symbols
///
/// Fetches recent news articles for all symbols concurrently using scrapers.
/// News articles are cached per symbol.
///
/// # Example
///
/// ```no_run
/// use finance_query::Tickers;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let tickers = Tickers::new(["AAPL", "MSFT"]).await?;
/// let news = tickers.news().await?;
///
/// for (symbol, articles) in &news.news {
/// println!("{}: {} articles", symbol, articles.len());
/// for article in articles.iter().take(3) {
/// println!(" - {}", article.title);
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub async fn news(&self) -> Result<BatchNewsResponse> {
batch_fetch_cached!(self;
cache: news_cache,
guard: simple(news_fetch),
key: |s| s.clone(),
response: BatchNewsResponse.news,
fetch: |providers, symbol| {
let sym = symbol.to_string();
providers.fetch(Capability::CORPORATE, move |p| {
let sym = sym.clone();
let p = p.clone();
async move {
p.as_corporate()
.ok_or_else(|| p.not_supported(crate::providers::Operation::News))?
.fetch_news(&sym)
.await
.map(|data| data.into_iter().collect::<Vec<News>>())
}
}).await
},
)
}
/// Batch fetch recommendations for all symbols
///
/// Fetches analyst recommendations and similar stocks for all symbols concurrently.
/// Recommendations are cached per (symbol, limit) tuple — different limits
/// produce different API responses and are cached independently.
///
/// # Arguments
///
/// * `limit` - Maximum number of similar stocks to return per symbol
///
/// # Example
///
/// ```no_run
/// use finance_query::Tickers;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let tickers = Tickers::new(["AAPL", "MSFT"]).await?;
/// let recommendations = tickers.recommendations(10).await?;
///
/// for (symbol, rec) in &recommendations.recommendations {
/// println!("{}: {} recommendations", symbol, rec.count());
/// for similar in &rec.recommendations {
/// println!(" - {}: score {}", similar.symbol, similar.score);
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub async fn recommendations(&self, limit: u32) -> Result<BatchRecommendationsResponse> {
batch_fetch_cached!(self;
cache: recommendations_cache,
guard: map(recommendations_fetch, limit),
key: |s| (s.clone(), limit),
response: BatchRecommendationsResponse.recommendations,
fetch: |providers, symbol| {
let sym = symbol.to_string();
providers.fetch(Capability::CORPORATE, move |p| {
let sym = sym.clone();
let p = p.clone();
async move {
let items = p
.as_corporate()
.ok_or_else(|| {
p.not_supported(crate::providers::Operation::Recommendations)
})?
.fetch_similar_symbols(&sym, limit)
.await?;
Ok(recommendation_from_similar(
sym,
Some(p.id()),
items,
Some(limit),
))
}
}).await
},
)
}
/// Batch fetch options chains for all symbols
///
/// Fetches options chains for the specified expiration date for all symbols concurrently.
/// Options are cached per (symbol, date) tuple.
///
/// # Arguments
///
/// * `date` - Optional expiration date (Unix timestamp). If None, fetches nearest expiration.
///
/// # Example
///
/// ```no_run
/// use finance_query::Tickers;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let tickers = Tickers::new(["AAPL", "MSFT"]).await?;
/// let options = tickers.options(None).await?;
///
/// for (symbol, opts) in &options.options {
/// println!("{}: {} expirations", symbol, opts.expiration_dates().len());
/// }
/// # Ok(())
/// # }
/// ```
pub async fn options(&self, date: Option<i64>) -> Result<BatchOptionsResponse> {
batch_fetch_cached!(self;
cache: options_cache,
guard: map(options_fetch, date),
key: |s| (s.clone(), date),
response: BatchOptionsResponse.options,
fetch: |providers, symbol| {
let sym = symbol.to_string();
providers.fetch(Capability::OPTIONS, move |p| {
let sym = sym.clone();
let p = p.clone();
async move {
p.as_options()
.ok_or_else(|| p.not_supported(crate::providers::Operation::Options))?
.fetch_options(&sym, date)
.await
}
}).await
},
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
#[ignore = "requires network access"]
async fn test_tickers_financials() {
let tickers = Tickers::new(["AAPL", "MSFT"]).await.unwrap();
let result = tickers
.financials(StatementType::Income, Frequency::Annual)
.await
.unwrap();
assert!(result.success_count() > 0);
// Verify financial statement structure
for (symbol, stmt) in &result.financials {
assert_eq!(stmt.symbol, *symbol);
assert_eq!(stmt.statement_type, "income");
assert_eq!(stmt.frequency, "annual");
assert!(!stmt.statement.is_empty());
// Common income statement fields
if let Some(revenue) = stmt.statement.get("TotalRevenue") {
assert!(!revenue.is_empty());
}
}
}
#[tokio::test]
#[ignore = "requires network access"]
async fn test_tickers_news() {
let tickers = Tickers::new(["AAPL", "TSLA"]).await.unwrap();
let result = tickers.news().await.unwrap();
assert!(result.success_count() > 0);
// Verify news structure
for articles in result.news.values() {
if !articles.is_empty() {
let article = &articles[0];
assert!(!article.title.is_empty());
assert!(!article.link.is_empty());
assert!(!article.source.is_empty());
}
}
}
#[tokio::test]
#[ignore = "requires network access"]
async fn test_tickers_recommendations() {
let tickers = Tickers::new(["AAPL", "MSFT"]).await.unwrap();
let result = tickers.recommendations(5).await.unwrap();
assert!(result.success_count() > 0);
// Verify recommendations structure
for (symbol, rec) in &result.recommendations {
assert_eq!(rec.symbol, *symbol);
assert!(rec.count() > 0);
for similar in &rec.recommendations {
assert!(!similar.symbol.is_empty());
}
}
}
#[tokio::test]
#[ignore = "requires network access"]
async fn test_tickers_options() {
let tickers = Tickers::new(["AAPL", "MSFT"]).await.unwrap();
let result = tickers.options(None).await.unwrap();
assert!(result.success_count() > 0);
// Verify options structure
for opts in result.options.values() {
assert!(!opts.expiration_dates().is_empty());
}
}
}