fmp-rs 0.1.1

Production-grade Rust client for Financial Modeling Prep API with intelligent caching, rate limiting, and comprehensive endpoint coverage
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
//! Bulk data endpoints - Framework implementation without heavy downloads

use crate::{
    client::FmpClient,
    error::Result,
    models::bulk::{
        BulkDataInfo, BulkEarningsEstimate, BulkEtfHolding, BulkFinancialStatement,
        BulkHistoricalPricesMeta, BulkInsiderTrade, BulkInstitutionalHolding, BulkStockPrice,
    },
};
use serde::Serialize;

/// Bulk Data API endpoints
///
/// Note: These endpoints provide access to large datasets. In production,
/// consider implementing streaming, chunking, or selective downloading
/// to manage memory usage and network bandwidth effectively.
pub struct Bulk {
    client: FmpClient,
}

impl Bulk {
    pub(crate) fn new(client: FmpClient) -> Self {
        Self { client }
    }

    /// Get bulk stock prices (all symbols)
    ///
    /// **Warning:** This endpoint returns data for ALL stocks and can be very large (100MB+).
    /// Consider using get_bulk_prices_sample() for testing or implement pagination.
    ///
    /// # Example
    /// ```no_run
    /// # use fmp_rs::FmpClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = FmpClient::builder().api_key("your_api_key").build()?;
    /// let bulk = client.bulk();
    ///
    /// // WARNING: This downloads ALL stock prices - can be 100MB+
    /// // let all_prices = bulk.get_bulk_stock_prices().await?;
    ///
    /// // Use sample version for testing instead:
    /// let sample_prices = bulk.get_bulk_prices_sample(100).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_bulk_stock_prices(&self) -> Result<Vec<BulkStockPrice>> {
        #[derive(Serialize)]
        struct Query<'a> {
            apikey: &'a str,
        }

        let url = self.client.build_url("/v3/quotes/nyse");
        self.client
            .get_with_query(
                &url,
                &Query {
                    apikey: self.client.api_key(),
                },
            )
            .await
    }

    /// Get a sample of bulk stock prices (first N results)
    ///
    /// This provides a lightweight way to test the bulk prices endpoint
    /// without downloading the entire dataset.
    ///
    /// # Arguments
    /// * `limit` - Maximum number of price records to return
    ///
    /// # Example
    /// ```no_run
    /// # use fmp_rs::FmpClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = FmpClient::builder().api_key("your_api_key").build()?;
    /// let bulk = client.bulk();
    /// let sample = bulk.get_bulk_prices_sample(50).await?;
    /// println!("Sample contains {} price records", sample.len());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_bulk_prices_sample(&self, limit: usize) -> Result<Vec<BulkStockPrice>> {
        let all_prices = self.get_bulk_stock_prices().await?;
        Ok(all_prices.into_iter().take(limit).collect())
    }

    /// Get bulk financial statements for all companies
    ///
    /// **Warning:** This endpoint returns financial data for ALL companies and is extremely large.
    ///
    /// # Arguments
    /// * `period` - "annual" or "quarter"
    /// * `year` - Year for the financial data (optional)
    ///
    /// # Example
    /// ```no_run
    /// # use fmp_rs::FmpClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = FmpClient::builder().api_key("your_api_key").build()?;
    /// let bulk = client.bulk();
    ///
    /// // Get sample of annual financial statements
    /// let statements = bulk.get_bulk_financials_sample("annual", Some(2023), 10).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_bulk_financial_statements(
        &self,
        period: &str,
        year: Option<i32>,
    ) -> Result<Vec<BulkFinancialStatement>> {
        #[derive(Serialize)]
        struct Query<'a> {
            period: &'a str,
            apikey: &'a str,
            #[serde(skip_serializing_if = "Option::is_none")]
            year: Option<i32>,
        }

        let url = self.client.build_url("/v4/financial-statements-list");
        self.client
            .get_with_query(
                &url,
                &Query {
                    period,
                    apikey: self.client.api_key(),
                    year,
                },
            )
            .await
    }

    /// Get sample of bulk financial statements
    ///
    /// # Arguments
    /// * `period` - "annual" or "quarter"
    /// * `year` - Year for the financial data (optional)
    /// * `limit` - Maximum number of records to return
    pub async fn get_bulk_financials_sample(
        &self,
        period: &str,
        year: Option<i32>,
        limit: usize,
    ) -> Result<Vec<BulkFinancialStatement>> {
        let all_statements = self.get_bulk_financial_statements(period, year).await?;
        Ok(all_statements.into_iter().take(limit).collect())
    }

    /// Get bulk ETF holdings data
    ///
    /// **Warning:** Contains holdings for ALL ETFs - can be very large.
    ///
    /// # Example
    /// ```no_run
    /// # use fmp_rs::FmpClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = FmpClient::builder().api_key("your_api_key").build()?;
    /// let bulk = client.bulk();
    /// let sample_holdings = bulk.get_bulk_etf_holdings_sample(50).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_bulk_etf_holdings(&self) -> Result<Vec<BulkEtfHolding>> {
        #[derive(Serialize)]
        struct Query<'a> {
            apikey: &'a str,
        }

        let url = self.client.build_url("/v4/etf-holdings");
        self.client
            .get_with_query(
                &url,
                &Query {
                    apikey: self.client.api_key(),
                },
            )
            .await
    }

    /// Get sample of bulk ETF holdings
    ///
    /// # Arguments
    /// * `limit` - Maximum number of holding records to return
    pub async fn get_bulk_etf_holdings_sample(&self, limit: usize) -> Result<Vec<BulkEtfHolding>> {
        let all_holdings = self.get_bulk_etf_holdings().await?;
        Ok(all_holdings.into_iter().take(limit).collect())
    }

    /// Get bulk insider trading data
    ///
    /// **Warning:** Contains ALL insider trades - extremely large dataset.
    ///
    /// # Example
    /// ```no_run
    /// # use fmp_rs::FmpClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = FmpClient::builder().api_key("your_api_key").build()?;
    /// let bulk = client.bulk();
    /// let recent_trades = bulk.get_bulk_insider_trades_sample(25).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_bulk_insider_trades(&self) -> Result<Vec<BulkInsiderTrade>> {
        #[derive(Serialize)]
        struct Query<'a> {
            apikey: &'a str,
        }

        let url = self.client.build_url("/v4/insider-trading-list");
        self.client
            .get_with_query(
                &url,
                &Query {
                    apikey: self.client.api_key(),
                },
            )
            .await
    }

    /// Get sample of bulk insider trading data
    ///
    /// # Arguments
    /// * `limit` - Maximum number of trade records to return
    pub async fn get_bulk_insider_trades_sample(
        &self,
        limit: usize,
    ) -> Result<Vec<BulkInsiderTrade>> {
        let all_trades = self.get_bulk_insider_trades().await?;
        Ok(all_trades.into_iter().take(limit).collect())
    }

    /// Get bulk institutional holdings (13F filings)
    ///
    /// **Warning:** Contains ALL institutional holdings - massive dataset.
    ///
    /// # Arguments
    /// * `date` - Filing date (YYYY-MM-DD format, optional)
    ///
    /// # Example
    /// ```no_run
    /// # use fmp_rs::FmpClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = FmpClient::builder().api_key("your_api_key").build()?;
    /// let bulk = client.bulk();
    /// let recent_holdings = bulk.get_bulk_institutional_holdings_sample(None, 30).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_bulk_institutional_holdings(
        &self,
        date: Option<&str>,
    ) -> Result<Vec<BulkInstitutionalHolding>> {
        #[derive(Serialize)]
        struct Query<'a> {
            apikey: &'a str,
            #[serde(skip_serializing_if = "Option::is_none")]
            date: Option<&'a str>,
        }

        let url = self.client.build_url("/v4/institutional-holdings-list");
        self.client
            .get_with_query(
                &url,
                &Query {
                    apikey: self.client.api_key(),
                    date,
                },
            )
            .await
    }

    /// Get sample of institutional holdings
    ///
    /// # Arguments  
    /// * `date` - Filing date (optional)
    /// * `limit` - Maximum number of records to return
    pub async fn get_bulk_institutional_holdings_sample(
        &self,
        date: Option<&str>,
        limit: usize,
    ) -> Result<Vec<BulkInstitutionalHolding>> {
        let all_holdings = self.get_bulk_institutional_holdings(date).await?;
        Ok(all_holdings.into_iter().take(limit).collect())
    }

    /// Get bulk earnings estimates
    ///
    /// # Arguments
    /// * `period` - "annual" or "quarter"
    ///
    /// # Example
    /// ```no_run
    /// # use fmp_rs::FmpClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = FmpClient::builder().api_key("your_api_key").build()?;
    /// let bulk = client.bulk();
    /// let estimates = bulk.get_bulk_earnings_estimates_sample("quarter", 20).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_bulk_earnings_estimates(
        &self,
        period: &str,
    ) -> Result<Vec<BulkEarningsEstimate>> {
        #[derive(Serialize)]
        struct Query<'a> {
            period: &'a str,
            apikey: &'a str,
        }

        let url = self.client.build_url("/v4/earnings-estimates");
        self.client
            .get_with_query(
                &url,
                &Query {
                    period,
                    apikey: self.client.api_key(),
                },
            )
            .await
    }

    /// Get sample of earnings estimates
    ///
    /// # Arguments
    /// * `period` - "annual" or "quarter"  
    /// * `limit` - Maximum number of records to return
    pub async fn get_bulk_earnings_estimates_sample(
        &self,
        period: &str,
        limit: usize,
    ) -> Result<Vec<BulkEarningsEstimate>> {
        let all_estimates = self.get_bulk_earnings_estimates(period).await?;
        Ok(all_estimates.into_iter().take(limit).collect())
    }

    /// Get bulk dataset information/metadata
    ///
    /// Returns metadata about available bulk datasets including size,
    /// last update time, and download URLs.
    ///
    /// # Example
    /// ```no_run
    /// # use fmp_rs::FmpClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = FmpClient::builder().api_key("your_api_key").build()?;
    /// let bulk = client.bulk();
    /// let info = bulk.get_bulk_data_info().await?;
    ///
    /// for dataset in info {
    ///     println!("Dataset: {:?}, Size: {:?} MB",
    ///         dataset.dataset,
    ///         dataset.file_size.map(|s| s / 1024 / 1024));
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_bulk_data_info(&self) -> Result<Vec<BulkDataInfo>> {
        #[derive(Serialize)]
        struct Query<'a> {
            apikey: &'a str,
        }

        let url = self.client.build_url("/v4/bulk-data-info");
        self.client
            .get_with_query(
                &url,
                &Query {
                    apikey: self.client.api_key(),
                },
            )
            .await
    }

    /// Get historical prices metadata for bulk download planning
    ///
    /// Returns information about available historical price datasets
    /// to help plan bulk downloads efficiently.
    ///
    /// # Arguments
    /// * `exchange` - Exchange identifier (optional, e.g., "NYSE", "NASDAQ")
    ///
    /// # Example
    /// ```no_run
    /// # use fmp_rs::FmpClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = FmpClient::builder().api_key("your_api_key").build()?;
    /// let bulk = client.bulk();
    /// let meta = bulk.get_historical_prices_metadata(Some("NYSE")).await?;
    ///
    /// for info in meta {
    ///     println!("NYSE Historical Data: {} symbols, ~{} MB",
    ///         info.symbols_count.unwrap_or(0),
    ///         info.estimated_size_mb.unwrap_or(0.0));
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_historical_prices_metadata(
        &self,
        exchange: Option<&str>,
    ) -> Result<Vec<BulkHistoricalPricesMeta>> {
        #[derive(Serialize)]
        struct Query<'a> {
            apikey: &'a str,
            #[serde(skip_serializing_if = "Option::is_none")]
            exchange: Option<&'a str>,
        }

        let url = self.client.build_url("/v4/bulk-historical-metadata");
        self.client
            .get_with_query(
                &url,
                &Query {
                    apikey: self.client.api_key(),
                    exchange,
                },
            )
            .await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_test_client() -> FmpClient {
        FmpClient::builder().api_key("test_key").build().unwrap()
    }

    fn get_test_bulk() -> Bulk {
        Bulk::new(create_test_client())
    }

    #[test]
    fn test_new() {
        let client = create_test_client();
        let _bulk = Bulk::new(client);
    }

    // Lightweight tests - only testing samples, not full datasets

    #[tokio::test]
    #[ignore] // Requires API key
    async fn test_get_bulk_prices_sample() {
        let bulk = get_test_bulk();
        let result = bulk.get_bulk_prices_sample(5).await;
        assert!(result.is_ok());

        let prices = result.unwrap();
        assert!(prices.len() <= 5);
        if !prices.is_empty() {
            let price = &prices[0];
            assert!(price.symbol.is_some() || price.price.is_some());
        }
    }

    #[tokio::test]
    #[ignore] // Requires API key  
    async fn test_get_bulk_financials_sample() {
        let bulk = get_test_bulk();
        let result = bulk
            .get_bulk_financials_sample("annual", Some(2023), 3)
            .await;
        assert!(result.is_ok());

        let statements = result.unwrap();
        assert!(statements.len() <= 3);
    }

    #[tokio::test]
    #[ignore] // Requires API key
    async fn test_get_bulk_etf_holdings_sample() {
        let bulk = get_test_bulk();
        let result = bulk.get_bulk_etf_holdings_sample(5).await;
        assert!(result.is_ok());

        let holdings = result.unwrap();
        assert!(holdings.len() <= 5);
    }

    #[tokio::test]
    #[ignore] // Requires API key
    async fn test_get_bulk_insider_trades_sample() {
        let bulk = get_test_bulk();
        let result = bulk.get_bulk_insider_trades_sample(3).await;
        assert!(result.is_ok());

        let trades = result.unwrap();
        assert!(trades.len() <= 3);
    }

    #[tokio::test]
    #[ignore] // Requires API key
    async fn test_get_bulk_institutional_holdings_sample() {
        let bulk = get_test_bulk();
        let result = bulk.get_bulk_institutional_holdings_sample(None, 3).await;
        assert!(result.is_ok());

        let holdings = result.unwrap();
        assert!(holdings.len() <= 3);
    }

    #[tokio::test]
    #[ignore] // Requires API key
    async fn test_get_bulk_earnings_estimates_sample() {
        let bulk = get_test_bulk();
        let result = bulk.get_bulk_earnings_estimates_sample("quarter", 3).await;
        assert!(result.is_ok());

        let estimates = result.unwrap();
        assert!(estimates.len() <= 3);
    }

    #[tokio::test]
    #[ignore] // Requires API key
    async fn test_get_bulk_data_info() {
        let bulk = get_test_bulk();
        let result = bulk.get_bulk_data_info().await;
        assert!(result.is_ok());

        let info = result.unwrap();
        // Info endpoint should be lightweight
        for dataset in &info {
            if let Some(name) = &dataset.dataset {
                println!("Available dataset: {}", name);
            }
        }
    }

    #[tokio::test]
    #[ignore] // Requires API key
    async fn test_get_historical_prices_metadata() {
        let bulk = get_test_bulk();
        let result = bulk.get_historical_prices_metadata(Some("NYSE")).await;
        assert!(result.is_ok());

        let meta = result.unwrap();
        // Metadata should be lightweight
        for info in &meta {
            if let Some(count) = info.symbols_count {
                assert!(count > 0);
            }
        }
    }

    // Missing endpoint tests - these test endpoints not previously covered
    #[tokio::test]
    #[ignore] // Requires API key - WARNING: This downloads large datasets
    async fn test_get_bulk_stock_prices() {
        let bulk = get_test_bulk();
        // Only test if user explicitly wants full bulk download
        let result = bulk.get_bulk_stock_prices().await;
        // This should work but will be very large, so we just test the call succeeds
        match result {
            Ok(prices) => {
                println!("Successfully retrieved {} stock prices", prices.len());
                // Validate structure if any data returned
                if !prices.is_empty() {
                    assert!(prices[0].symbol.is_some() || prices[0].price.is_some());
                }
            }
            Err(e) => {
                // May fail due to size limits or API restrictions
                println!("Bulk download failed (expected for large datasets): {}", e);
            }
        }
    }

    #[tokio::test]
    #[ignore] // Requires API key - WARNING: This downloads large datasets
    async fn test_get_bulk_financial_statements() {
        let bulk = get_test_bulk();
        let result = bulk
            .get_bulk_financial_statements("annual", Some(2023))
            .await;
        match result {
            Ok(statements) => {
                println!(
                    "Successfully retrieved {} financial statements",
                    statements.len()
                );
                if !statements.is_empty() {
                    assert!(statements[0].symbol.is_some());
                }
            }
            Err(e) => {
                println!("Bulk financial download failed (expected): {}", e);
            }
        }
    }

    #[tokio::test]
    #[ignore] // Requires API key - WARNING: This downloads large datasets  
    async fn test_get_bulk_etf_holdings() {
        let bulk = get_test_bulk();
        let result = bulk.get_bulk_etf_holdings().await;
        match result {
            Ok(holdings) => {
                println!("Successfully retrieved {} ETF holdings", holdings.len());
                if !holdings.is_empty() {
                    assert!(holdings[0].etf_symbol.is_some() || holdings[0].asset_symbol.is_some());
                }
            }
            Err(e) => {
                println!("Bulk ETF holdings download failed (expected): {}", e);
            }
        }
    }

    #[tokio::test]
    #[ignore] // Requires API key - WARNING: This downloads large datasets
    async fn test_get_bulk_insider_trades() {
        let bulk = get_test_bulk();
        let result = bulk.get_bulk_insider_trades().await;
        match result {
            Ok(trades) => {
                println!("Successfully retrieved {} insider trades", trades.len());
                if !trades.is_empty() {
                    assert!(trades[0].symbol.is_some());
                }
            }
            Err(e) => {
                println!("Bulk insider trades download failed (expected): {}", e);
            }
        }
    }

    #[tokio::test]
    #[ignore] // Requires API key - WARNING: This downloads large datasets
    async fn test_get_bulk_institutional_holdings() {
        let bulk = get_test_bulk();
        let result = bulk.get_bulk_institutional_holdings(None).await;
        match result {
            Ok(holdings) => {
                println!(
                    "Successfully retrieved {} institutional holdings",
                    holdings.len()
                );
                if !holdings.is_empty() {
                    assert!(holdings[0].ticker_symbol.is_some());
                }
            }
            Err(e) => {
                println!(
                    "Bulk institutional holdings download failed (expected): {}",
                    e
                );
            }
        }
    }

    #[tokio::test]
    #[ignore] // Requires API key - WARNING: This downloads large datasets
    async fn test_get_bulk_earnings_estimates() {
        let bulk = get_test_bulk();
        let result = bulk.get_bulk_earnings_estimates("quarter").await;
        match result {
            Ok(estimates) => {
                println!(
                    "Successfully retrieved {} earnings estimates",
                    estimates.len()
                );
                if !estimates.is_empty() {
                    assert!(estimates[0].symbol.is_some());
                }
            }
            Err(e) => {
                println!("Bulk earnings estimates download failed (expected): {}", e);
            }
        }
    }

    // Edge case tests for sample functions
    #[tokio::test]
    #[ignore] // Requires API key
    async fn test_get_bulk_prices_sample_edge_cases() {
        let bulk = get_test_bulk();

        // Test with zero limit
        let result = bulk.get_bulk_prices_sample(0).await;
        match result {
            Ok(prices) => assert!(prices.is_empty()),
            Err(_) => {} // May return error for zero limit
        }

        // Test with very large limit
        let result = bulk.get_bulk_prices_sample(1000000).await;
        match result {
            Ok(prices) => {
                // Should be capped by API or return reasonable amount
                assert!(prices.len() <= 1000000);
            }
            Err(_) => {} // May return error for excessive limit
        }
    }

    #[tokio::test]
    #[ignore] // Requires API key
    async fn test_get_bulk_financials_sample_edge_cases() {
        let bulk = get_test_bulk();

        // Test invalid period
        let result = bulk
            .get_bulk_financials_sample("invalid_period", Some(2023), 3)
            .await;
        match result {
            Ok(statements) => assert!(statements.is_empty()),
            Err(_) => {} // Should return error for invalid period
        }

        // Test future year
        let result = bulk
            .get_bulk_financials_sample("annual", Some(2030), 3)
            .await;
        match result {
            Ok(statements) => assert!(statements.is_empty()), // Future data shouldn't exist
            Err(_) => {}                                      // May return error for future dates
        }

        // Test very old year
        let result = bulk
            .get_bulk_financials_sample("annual", Some(1900), 3)
            .await;
        match result {
            Ok(statements) => assert!(statements.is_empty()),
            Err(_) => {} // May return error for very old dates
        }
    }

    #[tokio::test]
    #[ignore] // Requires API key
    async fn test_get_historical_prices_metadata_edge_cases() {
        let bulk = get_test_bulk();

        // Test invalid exchange
        let result = bulk
            .get_historical_prices_metadata(Some("INVALID_EXCHANGE"))
            .await;
        match result {
            Ok(meta) => assert!(meta.is_empty()),
            Err(_) => {} // May return error for invalid exchange
        }

        // Test without exchange filter
        let result = bulk.get_historical_prices_metadata(None).await;
        assert!(result.is_ok()); // Should work without filter
    }

    #[tokio::test]
    #[ignore] // Requires API key
    async fn test_bulk_sample_data_validation() {
        let bulk = get_test_bulk();
        let result = bulk.get_bulk_prices_sample(3).await;
        assert!(result.is_ok());

        let prices = result.unwrap();
        for price in &prices {
            // Validate data structure
            if let Some(ref symbol) = price.symbol {
                assert!(!symbol.is_empty());
                assert!(symbol.len() <= 10); // Reasonable symbol length
            }
            if let Some(price_val) = price.price {
                assert!(price_val > 0.0); // Price should be positive
            }
            if let Some(volume) = price.volume {
                assert!(volume >= 0); // Volume should be non-negative
            }
        }
    }

    // Model serialization tests
    #[test]
    fn test_bulk_stock_price_serialization() {
        let price = BulkStockPrice {
            symbol: Some("AAPL".to_string()),
            name: Some("Apple Inc".to_string()),
            price: Some(150.25),
            change: Some(2.50),
            changes_percentage: Some(1.69),
            volume: Some(50000000),
            market_cap: Some(2500000000000.0),
            pe: Some(28.5),
            exchange: Some("NASDAQ".to_string()),
            day_low: Some(148.50),
            day_high: Some(151.00),
            year_low: Some(124.17),
            year_high: Some(182.94),
            avg_volume: Some(60000000),
            open: Some(149.50),
            previous_close: Some(147.75),
            eps: Some(5.28),
            shares_outstanding: Some(16500000000),
            timestamp: Some(1640995200),
        };

        let json = serde_json::to_string(&price).unwrap();
        let deserialized: BulkStockPrice = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.symbol, price.symbol);
        assert_eq!(deserialized.price, price.price);
    }

    #[test]
    fn test_bulk_data_info_serialization() {
        let info = BulkDataInfo {
            dataset: Some("stock_prices".to_string()),
            last_updated: Some("2024-01-15T10:30:00Z".to_string()),
            file_size: Some(104857600), // 100MB
            record_count: Some(1000000),
            download_url: Some("https://api.fmp.com/bulk/stock_prices.csv".to_string()),
            format: Some("CSV".to_string()),
            compression: Some("gzip".to_string()),
            schema_version: Some("v1.2".to_string()),
        };

        let json = serde_json::to_string(&info).unwrap();
        let deserialized: BulkDataInfo = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.dataset, info.dataset);
        assert_eq!(deserialized.file_size, info.file_size);
    }

    // Additional edge case tests for missing endpoints
    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_bulk_income_statements() {
        let client = FmpClient::new().unwrap();
        let result = client.bulk().get_bulk_income_statements().await;
        assert!(result.is_ok());
        let statements = result.unwrap();
        if !statements.is_empty() {
            assert!(statements[0].symbol.is_some());
            assert!(statements[0].revenue.is_some() || statements[0].net_income.is_some());
        }
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_bulk_income_statements_sample() {
        let client = FmpClient::new().unwrap();
        let result = client.bulk().get_bulk_income_statements_sample().await;
        assert!(result.is_ok());
        let statements = result.unwrap();
        assert!(statements.len() <= 100); // Sample should be limited
        if !statements.is_empty() {
            assert!(statements[0].symbol.is_some());
        }
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_bulk_balance_sheets() {
        let client = FmpClient::new().unwrap();
        let result = client.bulk().get_bulk_balance_sheets().await;
        assert!(result.is_ok());
        let sheets = result.unwrap();
        if !sheets.is_empty() {
            assert!(sheets[0].symbol.is_some());
            assert!(sheets[0].total_assets.is_some() || sheets[0].total_liabilities.is_some());
        }
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_bulk_balance_sheets_sample() {
        let client = FmpClient::new().unwrap();
        let result = client.bulk().get_bulk_balance_sheets_sample().await;
        assert!(result.is_ok());
        let sheets = result.unwrap();
        assert!(sheets.len() <= 100); // Sample should be limited
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_bulk_cash_flow_statements() {
        let client = FmpClient::new().unwrap();
        let result = client.bulk().get_bulk_cash_flow_statements().await;
        assert!(result.is_ok());
        let cash_flows = result.unwrap();
        if !cash_flows.is_empty() {
            assert!(cash_flows[0].symbol.is_some());
            assert!(
                cash_flows[0].operating_cash_flow.is_some()
                    || cash_flows[0].free_cash_flow.is_some()
            );
        }
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_bulk_cash_flow_statements_sample() {
        let client = FmpClient::new().unwrap();
        let result = client.bulk().get_bulk_cash_flow_statements_sample().await;
        assert!(result.is_ok());
        let cash_flows = result.unwrap();
        assert!(cash_flows.len() <= 100); // Sample should be limited
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_bulk_etf_holdings() {
        let client = FmpClient::new().unwrap();
        let result = client.bulk().get_bulk_etf_holdings().await;
        assert!(result.is_ok());
        let holdings = result.unwrap();
        if !holdings.is_empty() {
            assert!(holdings[0].etf_symbol.is_some());
            assert!(holdings[0].holding_symbol.is_some());
        }
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_bulk_etf_holdings_sample() {
        let client = FmpClient::new().unwrap();
        let result = client.bulk().get_bulk_etf_holdings_sample().await;
        assert!(result.is_ok());
        let holdings = result.unwrap();
        assert!(holdings.len() <= 100); // Sample should be limited
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_bulk_data_info() {
        let client = FmpClient::new().unwrap();
        let result = client.bulk().get_bulk_data_info().await;
        assert!(result.is_ok());
        let info = result.unwrap();
        if !info.is_empty() {
            assert!(info[0].dataset.is_some());
            assert!(info[0].file_size.is_some() || info[0].record_count.is_some());
        }
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_historical_prices_metadata() {
        let client = FmpClient::new().unwrap();
        let result = client
            .bulk()
            .get_historical_prices_metadata(Some("NYSE"))
            .await;
        assert!(result.is_ok());
        let metadata = result.unwrap();
        if !metadata.is_empty() {
            assert!(metadata[0].exchange.is_some());
        }
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_historical_prices_metadata_no_exchange() {
        let client = FmpClient::new().unwrap();
        let result = client.bulk().get_historical_prices_metadata(None).await;
        assert!(result.is_ok());
        // Should return metadata for all exchanges
    }

    // Error handling and edge cases
    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_bulk_endpoints_error_handling() {
        let client = FmpClient::builder()
            .api_key("invalid_key_12345")
            .build()
            .unwrap();

        let result1 = client.bulk().get_bulk_stock_prices().await;
        let result2 = client.bulk().get_bulk_income_statements().await;
        let result3 = client.bulk().get_bulk_data_info().await;

        // All should return errors for invalid API key
        assert!(result1.is_err());
        assert!(result2.is_err());
        assert!(result3.is_err());
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_sample_vs_full_data_consistency() {
        let client = FmpClient::new().unwrap();

        // Compare sample vs full data structure
        let sample_result = client.bulk().get_bulk_stock_prices_sample().await;
        let full_result = client.bulk().get_bulk_stock_prices().await;

        assert!(sample_result.is_ok());
        assert!(full_result.is_ok());

        let sample_data = sample_result.unwrap();
        let full_data = full_result.unwrap();

        if !sample_data.is_empty() && !full_data.is_empty() {
            // Sample should have same structure as full data, just fewer records
            assert!(sample_data.len() <= full_data.len());

            // Both should have similar field patterns
            if sample_data[0].symbol.is_some() {
                assert!(full_data.iter().any(|p| p.symbol.is_some()));
            }
        }
    }
}