eeyf 0.1.0

Eric Evans' Yahoo Finance API - A rate-limited, reliable Rust adapter for Yahoo Finance API
Documentation
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
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
use crate::quotes::{FinancialEvent, YEarningsResponse, YErrorMessage};
use crate::batch::{BatchOperations, BatchQuoteRequest, BatchResult};

use super::*;

impl YahooConnector {
    /// Retrieve the quotes of the last day for the given ticker
    pub async fn get_latest_quotes(
        &self,
        ticker: &str,
        interval: &str,
    ) -> Result<YResponse, YahooError> {
        self.get_quote_range(ticker, interval, "1mo").await
    }

    /// Retrieve the quote history for the given ticker form date start to end (inclusive), if available
    pub async fn get_quote_history(
        &self,
        ticker: &str,
        start: OffsetDateTime,
        end: OffsetDateTime,
    ) -> Result<YResponse, YahooError> {
        self.get_quote_history_interval(ticker, start, end, "1d")
            .await
    }

    /// Retrieve quotes for the given ticker for an arbitrary range
    pub async fn get_quote_range(
        &self,
        ticker: &str,
        interval: &str,
        range: &str,
    ) -> Result<YResponse, YahooError> {
        let url: String = format!(
            YCHART_RANGE_QUERY!(),
            url = self.url,
            symbol = ticker,
            interval = interval,
            range = range
        );
        YResponse::from_json(self.send_request(&url).await?)?.map_error_msg()
    }

    /// Retrieve the quote history for the given ticker form date start to end (inclusive), if available; specifying the interval of the ticker.
    pub async fn get_quote_history_interval(
        &self,
        ticker: &str,
        start: OffsetDateTime,
        end: OffsetDateTime,
        interval: &str,
    ) -> Result<YResponse, YahooError> {
        let url = format!(
            YCHART_PERIOD_QUERY!(),
            url = self.url,
            symbol = ticker,
            start = start.unix_timestamp(),
            end = end.unix_timestamp(),
            interval = interval,
        );
        YResponse::from_json(self.send_request(&url).await?)?.map_error_msg()
    }

    /// Retrieve the quote history for the given ticker form date start to end (inclusive) and optionally before and after regular trading hours, if available; specifying the interval of the ticker.
    pub async fn get_quote_history_interval_prepost(
        &self,
        ticker: &str,
        start: OffsetDateTime,
        end: OffsetDateTime,
        interval: &str,
        prepost: bool,
    ) -> Result<YResponse, YahooError> {
        let url = format!(
            YCHART_PERIOD_QUERY_PRE_POST!(),
            url = self.url,
            symbol = ticker,
            start = start.unix_timestamp(),
            end = end.unix_timestamp(),
            interval = interval,
            prepost = prepost,
        );
        YResponse::from_json(self.send_request(&url).await?)?.map_error_msg()
    }

    /// Retrieve the quote history for the given ticker for a given period and ticker interval and optionally before and after regular trading hours
    pub async fn get_quote_period_interval(
        &self,
        ticker: &str,
        range: &str,
        interval: &str,
        prepost: bool,
    ) -> Result<YResponse, YahooError> {
        let url = format!(
            YCHART_PERIOD_INTERVAL_QUERY!(),
            url = self.url,
            symbol = ticker,
            range = range,
            interval = interval,
            prepost = prepost,
        );
        YResponse::from_json(self.send_request(&url).await?)?.map_error_msg()
    }

    /// Retrieve the list of quotes found searching a given name
    pub async fn search_ticker_opt(&self, name: &str) -> Result<YSearchResultOpt, YahooError> {
        let url = format!(YTICKER_QUERY!(), url = self.search_url, name = name);
        YSearchResultOpt::from_json(self.send_request(&url).await?)
    }

    /// Retrieve the list of quotes found searching a given name
    pub async fn search_ticker(&self, name: &str) -> Result<YSearchResult, YahooError> {
        let result = self.search_ticker_opt(name).await?;
        Ok(YSearchResult::from_opt(&result))
    }

    // Get symbol metadata
    pub async fn get_ticker_info(&mut self, symbol: &str) -> Result<YQuoteSummary, YahooError> {
        if self.crumb.is_none() {
            self.crumb = Some(self.get_crumb().await?);
        }
        if self.cookie.is_none() {
            self.cookie = Some(self.get_cookie().await?);
        }

        let cookie_provider = Arc::new(reqwest::cookie::Jar::default());
        let url = reqwest::Url::parse(
            &(format!(
                YQUOTE_SUMMARY_QUERY!(),
                symbol = symbol,
                crumb = self.crumb.as_ref().unwrap()
            )),
        );

        cookie_provider.add_cookie_str(&self.cookie.clone().unwrap(), &url.clone().unwrap());

        let max_retries = 1;
        for i in 0..=max_retries {
            let text = self
                .create_client(Some(cookie_provider.clone()))
                .await?
                .get(url.clone().unwrap())
                .send()
                .await?
                .text()
                .await?;

            let result: YQuoteSummary = serde_json::from_str(&text)?;

            if let Some(finance) = &result.finance {
                if let Some(error) = &finance.error {
                    if let Some(description) = &error.description {
                        if description.contains("Invalid Crumb") {
                            self.crumb = Some(self.get_crumb().await?);
                            if i == max_retries {
                                return Err(YahooError::InvalidCrumb);
                            } else {
                                continue;
                            }
                        }
                    }
                    if let Some(code) = &error.code {
                        if code.contains("Unauthorized") {
                            self.crumb = Some(self.get_crumb().await?);
                            if i == max_retries {
                                return Err(YahooError::Unauthorized);
                            } else {
                                continue;
                            }
                        }
                    }
                }
            }
            return Ok(result);
        }

        Err(YahooError::NoResponse)
    }

    /// Retrieve financial events(Earnings, Meeting, Call) dates for the given ticker with specified limit (max limit: 250),
    pub async fn get_financial_events(
        &mut self,
        ticker: &str,
        limit: u32,
    ) -> Result<Vec<FinancialEvent>, YahooError> {
        if ticker.is_empty() {
            return Err(YahooError::FetchFailed(
                "Ticker cannot be empty".to_string(),
            ));
        }

        // Ensure we have crumb for authentication
        if self.crumb.is_none() {
            self.crumb = Some(self.get_crumb().await?);
        }
        if self.cookie.is_none() {
            self.cookie = Some(self.get_cookie().await?);
        }

        let url = format!(
            YEARNINGS_QUERY!(),
            url = Y_EARNINGS_URL,
            lang = "en-US",
            region = "US",
            crumb = self.crumb.as_ref().unwrap()
        );

        // Create request body
        let query_body = serde_json::json!({
            "size": limit,
            "query": {
                "operator": "eq",
                "operands": ["ticker", ticker]
            },
            "sortField": "startdatetime",
            "sortType": "DESC",
            "entityIdType": "earnings",
            "includeFields": [
                "startdatetime",
                "timeZoneShortName",
                "epsestimate",
                "epsactual",
                "epssurprisepct",
                "eventtype"
            ]
        });

        // Setup cookie for authenticated request
        let cookie_provider = Arc::new(reqwest::cookie::Jar::default());
        let parsed_url = reqwest::Url::parse(&url).map_err(|_| YahooError::InvalidUrl)?;

        if let Some(cookie) = &self.cookie {
            cookie_provider.add_cookie_str(cookie, &parsed_url);
        }

        let max_retries = 1;
        for attempt in 0..=max_retries {
            let client = self.create_client(Some(cookie_provider.clone())).await?;

            let response = client
                .post(&url)
                .header("Content-Type", "application/json")
                .json(&query_body)
                .send()
                .await?;

            let status = response.status();

            match status {
                reqwest::StatusCode::TOO_MANY_REQUESTS => {
                    return Err(YahooError::TooManyRequests(format!(
                        "POST {} in get_financial_events for ticker {}",
                        Y_EARNINGS_URL, ticker
                    )));
                }
                reqwest::StatusCode::UNAUTHORIZED => {
                    if attempt < max_retries {
                        self.crumb = Some(self.get_crumb().await?);
                        continue;
                    } else {
                        return Err(YahooError::Unauthorized);
                    }
                }
                reqwest::StatusCode::FORBIDDEN => {
                    return Err(YahooError::Unauthorized);
                }
                reqwest::StatusCode::NOT_FOUND => {
                    return Err(YahooError::FetchFailed(format!(
                        "Ticker {} not found",
                        ticker
                    )));
                }
                _ if !status.is_success() => {
                    return Err(YahooError::FetchFailed(format!("HTTP error: {}", status)));
                }
                _ => {} // Success, continue
            }

            let text = response.text().await?;

            // Try to parse response
            match serde_json::from_str::<YEarningsResponse>(&text) {
                Ok(earnings_response) => {
                    // Check for API errors
                    if let Some(error) = &earnings_response.finance.error {
                        let code = error.get("code").and_then(|v| v.as_str()).unwrap_or("");
                        let description = error
                            .get("description")
                            .and_then(|v| v.as_str())
                            .unwrap_or("");

                        // If the crumb is invalid, try to refetch it and retry the request
                        if description.contains("Invalid Crumb") {
                            if attempt < max_retries {
                                self.crumb = Some(self.get_crumb().await?); // Refetch crumb
                                continue; // Go to the next iteration
                            } else {
                                return Err(YahooError::InvalidCrumb);
                            }
                        }

                        return Err(YahooError::ApiError(YErrorMessage {
                            code: Some(code.to_string()),
                            description: Some(description.to_string()),
                        }));
                    }

                    return Ok(self.parse_earnings_response(earnings_response)?);
                }
                Err(e) => {
                    // A parsing error is a critical failure unless we are retrying.
                    if attempt < max_retries {
                        // It's possible the session expired, let's try refreshing the crumb and cookie.
                        self.crumb = Some(self.get_crumb().await?);
                        continue;
                    } else {
                        // If parsing fails on the last attempt, return the error.
                        return Err(YahooError::DeserializeFailed(e.to_string()));
                    }
                }
            }
        }

        Err(YahooError::NoResponse)
    }

    /// Parse earnings response into structured data
    fn parse_earnings_response(
        &self,
        response: YEarningsResponse,
    ) -> Result<Vec<FinancialEvent>, YahooError> {
        let mut earnings_events = Vec::new();

        if response.finance.result.is_empty() {
            return Ok(earnings_events);
        }

        let result = &response.finance.result[0];
        if result.documents.is_empty() {
            return Ok(earnings_events);
        }

        let document = &result.documents[0];

        if document.columns.is_empty() {
            return Err(YahooError::DataInconsistency);
        }

        // Map column names to indices
        let mut column_map = std::collections::HashMap::new();
        for (index, column) in document.columns.iter().enumerate() {
            column_map.insert(column.label.as_str(), index);
        }

        // Parse each row
        for row in &document.rows {
            let earnings_event = self.parse_earnings_row(row, &column_map)?;
            earnings_events.push(earnings_event);
        }

        Ok(earnings_events)
    }

    /// Parse individual earnings row
    fn parse_earnings_row(
        &self,
        row: &[serde_json::Value],
        column_map: &std::collections::HashMap<&str, usize>,
    ) -> Result<FinancialEvent, YahooError> {
        // Extract earnings date
        let get_value = |col_name: &str| column_map.get(col_name).and_then(|&idx| row.get(idx));

        let earnings_date = match get_value("Event Start Date").and_then(|v| v.as_str()) {
            Some(date_str) => {
                OffsetDateTime::parse(date_str, &time::format_description::well_known::Rfc3339)
                    .or_else(|_| {
                        OffsetDateTime::parse(
                            date_str,
                            &time::format_description::well_known::Iso8601::DEFAULT,
                        )
                    })
                    .map_err(|_| YahooError::InvalidDateFormat)?
            }
            None => return Err(YahooError::MissingField("Event Start Date".to_string())),
        };

        // Extract event type and convert codes
        let event_type = get_value("Event Type")
            .map(|v| {
                if let Some(s) = v.as_str() {
                    s.to_string()
                } else if let Some(i) = v.as_i64() {
                    i.to_string()
                } else {
                    "Unknown".to_string()
                }
            })
            .unwrap_or_else(|| "Unknown".to_string());

        let event_type = match event_type.as_str() {
            "1" => "Call".to_string(),
            "2" => "Earnings".to_string(),
            "11" => "Meeting".to_string(),
            other => other.to_string(),
        };
        let eps_estimate = get_value("EPS Estimate").and_then(|v| v.as_f64());
        let reported_eps = get_value("Reported EPS").and_then(|v| v.as_f64());
        let surprise_percent = get_value("Surprise (%)").and_then(|v| v.as_f64());
        let timezone = get_value("Timezone short name")
            .and_then(|v| v.as_str())
            .map(String::from);

        Ok(FinancialEvent {
            earnings_date,
            event_type,
            eps_estimate,
            reported_eps,
            surprise_percent,
            timezone,
        })
    }

    /// Get only earnings events (filter out meetings)
    pub async fn get_earnings_only(
        &mut self,
        ticker: &str,
        limit: u32,
    ) -> Result<Vec<FinancialEvent>, YahooError> {
        let all_events = self.get_financial_events(ticker, limit).await?;

        Ok(all_events
            .into_iter()
            .filter(|event| event.event_type == "Earnings")
            .collect())
    }

    async fn get_crumb(&mut self) -> Result<String, YahooError> {
        if self.cookie.is_none() {
            self.cookie = Some(self.get_cookie().await?);
        }

        const MAX_RETRIES: usize = 1;
        let crumb_url = reqwest::Url::parse(Y_GET_CRUMB_URL).unwrap();
        let mut last_error = YahooError::NoResponse;

        for _attempt in 0..=MAX_RETRIES {
            let cookie_provider = Arc::new(reqwest::cookie::Jar::default());
            cookie_provider.add_cookie_str(&self.cookie.clone().unwrap(), &crumb_url);

            let response = self
                .create_client(Some(cookie_provider.clone()))
                .await?
                .get(crumb_url.clone())
                .send()
                .await?;

            if response.status() == reqwest::StatusCode::TOO_MANY_REQUESTS {
                return Err(YahooError::TooManyRequests(format!(
                    "GET {} in get_crumb",
                    Y_GET_CRUMB_URL
                )));
            }
            let crumb = response.text().await?;
            let crumb = crumb.trim();

            if crumb.contains("Invalid Cookie") {
                self.cookie = Some(self.get_cookie().await?);
                last_error = YahooError::InvalidCookie;
                continue;
            }

            if crumb.contains("Too Many Requests") {
                last_error =
                    YahooError::TooManyRequests(format!("GET {} in get_crumb", Y_GET_CRUMB_URL));
                continue;
            }

            if crumb.is_empty() {
                last_error = YahooError::InvalidCrumb;
                continue;
            }

            return Ok(crumb.to_string());
        }

        Err(last_error)
    }

    async fn get_cookie(&mut self) -> Result<String, YahooError> {
        Ok(self
            .client
            .get(Y_GET_COOKIE_URL)
            .send()
            .await?
            .headers()
            .get(Y_COOKIE_REQUEST_HEADER)
            .ok_or(YahooError::NoCookies)?
            .to_str()
            .map_err(|_| YahooError::InvisibleAsciiInCookies)?
            .to_string())
    }

    async fn create_client(
        &self,
        cookie_provider: Option<Arc<reqwest::cookie::Jar>>,
    ) -> Result<Client, reqwest::Error> {
        let mut client_builder = Client::builder();

        if let Some(cookie_provider) = cookie_provider {
            client_builder = client_builder.cookie_provider(cookie_provider);
        }
        if let Some(timeout) = &self.timeout {
            client_builder = client_builder.timeout(*timeout);
        }
        if let Some(user_agent) = &self.user_agent {
            client_builder = client_builder.user_agent(user_agent.clone());
        }
        if let Some(proxy) = &self.proxy {
            client_builder = client_builder.proxy(proxy.clone());
        }

        client_builder.build()
    }

    /// Send request to yahoo! finance server and transform response to JSON value
    pub async fn send_request(&self, url: &str) -> Result<serde_json::Value, YahooError> {
        let response = self.client.get(url).send().await?.text().await?;

        let json = serde_json::from_str::<serde_json::Value>(&response)
            .map_err(|e| YahooError::DeserializeFailed(e.to_string()));

        if let Err(YahooError::DeserializeFailed(ref _e)) = json {
            let trimmed_response = response.trim();
            if trimmed_response.len() <= 4_000
                && trimmed_response
                    .to_lowercase()
                    .contains("too many requests")
            {
                Err(YahooError::TooManyRequests(format!("request url: {}", url)))?
            } else {
                #[cfg(feature = "debug")]
                if format!("{}", _e).contains("expected value") {
                    Err(YahooError::DeserializeFailedDebug(
                        trimmed_response.to_string(),
                    ))?
                }
            }
        }

        json
    }

    /// Fetch multiple symbols in parallel with automatic rate limiting
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use eeyf::{YahooConnector, batch::BatchQuoteRequest};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let provider = YahooConnector::new()?;
    ///     
    ///     let symbols = vec!["AAPL", "GOOGL", "MSFT", "AMZN", "TSLA"];
    ///     let batch = BatchQuoteRequest::new(symbols)
    ///         .with_concurrency(10)
    ///         .with_continue_on_error(true);
    ///     
    ///     let result = provider.batch_get_latest_quotes(&batch, "1d").await?;
    ///     
    ///     println!("Successfully fetched: {}/{}", result.successful, result.total);
    ///     println!("Success rate: {:.1}%", result.success_rate());
    ///     
    ///     for (symbol, response) in result.results {
    ///         if let Ok(quote) = response.last_quote() {
    ///             println!("{}: ${:.2}", symbol, quote.close);
    ///         }
    ///     }
    ///     
    ///     for (symbol, error) in result.errors {
    ///         eprintln!("{}: {}", symbol, error);
    ///     }
    ///     
    ///     Ok(())
    /// }
    /// ```
    pub async fn batch_get_latest_quotes(
        &self,
        request: &BatchQuoteRequest,
        interval: &str,
    ) -> Result<BatchResult<YResponse>, YahooError> {
        let interval = interval.to_string();
        let connector = self.clone();
        
        let fetch_fn = move |symbol: String| {
            let connector = connector.clone();
            let interval = interval.clone();
            async move { connector.get_latest_quotes(&symbol, &interval).await }
        };

        let batch_ops = BatchOperations::new(fetch_fn);
        Ok(batch_ops.execute(request.clone()).await)
    }

    /// Fetch quote history for multiple symbols in parallel
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use eeyf::{YahooConnector, batch::BatchQuoteRequest};
    /// use time::{macros::datetime};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let provider = YahooConnector::new()?;
    ///     
    ///     let symbols = vec!["AAPL", "GOOGL", "MSFT"];
    ///     let batch = BatchQuoteRequest::new(symbols).with_concurrency(5);
    ///     
    ///     let start = datetime!(2024-1-1 0:00:00.00 UTC);
    ///     let end = datetime!(2024-12-31 23:59:59.99 UTC);
    ///     
    ///     let result = provider.batch_get_quote_history(&batch, start, end).await?;
    ///     
    ///     for (symbol, response) in result.results {
    ///         if let Ok(quotes) = response.quotes() {
    ///             println!("{}: {} quotes", symbol, quotes.len());
    ///         }
    ///     }
    ///     
    ///     Ok(())
    /// }
    /// ```
    pub async fn batch_get_quote_history(
        &self,
        request: &BatchQuoteRequest,
        start: OffsetDateTime,
        end: OffsetDateTime,
    ) -> Result<BatchResult<YResponse>, YahooError> {
        let connector = self.clone();
        
        let fetch_fn = move |symbol: String| {
            let connector = connector.clone();
            async move { connector.get_quote_history(&symbol, start, end).await }
        };

        let batch_ops = BatchOperations::new(fetch_fn);
        Ok(batch_ops.execute(request.clone()).await)
    }

    /// Fetch quote ranges for multiple symbols in parallel
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use eeyf::{YahooConnector, batch::BatchQuoteRequest};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let provider = YahooConnector::new()?;
    ///     
    ///     let symbols = vec!["AAPL", "GOOGL", "MSFT", "AMZN"];
    ///     let batch = BatchQuoteRequest::new(symbols);
    ///     
    ///     let result = provider.batch_get_quote_range(&batch, "1d", "1mo").await?;
    ///     
    ///     println!("Fetched {} symbols successfully", result.successful);
    ///     
    ///     Ok(())
    /// }
    /// ```
    pub async fn batch_get_quote_range(
        &self,
        request: &BatchQuoteRequest,
        interval: &str,
        range: &str,
    ) -> Result<BatchResult<YResponse>, YahooError> {
        let interval = interval.to_string();
        let range = range.to_string();
        let connector = self.clone();
        
        let fetch_fn = move |symbol: String| {
            let connector = connector.clone();
            let interval = interval.clone();
            let range = range.clone();
            async move { connector.get_quote_range(&symbol, &interval, &range).await }
        };

        let batch_ops = BatchOperations::new(fetch_fn);
        Ok(batch_ops.execute(request.clone()).await)
    }

    /// Fetch search results for multiple queries in parallel
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use eeyf::{YahooConnector, batch::BatchQuoteRequest};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let provider = YahooConnector::new()?;
    ///     
    ///     let queries = vec!["Apple", "Google", "Microsoft"];
    ///     let batch = BatchQuoteRequest::new(queries);
    ///     
    ///     let result = provider.batch_search_ticker(&batch).await?;
    ///     
    ///     for (query, search_result) in result.results {
    ///         println!("{} found {} results", query, search_result.count);
    ///     }
    ///     
    ///     Ok(())
    /// }
    /// ```
    pub async fn batch_search_ticker(
        &self,
        request: &BatchQuoteRequest,
    ) -> Result<BatchResult<YSearchResult>, YahooError> {
        let connector = self.clone();
        
        let fetch_fn = move |query: String| {
            let connector = connector.clone();
            async move { connector.search_ticker(&query).await }
        };

        let batch_ops = BatchOperations::new(fetch_fn);
        Ok(batch_ops.execute(request.clone()).await)
    }
}

#[cfg(test)]
mod tests {
    use time::macros::datetime;

    use super::*;

    #[test]
    fn test_get_single_quote() {
        let provider = YahooConnector::new().unwrap();
        let response = tokio_test::block_on(provider.get_latest_quotes("HNL.DE", "1d")).unwrap();

        let result = &response.chart.result.as_ref().unwrap();
        assert_eq!(&result[0].meta.symbol, "HNL.DE");
        assert_eq!(&result[0].meta.range, "1mo");
        assert_eq!(&result[0].meta.data_granularity, "1d");
        let _ = response.last_quote().unwrap();
    }

    #[test]
    fn test_strange_api_responses() {
        let provider = YahooConnector::new().unwrap();

        let start = datetime!(2019-07-03 0:00:00.00 UTC);
        let end = datetime!(2020-07-04 23:59:59.99 UTC);

        let response = tokio_test::block_on(provider.get_quote_history("IBM", start, end)).unwrap();
        let result = &response.chart.result.as_ref().unwrap();

        assert_eq!(&result[0].meta.symbol, "IBM");
        assert_eq!(&result[0].meta.data_granularity, "1d");
        assert_eq!(&result[0].meta.first_trade_date, &Some(-252322200));

        let _ = response.last_quote().unwrap();
    }

    #[test]
    #[should_panic(expected = "NoQuotes")]
    fn test_api_responses_missing_fields() {
        let provider = YahooConnector::new().unwrap();
        let response = tokio_test::block_on(provider.get_latest_quotes("BF.B", "1m")).unwrap();
        let result = &response.chart.result.as_ref().unwrap();

        assert_eq!(&result[0].meta.symbol, "BF.B");
        let _ = response.last_quote().unwrap();
    }

    #[test]
    fn test_get_quote_history() {
        let provider = YahooConnector::new().unwrap();

        let start = datetime!(2020-01-01 0:00:00.00 UTC);
        let end = datetime!(2020-01-31 23:59:59.99 UTC);

        let response = tokio_test::block_on(provider.get_quote_history("AAPL", start, end));

        if response.is_ok() {
            let response = response.unwrap();
            let result = &response.chart.result.as_ref().unwrap();
            assert_eq!(result[0].timestamp.as_ref().unwrap().len(), 21);

            let quotes = response.quotes().unwrap();
            assert_eq!(quotes.len(), 21);
        }
    }

    #[test]
    fn test_get_quote_range() {
        let provider = YahooConnector::new().unwrap();
        let response =
            tokio_test::block_on(provider.get_quote_range("HNL.DE", "1d", "1mo")).unwrap();
        let result = &response.chart.result.as_ref().unwrap();

        assert_eq!(&result[0].meta.symbol, "HNL.DE");
        assert_eq!(&result[0].meta.range, "1mo");
        assert_eq!(&result[0].meta.data_granularity, "1d");
        let _ = response.last_quote().unwrap();
    }

    #[test]
    fn test_get_metadata() {
        let provider = YahooConnector::new().unwrap();
        let response =
            tokio_test::block_on(provider.get_quote_range("HNL.DE", "1d", "1mo")).unwrap();
        let metadata = response.metadata().unwrap();
        assert_eq!(metadata.symbol, "HNL.DE");
    }

    #[test]
    fn test_get_quote_history_interval() {
        let provider = YahooConnector::new().unwrap();

        let start = datetime!(2019-01-01 0:00:00.00 UTC);
        let end = datetime!(2020-01-31 23:59:59.99 UTC);

        let response =
            tokio_test::block_on(provider.get_quote_history_interval("AAPL", start, end, "1mo"))
                .unwrap();
        let result = &response.chart.result.as_ref().unwrap();

        assert_eq!(&result[0].timestamp.as_ref().unwrap().len(), &13);
        assert_eq!(&result[0].meta.data_granularity, "1mo");
        let quotes = response.quotes().unwrap();
        assert_eq!(quotes.len(), 13usize);
    }

    #[test]
    #[should_panic(expected = "ApiError")]
    fn test_wrong_request_get_quote_history_interval() {
        let provider = YahooConnector::new().unwrap();
        let end = OffsetDateTime::now_utc();
        let days = 365;
        let start = end - Duration::from_secs(days * 24 * 60 * 60);
        let interval = "5m";
        let ticker = "AAPL";
        let prepost = true;

        let _ = tokio_test::block_on(
            provider.get_quote_history_interval_prepost(ticker, start, end, interval, prepost),
        )
        .unwrap();
    }

    #[test]
    fn test_get_quote_period_interval() {
        let provider = YahooConnector::new().unwrap();

        let range = "5d";
        let interval = "5m";

        let response = tokio_test::block_on(
            provider.get_quote_period_interval("AAPL", &range, &interval, true),
        )
        .unwrap();

        let metadata = response.metadata().unwrap();

        assert_eq!(metadata.data_granularity, interval);
        assert_eq!(metadata.range, range);
    }

    #[test]
    fn test_large_volume() {
        let provider = YahooConnector::new().unwrap();
        let response =
            tokio_test::block_on(provider.get_quote_range("BTC-USD", "1d", "5d")).unwrap();
        let quotes = response.quotes().unwrap();
        assert!(quotes.len() > 0usize);
    }

    #[test]
    fn test_search_ticker() {
        let provider = YahooConnector::new().unwrap();
        let response = tokio_test::block_on(provider.search_ticker("Apple")).unwrap();

        assert_eq!(response.count, 15);
        let mut apple_found = false;
        for item in response.quotes {
            if item.exchange == "NMS" && item.symbol == "AAPL" && item.short_name == "Apple Inc." {
                apple_found = true;
                break;
            }
        }
        assert!(apple_found)
    }

    #[test]
    fn test_mutual_fund_history() {
        let provider = YahooConnector::new().unwrap();

        let start = datetime!(2020-01-01 0:00:00.00 UTC);
        let end = datetime!(2020-01-31 23:59:59.99 UTC);

        let response = tokio_test::block_on(provider.get_quote_history("VTSAX", start, end));

        if response.is_ok() {
            let response = response.unwrap();
            let result = &response.chart.result.as_ref().unwrap();

            assert_eq!(result[0].timestamp.as_ref().unwrap().len(), 21);

            let quotes = response.quotes().unwrap();
            assert_eq!(quotes.len(), 21);
        }
    }

    #[test]
    fn test_mutual_fund_latest() {
        let provider = YahooConnector::new().unwrap();
        let response = tokio_test::block_on(provider.get_latest_quotes("VTSAX", "1d")).unwrap();
        let result = &response.chart.result.as_ref().unwrap();

        assert_eq!(&result[0].meta.symbol, "VTSAX");
        assert_eq!(&result[0].meta.range, "1mo");
        assert_eq!(&result[0].meta.data_granularity, "1d");
        let _ = response.last_quote().unwrap();
    }

    #[test]
    fn test_mutual_fund_latest_with_null_first_trade_date() {
        let provider = YahooConnector::new().unwrap();
        let response = tokio_test::block_on(provider.get_latest_quotes("SIWA.F", "1d")).unwrap();
        let result = &response.chart.result.as_ref().unwrap();

        assert_eq!(&result[0].meta.symbol, "SIWA.F");
        assert_eq!(&result[0].meta.range, "1mo");
        assert_eq!(&result[0].meta.data_granularity, "1d");
        let _ = response.last_quote().unwrap();
    }

    #[test]
    fn test_mutual_fund_range() {
        let provider = YahooConnector::new().unwrap();
        let response =
            tokio_test::block_on(provider.get_quote_range("VTSAX", "1d", "1mo")).unwrap();
        let result = &response.chart.result.as_ref().unwrap();

        assert_eq!(&result[0].meta.symbol, "VTSAX");
        assert_eq!(&result[0].meta.range, "1mo");
        assert_eq!(&result[0].meta.data_granularity, "1d");
    }

    #[test]
    fn test_mutual_fund_capital_gains() {
        let provider = YahooConnector::new().unwrap();
        let response = tokio_test::block_on(provider.get_quote_range("AMAGX", "1d", "5y")).unwrap();
        let result = &response.chart.result.as_ref().unwrap();

        assert_eq!(&result[0].meta.symbol, "AMAGX");
        assert_eq!(&result[0].meta.range, "5y");
        assert_eq!(&result[0].meta.data_granularity, "1d");
        let capital_gains = response.capital_gains().unwrap();
        assert!(capital_gains.len() > 0usize);
    }

    #[test]
    fn test_get_ticker_info() {
        let mut provider = YahooConnector::new().unwrap();

        let result = tokio_test::block_on(provider.get_ticker_info("AAPL"));

        let quote_summary = result.unwrap().quote_summary.unwrap();
        assert!(
            "Cupertino"
                == quote_summary.result.as_ref().unwrap()[0]
                    .asset_profile
                    .as_ref()
                    .unwrap()
                    .city
                    .as_ref()
                    .unwrap()
        );
    }

    #[tokio::test]
    async fn test_get_crumb() {
        let mut provider = YahooConnector::new().unwrap();
        let crumb = provider.get_crumb().await.unwrap();

        assert!(crumb.len() > 5);
        assert!(crumb.len() < 16);
    }

    #[tokio::test]
    async fn test_get_cookie() {
        let mut provider = YahooConnector::new().unwrap();
        let cookie = provider.get_cookie().await.unwrap();

        assert!(cookie.len() > 30);
        assert!(
            cookie.contains("Expires")
                || cookie.contains("Max-Age")
                || cookie.contains("Domain")
                || cookie.contains("Path")
                || cookie.contains("Secure")
        );
    }

    #[tokio::test]
    async fn test_neg_time_stamp() {
        let start = datetime!(1960-01-01 0:00:00.00 UTC);
        let end = datetime!(2025-04-30 23:59:59.99 UTC);

        let provider = YahooConnector::new().unwrap();
        let response = provider.get_quote_history("XOM", start, end).await.unwrap();
        let quotes = response.quotes();
        assert!(!quotes.is_err());
        let quotes = quotes.unwrap();
        assert_eq!(quotes.len(), 15939);
    }

    #[test]
    fn test_get_financial_events() {
        let mut provider = YahooConnector::new().unwrap();
        let limit = 100;

        let result = tokio_test::block_on(provider.get_financial_events("AAPL", limit));

        if result.is_err() {
            println!("{:?}", result);
        }

        assert!(result.is_ok());
        let earnings = result.unwrap();

        assert_eq!(earnings.len() as u32, limit);
    }

    #[test]
    fn test_get_earnings_only() {
        let mut provider = YahooConnector::new().unwrap();
        let result = tokio_test::block_on(provider.get_earnings_only("AAPL", 100));

        assert!(result.is_ok());
        let earnings = result.unwrap();

        // All events should be earnings type
        for event in &earnings {
            assert_eq!(event.event_type, "Earnings");
        }
    }
}