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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
use crate::auth::YahooAuth;
use crate::constants::{Interval, Region, TimeRange};
use crate::error::{FinanceError, Result};
use std::time::Duration;
use tracing::{debug, info};
// ============================================================================
// Client Configuration Constants
// ============================================================================
/// Default HTTP request timeout
pub(crate) const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
/// Default language for API requests
pub(crate) const DEFAULT_LANG: &str = "en-US";
/// Default region for API requests
pub(crate) const DEFAULT_REGION: &str = "US";
/// Merge parameter for timeseries - don't merge data
pub(crate) const API_PARAM_MERGE: &str = "false";
/// Pad timeseries - fill gaps in data
pub(crate) const API_PARAM_PAD_TIMESERIES: &str = "true";
/// Configuration for Yahoo Finance client
#[derive(Debug, Clone)]
pub struct ClientConfig {
/// HTTP request timeout
pub timeout: Duration,
/// Optional proxy URL
pub proxy: Option<String>,
/// Language code for API requests (e.g., "en-US", "ja-JP", "de-DE")
pub lang: String,
/// Region code for API requests (e.g., "US", "JP", "DE")
pub region: String,
}
impl Default for ClientConfig {
fn default() -> Self {
Self {
timeout: DEFAULT_TIMEOUT,
proxy: None,
lang: DEFAULT_LANG.to_string(),
region: DEFAULT_REGION.to_string(),
}
}
}
impl ClientConfig {
/// Create a new builder for ClientConfig
///
/// # Example
///
/// ```ignore
/// use finance_query::ClientConfig;
/// use std::time::Duration;
///
/// let config = ClientConfig::builder()
/// .timeout(Duration::from_secs(30))
/// .lang("ja-JP")
/// .region_code("JP")
/// .build();
/// ```
pub fn builder() -> ClientConfigBuilder {
ClientConfigBuilder::new()
}
}
/// Builder for ClientConfig
///
/// Provides a fluent API for constructing ClientConfig instances.
///
/// # Example
///
/// ```ignore
/// use finance_query::ClientConfig;
/// use std::time::Duration;
///
/// let config = ClientConfig::builder()
/// .timeout(Duration::from_secs(30))
/// .proxy("http://proxy.example.com:8080")
/// .lang("de-DE")
/// .region_code("DE")
/// .build();
/// ```
#[derive(Debug)]
pub struct ClientConfigBuilder {
timeout: Duration,
proxy: Option<String>,
lang: String,
region: String,
}
impl ClientConfigBuilder {
fn new() -> Self {
let default = ClientConfig::default();
Self {
timeout: default.timeout,
proxy: default.proxy,
lang: default.lang,
region: default.region,
}
}
/// Set the HTTP request timeout
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
/// Set the proxy URL
pub fn proxy(mut self, proxy: impl Into<String>) -> Self {
self.proxy = Some(proxy.into());
self
}
/// Set the region (automatically sets correct lang and code)
///
/// This is the recommended way to configure regional settings as it ensures
/// lang and region code are correctly paired.
///
/// # Example
///
/// ```ignore
/// use finance_query::{ClientConfig, Region};
///
/// let config = ClientConfig::builder()
/// .region(Region::Germany)
/// .build();
/// ```
pub fn region(mut self, region: crate::constants::Region) -> Self {
self.lang = region.lang().to_string();
self.region = region.region().to_string();
self
}
/// Set the language code (e.g., "en-US", "ja-JP", "de-DE")
///
/// For standard countries, prefer using `.region()` instead to ensure
/// correct lang/region pairing.
pub fn lang(mut self, lang: impl Into<String>) -> Self {
self.lang = lang.into();
self
}
/// Set the region code (e.g., "US", "JP", "DE")
///
/// For standard countries, prefer using `.region()` instead to ensure
/// correct lang/region pairing.
pub fn region_code(mut self, region: impl Into<String>) -> Self {
self.region = region.into();
self
}
/// Build the ClientConfig
pub fn build(self) -> ClientConfig {
ClientConfig {
timeout: self.timeout,
proxy: self.proxy,
lang: self.lang,
region: self.region,
}
}
}
/// Yahoo Finance API client
///
/// This client handles authentication and provides methods to fetch data from Yahoo Finance.
pub struct YahooClient {
/// Authentication data (crumb + HTTP client with cookies).
/// Immutable after construction — no lock needed.
auth: YahooAuth,
/// Client configuration
config: ClientConfig,
}
impl YahooClient {
/// Check response status and return it if successful, or map the error code
fn check_response(response: reqwest::Response) -> Result<reqwest::Response> {
let status = response.status();
if !status.is_success() {
return Err(Self::map_http_status(status.as_u16()));
}
Ok(response)
}
/// HTTP error mapping
fn map_http_status(status: u16) -> FinanceError {
match status {
401 => FinanceError::AuthenticationFailed {
context: "HTTP 401 Unauthorized".to_string(),
},
404 => FinanceError::SymbolNotFound {
symbol: None,
context: "HTTP 404 Not Found".to_string(),
},
429 => FinanceError::RateLimited { retry_after: None },
status if status >= 500 => FinanceError::ServerError {
status,
context: format!("HTTP {}", status),
},
_ => FinanceError::UnexpectedResponse(format!("HTTP {}", status)),
}
}
/// Map reqwest errors to FinanceError, using configured timeout for error messages
fn map_request_error(&self, e: reqwest::Error) -> FinanceError {
if e.is_timeout() {
FinanceError::Timeout {
timeout_ms: self.config.timeout.as_millis() as u64,
}
} else {
FinanceError::HttpError(e)
}
}
/// Create a new Yahoo Finance client
///
/// This will perform authentication with Yahoo Finance immediately.
///
/// # Example
///
/// ```ignore
/// use finance_query::{YahooClient, ClientConfig};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = YahooClient::new(ClientConfig::default()).await?;
/// # Ok(())
/// # }
/// ```
pub async fn new(config: ClientConfig) -> Result<Self> {
info!("Initializing Yahoo Finance client");
// Authenticate with the provided configuration (timeout, proxy)
let auth = YahooAuth::authenticate_with_config(&config).await?;
Ok(Self { auth, config })
}
/// Make a GET request to Yahoo Finance with authentication
///
/// This automatically:
/// - Adds the crumb token as a query parameter
/// - Includes cookies via reqwest's cookie store
/// - Sets proper headers
pub async fn request_with_crumb(&self, url: &str) -> Result<reqwest::Response> {
let request = self
.auth
.http_client
.get(url)
.query(&[("crumb", &self.auth.crumb)]);
debug!("Making request to {}", url);
// Send request
let response = request
.send()
.await
.map_err(|e| self.map_request_error(e))?;
Self::check_response(response)
}
/// Get the client configuration
///
/// Returns a reference to the client's configuration, including language and region settings.
pub fn config(&self) -> &ClientConfig {
&self.config
}
/// Fetch logo URLs for a symbol
///
/// Returns (logoUrl, companyLogoUrl) if available, None for each if not found or on error.
/// This uses the /v7/finance/quote endpoint with selective fields for efficiency.
///
/// # Arguments
///
/// * `symbol` - Stock symbol (e.g., "AAPL", "TSLA")
///
/// # Returns
///
/// Tuple of (logoUrl, companyLogoUrl), each as Option<String>
///
/// # Example
///
/// ```ignore
/// # use finance_query::{YahooClient, ClientConfig};
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = YahooClient::new(ClientConfig::default()).await?;
/// let (logo_url, company_logo_url) = client.get_logo_url("AAPL").await;
/// if let Some(url) = logo_url {
/// println!("Logo URL: {}", url);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn get_logo_url(&self, symbol: &str) -> (Option<String>, Option<String>) {
// Use existing fetch_with_fields from quotes.rs
let json = match crate::endpoints::quotes::fetch_with_fields(
self,
&[symbol],
Some(&["logoUrl", "companyLogoUrl"]),
false, // no formatting needed
true, // include logo params (imgHeights, imgWidths, imgLabels)
)
.await
{
Ok(j) => j,
Err(_) => return (None, None),
};
// Extract both URLs from response
let result = match json
.get("quoteResponse")
.and_then(|qr| qr.get("result"))
.and_then(|r| r.as_array())
.and_then(|arr| arr.first())
{
Some(r) => r,
None => return (None, None),
};
let logo_url = result
.get("logoUrl")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let company_logo_url = result
.get("companyLogoUrl")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
(logo_url, company_logo_url)
}
/// Make a POST request with JSON body and crumb authentication
///
/// Used for endpoints that require POST with JSON payload (e.g., custom screeners)
pub async fn request_post_with_crumb<T: serde::Serialize + ?Sized>(
&self,
url: &str,
body: &T,
) -> Result<reqwest::Response> {
// Build URL with crumb
let url_with_crumb = format!(
"{}{}crumb={}",
url,
if url.contains('?') { "&" } else { "?" },
self.auth.crumb
);
let request = self
.auth
.http_client
.post(&url_with_crumb)
.header("Content-Type", "application/json")
.header("x-crumb", &self.auth.crumb)
.json(body);
debug!("Making POST request to {}", url_with_crumb);
let response = request
.send()
.await
.map_err(|e| self.map_request_error(e))?;
Self::check_response(response)
}
/// Make a GET request with query parameters and crumb authentication
pub async fn request_with_params<T: serde::Serialize + ?Sized>(
&self,
url: &str,
params: &T,
) -> Result<reqwest::Response> {
let request = self
.auth
.http_client
.get(url)
.query(&[("crumb", &self.auth.crumb)])
.query(params);
debug!(
"Making request to {} (lang={}, region={})",
url, self.config.lang, self.config.region
);
let response = request
.send()
.await
.map_err(|e| self.map_request_error(e))?;
Self::check_response(response)
}
/// Fetch batch quotes for multiple symbols
///
/// This uses the /v7/finance/quote endpoint which is more efficient for batch requests.
///
/// # Example
///
/// ```ignore
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = finance_query::YahooClient::new(Default::default()).await?;
/// let quotes = client.get_quotes(&["AAPL", "GOOGL", "MSFT"]).await?;
/// # Ok(())
/// # }
/// ```
#[cfg(test)]
pub(crate) async fn get_quotes(&self, symbols: &[&str]) -> Result<serde_json::Value> {
crate::endpoints::quotes::fetch(self, symbols).await
}
/// Fetch chart data for a symbol
///
/// # Example
///
/// ```ignore
/// use finance_query::{Interval, TimeRange};
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = finance_query::YahooClient::new(Default::default()).await?;
/// let chart = client.get_chart("AAPL", Interval::OneDay, TimeRange::OneMonth).await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_chart(
&self,
symbol: &str,
interval: Interval,
range: TimeRange,
) -> Result<serde_json::Value> {
crate::endpoints::chart::fetch(self, symbol, interval, range).await
}
/// Fetch chart data for a symbol using absolute date boundaries
pub async fn get_chart_range(
&self,
symbol: &str,
interval: Interval,
start: i64,
end: i64,
) -> Result<serde_json::Value> {
crate::endpoints::chart::fetch_with_dates(self, symbol, interval, start, end).await
}
/// Search for quotes and news
///
/// # Example
///
/// ```ignore
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # use finance_query::SearchOptions;
/// # let client = finance_query::YahooClient::new(Default::default()).await?;
/// // Simple search with defaults
/// let results = client.search("Apple", &SearchOptions::default()).await?;
///
/// // Search with custom options
/// let options = SearchOptions::new()
/// .quotes_count(10)
/// .news_count(5)
/// .enable_research_reports(true);
/// let results = client.search("NVDA", &options).await?;
/// # Ok(())
/// # }
/// ```
pub async fn search(
&self,
query: &str,
options: &crate::endpoints::search::SearchOptions,
) -> Result<crate::models::search::SearchResults> {
let json = crate::endpoints::search::fetch(self, query, options).await?;
Ok(crate::models::search::SearchResults::from_json(json)?)
}
/// Look up symbols by type (equity, ETF, index, etc.)
///
/// Unlike search, lookup specializes in discovering tickers filtered by asset type.
/// Optionally fetches logo URLs via an additional API call.
///
/// # Example
///
/// ```ignore
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # use finance_query::{LookupOptions, LookupType};
/// # let client = finance_query::YahooClient::new(Default::default()).await?;
/// // Simple lookup with defaults
/// let results = client.lookup("Apple", &LookupOptions::default()).await?;
///
/// // Lookup equities only with logos
/// let options = LookupOptions::new()
/// .lookup_type(LookupType::Equity)
/// .count(10)
/// .include_logo(true);
/// let results = client.lookup("NVDA", &options).await?;
/// # Ok(())
/// # }
/// ```
pub async fn lookup(
&self,
query: &str,
options: &crate::endpoints::lookup::LookupOptions,
) -> Result<crate::models::lookup::LookupResults> {
let json = crate::endpoints::lookup::fetch(self, query, options).await?;
Ok(crate::models::lookup::LookupResults::from_json(json)?)
}
/// Get recommended/similar quotes for a symbol
///
/// # Example
///
/// ```ignore
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = finance_query::YahooClient::new(Default::default()).await?;
/// let recommendations = client.get_recommendations("AAPL", 5).await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_recommendations(&self, symbol: &str, limit: u32) -> Result<serde_json::Value> {
crate::endpoints::recommendations::fetch(self, symbol, limit).await
}
/// Fetch fundamentals timeseries data (financial statements)
///
/// # Arguments
///
/// * `symbol` - Stock symbol
/// * `statement_type` - Type of statement (Income, Balance, CashFlow)
/// * `frequency` - Annual or Quarterly
///
/// # Example
///
/// ```ignore
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = finance_query::YahooClient::new(Default::default()).await?;
/// use finance_query::{StatementType, Frequency};
/// let statement = client.get_financials("AAPL", StatementType::Income, Frequency::Annual).await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_financials(
&self,
symbol: &str,
statement_type: crate::constants::StatementType,
frequency: crate::constants::Frequency,
) -> Result<crate::models::financials::FinancialStatement> {
crate::endpoints::financials::fetch(self, symbol, statement_type, frequency).await
}
/// Fetch quote type data including company ID (quartrId)
///
/// # Example
///
/// ```ignore
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = finance_query::YahooClient::new(Default::default()).await?;
/// let quote_type = client.get_quote_type("AAPL").await?;
/// # Ok(())
/// # }
/// ```
#[cfg(test)]
pub(crate) async fn get_quote_type(&self, symbol: &str) -> Result<serde_json::Value> {
crate::endpoints::quote_type::fetch(self, symbol).await
}
/// Get options chain for a symbol
///
/// # Example
///
/// ```ignore
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = finance_query::YahooClient::new(Default::default()).await?;
/// let options = client.get_options("AAPL", None).await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_options(&self, symbol: &str, date: Option<i64>) -> Result<serde_json::Value> {
crate::endpoints::options::fetch(self, symbol, date).await
}
/// Get data from a predefined Yahoo Finance screener
///
/// Fetches stocks/funds matching predefined criteria such as day gainers,
/// day losers, most actives, most shorted stocks, growth stocks, and more.
///
/// # Arguments
///
/// * `screener_type` - The predefined screener type to use
/// * `count` - Number of results to return (max 250)
///
/// # Example
///
/// ```ignore
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = finance_query::YahooClient::new(Default::default()).await?;
/// use finance_query::Screener;
/// let gainers = client.get_screener(Screener::DayGainers, 25).await?;
/// let losers = client.get_screener(Screener::DayLosers, 25).await?;
/// let actives = client.get_screener(Screener::MostActives, 25).await?;
/// let shorted = client.get_screener(Screener::MostShortedStocks, 25).await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_screener(
&self,
screener_type: crate::constants::screeners::Screener,
count: u32,
) -> Result<crate::models::screeners::ScreenerResults> {
crate::endpoints::screeners::fetch(self, screener_type, count).await
}
/// Execute a custom screener query
///
/// Allows flexible filtering of stocks/funds/ETFs based on various criteria.
///
/// # Arguments
///
/// * `query` - The custom screener query to execute
///
/// # Example
///
/// ```ignore
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = finance_query::YahooClient::new(Default::default()).await?;
/// use finance_query::{EquityField, EquityScreenerQuery, ScreenerFieldExt};
///
/// // Find US stocks with high volume sorted by market cap
/// let query = EquityScreenerQuery::new()
/// .size(25)
/// .sort_by(EquityField::IntradayMarketCap, false)
/// .add_condition(EquityField::Region.eq_str("us"))
/// .add_condition(EquityField::AvgDailyVol3M.gt(200_000.0));
///
/// let result = client.custom_screener(query).await?;
/// # Ok(())
/// # }
/// ```
pub async fn custom_screener<F: crate::models::screeners::ScreenerField>(
&self,
query: crate::models::screeners::ScreenerQuery<F>,
) -> Result<crate::models::screeners::ScreenerResults> {
crate::endpoints::screeners::fetch_custom(self, query).await
}
/// Fetch detailed sector data from Yahoo Finance
///
/// Returns comprehensive sector information including overview, performance,
/// top companies, ETFs, mutual funds, industries, and research reports.
///
/// # Arguments
///
/// * `sector_type` - The sector to fetch data for
///
/// # Example
///
/// ```ignore
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = finance_query::YahooClient::new(Default::default()).await?;
/// use finance_query::Sector;
/// let sector = client.get_sector(Sector::Technology).await?;
/// println!("Sector: {} ({} companies)", sector.name,
/// sector.overview.as_ref().map(|o| o.companies_count.unwrap_or(0)).unwrap_or(0));
/// for company in sector.top_companies.iter().take(5) {
/// println!(" {} - {:?}", company.symbol, company.name);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn get_sector(
&self,
sector_type: crate::constants::sectors::Sector,
) -> Result<crate::models::sectors::SectorData> {
crate::endpoints::sectors::fetch(self, sector_type).await
}
/// Fetch detailed industry data from Yahoo Finance
///
/// Returns comprehensive industry information including overview, performance,
/// top companies, top performing companies, top growth companies, and research reports.
///
/// # Arguments
///
/// * `industry_key` - The industry key/slug (e.g., "semiconductors", "software-infrastructure")
///
/// # Example
///
/// ```ignore
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = finance_query::YahooClient::new(Default::default()).await?;
/// let industry = client.get_industry("semiconductors").await?;
/// println!("Industry: {} ({} companies)", industry.name,
/// industry.overview.as_ref().map(|o| o.companies_count.unwrap_or(0)).unwrap_or(0));
/// for company in industry.top_companies.iter().take(5) {
/// println!(" {} - {:?}", company.symbol, company.name);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn get_industry(
&self,
industry_key: &str,
) -> Result<crate::models::industries::IndustryData> {
crate::endpoints::industries::fetch(self, industry_key).await
}
/// Get market hours/time data
///
/// Returns the current status for various markets.
///
/// # Arguments
///
/// * `region` - Optional region override (e.g., "US", "JP", "GB"). If None, uses client's configured region.
///
/// # Example
///
/// ```ignore
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = finance_query::YahooClient::new(Default::default()).await?;
/// // Use client's default region
/// let hours = client.get_hours(None).await?;
///
/// // Get Japan market hours
/// let jp_hours = client.get_hours(Some("JP")).await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_hours(
&self,
region: Option<&str>,
) -> Result<crate::models::hours::MarketHours> {
crate::endpoints::hours::fetch(self, region).await
}
/// Get list of available currencies
///
/// Returns currency information from Yahoo Finance.
///
/// # Example
///
/// ```ignore
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = finance_query::YahooClient::new(Default::default()).await?;
/// let currencies = client.get_currencies().await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_currencies(&self) -> Result<Vec<crate::models::currencies::Currency>> {
let json = crate::endpoints::currencies::fetch(self).await?;
Ok(crate::models::currencies::Currency::from_response(json)?)
}
/// Get market summary
///
/// Returns market summary with major indices, currencies, and commodities.
///
/// # Arguments
///
/// * `region` - Optional region for localization. If None, uses client's configured lang/code.
///
/// # Example
///
/// ```ignore
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = finance_query::YahooClient::new(Default::default()).await?;
/// use finance_query::Region;
/// // Use client's default config
/// let summary = client.get_market_summary(None).await?;
/// // Or specify a region
/// let summary = client.get_market_summary(Some(Region::France)).await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_market_summary(
&self,
region: Option<Region>,
) -> Result<Vec<crate::models::market_summary::MarketSummaryQuote>> {
let json = crate::endpoints::market_summary::fetch(self, region).await?;
Ok(crate::models::market_summary::MarketSummaryQuote::from_response(json)?)
}
/// Get trending tickers for a region
///
/// Returns trending stocks for a specific region.
///
/// # Arguments
///
/// * `region` - Optional region for localization. If None, uses client's configured lang/region.
///
/// # Example
///
/// ```ignore
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = finance_query::YahooClient::new(Default::default()).await?;
/// use finance_query::Region;
/// // Use client's default config
/// let trending = client.get_trending(None).await?;
/// // Or specify a region
/// let trending = client.get_trending(Some(Region::France)).await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_trending(
&self,
region: Option<Region>,
) -> Result<Vec<crate::models::trending::TrendingQuote>> {
let json = crate::endpoints::trending::fetch(self, region).await?;
Ok(crate::models::trending::TrendingQuote::from_response(json)?)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
#[ignore] // Ignore by default as it makes real network requests
async fn test_client_creation() {
let client = YahooClient::new(ClientConfig::default()).await;
assert!(client.is_ok());
}
#[test]
fn test_default_config() {
let config = ClientConfig::default();
assert_eq!(config.timeout, DEFAULT_TIMEOUT);
assert!(config.proxy.is_none());
}
#[tokio::test]
#[ignore] // Requires network access
async fn test_get_quotes() {
let client = YahooClient::new(ClientConfig::default()).await.unwrap();
let result = client.get_quotes(&["AAPL", "GOOGL"]).await;
assert!(result.is_ok());
let json = result.unwrap();
assert!(json.get("quoteResponse").is_some());
}
#[tokio::test]
#[ignore] // Requires network access
async fn test_get_chart() {
let client = YahooClient::new(ClientConfig::default()).await.unwrap();
let result = client
.get_chart("AAPL", Interval::OneDay, TimeRange::OneMonth)
.await;
assert!(result.is_ok());
let json = result.unwrap();
assert!(json.get("chart").is_some());
}
#[tokio::test]
#[ignore] // Requires network access
async fn test_search() {
use crate::endpoints::search::SearchOptions;
let client = YahooClient::new(ClientConfig::default()).await.unwrap();
let options = SearchOptions::new().quotes_count(5);
let result = client.search("Apple", &options).await;
assert!(result.is_ok());
let response = result.unwrap();
assert!(!response.quotes.is_empty(), "Should have search results");
}
#[tokio::test]
#[ignore] // Requires network access
async fn test_get_recommendations() {
let client = YahooClient::new(ClientConfig::default()).await.unwrap();
let result = client.get_recommendations("AAPL", 5).await;
assert!(result.is_ok());
let json = result.unwrap();
assert!(json.get("finance").is_some());
}
#[tokio::test]
#[ignore] // Requires network access
async fn test_get_quote_type() {
let client = YahooClient::new(ClientConfig::default()).await.unwrap();
let result = client.get_quote_type("AAPL").await;
assert!(result.is_ok());
let json = result.unwrap();
assert!(json.get("quoteType").is_some());
}
#[tokio::test]
#[ignore] // Requires network access
async fn test_get_financials() {
use crate::constants::{Frequency, StatementType};
let client = YahooClient::new(ClientConfig::default()).await.unwrap();
let result = client
.get_financials("AAPL", StatementType::Income, Frequency::Annual)
.await;
assert!(result.is_ok());
let statement = result.unwrap();
assert_eq!(statement.symbol, "AAPL");
assert!(statement.statement.contains_key("TotalRevenue"));
}
}