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
//! SEC filings endpoints

use crate::{
    client::FmpClient,
    error::Result,
    models::sec_filings::{
        CikSearch, CompanyName, Form4, Form13F, InsiderOwnership, SecFiling, SecFilingRss,
    },
};
use serde::Serialize;

/// SEC Filings API endpoints
pub struct SecFilings {
    client: FmpClient,
}

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

    /// Get SEC filings for a symbol
    ///
    /// Returns SEC filings (10-K, 10-Q, 8-K, etc.) for a given stock symbol.
    ///
    /// # Arguments
    /// * `symbol` - Stock symbol (e.g., "AAPL")
    /// * `limit` - Maximum number of filings to return (optional)
    ///
    /// # Example
    /// ```no_run
    /// # use fmp_rs::FmpClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = FmpClient::new()?;
    /// let filings = client.sec_filings().get_sec_filings("AAPL", Some(10)).await?;
    /// for filing in filings {
    ///     println!("{}: {} on {}",
    ///         filing.symbol,
    ///         filing.filing_type.unwrap_or_default(),
    ///         filing.filing_date.unwrap_or_default());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_sec_filings(
        &self,
        symbol: &str,
        limit: Option<u32>,
    ) -> Result<Vec<SecFiling>> {
        #[derive(Serialize)]
        struct Query<'a> {
            #[serde(skip_serializing_if = "Option::is_none")]
            limit: Option<u32>,
            apikey: &'a str,
        }

        let url = self.client.build_url(&format!("/sec_filings/{}", symbol));
        self.client
            .get_with_query(
                &url,
                &Query {
                    limit,
                    apikey: self.client.api_key(),
                },
            )
            .await
    }

    /// Get SEC filings RSS feed
    ///
    /// Returns recent SEC filings from the RSS feed with optional filtering.
    ///
    /// # Arguments
    /// * `limit` - Maximum number of filings to return (optional)
    ///
    /// # Example
    /// ```no_run
    /// # use fmp_rs::FmpClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = FmpClient::new()?;
    /// let rss = client.sec_filings().get_sec_rss_feed(Some(20)).await?;
    /// for item in rss.iter().take(10) {
    ///     println!("{}: {} - {}",
    ///         item.symbol.as_deref().unwrap_or("N/A"),
    ///         item.form_type.as_deref().unwrap_or("N/A"),
    ///         item.title.as_deref().unwrap_or("N/A"));
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_sec_rss_feed(&self, limit: Option<u32>) -> Result<Vec<SecFilingRss>> {
        #[derive(Serialize)]
        struct Query<'a> {
            #[serde(skip_serializing_if = "Option::is_none")]
            limit: Option<u32>,
            apikey: &'a str,
        }

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

    /// Get Form 13F filings
    ///
    /// Returns institutional holdings from Form 13F filings.
    ///
    /// # Arguments
    /// * `cik` - CIK number of the institution
    /// * `date` - Filing date (optional, format: YYYY-MM-DD)
    ///
    /// # Example
    /// ```no_run
    /// # use fmp_rs::FmpClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = FmpClient::new()?;
    /// let holdings = client.sec_filings().get_form_13f("0001067983", None).await?;
    /// for holding in holdings.iter().take(10) {
    ///     println!("{}: {} shares valued at ${}",
    ///         holding.name_of_issuer.as_deref().unwrap_or("N/A"),
    ///         holding.shares.unwrap_or(0),
    ///         holding.market_value.unwrap_or(0.0));
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_form_13f(&self, cik: &str, date: Option<&str>) -> Result<Vec<Form13F>> {
        #[derive(Serialize)]
        struct Query<'a> {
            #[serde(skip_serializing_if = "Option::is_none")]
            date: Option<&'a str>,
            apikey: &'a str,
        }

        let url = self.client.build_url(&format!("/form-thirteen/{}", cik));
        self.client
            .get_with_query(
                &url,
                &Query {
                    date,
                    apikey: self.client.api_key(),
                },
            )
            .await
    }

    /// Get cusip mapper (CUSIP to company info)
    ///
    /// Returns company information for a given CUSIP.
    ///
    /// # Arguments
    /// * `cusip` - CUSIP identifier
    ///
    /// # Example
    /// ```no_run
    /// # use fmp_rs::FmpClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = FmpClient::new()?;
    /// let info = client.sec_filings().get_cusip_mapper("037833100").await?;
    /// for item in info {
    ///     println!("{}: {}", item.cik, item.name.unwrap_or_default());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_cusip_mapper(&self, cusip: &str) -> Result<Vec<CikSearch>> {
        #[derive(Serialize)]
        struct Query<'a> {
            apikey: &'a str,
        }

        let url = self.client.build_url(&format!("/cusip/{}", cusip));
        self.client
            .get_with_query(
                &url,
                &Query {
                    apikey: self.client.api_key(),
                },
            )
            .await
    }

    /// Search for CIK by company name
    ///
    /// Returns CIK numbers for companies matching the search query.
    ///
    /// # Arguments
    /// * `name` - Company name to search for
    ///
    /// # Example
    /// ```no_run
    /// # use fmp_rs::FmpClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = FmpClient::new()?;
    /// let results = client.sec_filings().search_cik("Apple").await?;
    /// for result in results {
    ///     println!("CIK {}: {}", result.cik, result.name.unwrap_or_default());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn search_cik(&self, name: &str) -> Result<Vec<CikSearch>> {
        #[derive(Serialize)]
        struct Query<'a> {
            name: &'a str,
            apikey: &'a str,
        }

        let url = self.client.build_url("/cik-search");
        self.client
            .get_with_query(
                &url,
                &Query {
                    name,
                    apikey: self.client.api_key(),
                },
            )
            .await
    }

    /// Get company name by CIK
    ///
    /// Returns the company name for a given CIK number.
    ///
    /// # Arguments
    /// * `cik` - CIK number
    ///
    /// # Example
    /// ```no_run
    /// # use fmp_rs::FmpClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = FmpClient::new()?;
    /// let company = client.sec_filings().get_company_name_by_cik("0000320193").await?;
    /// for c in company {
    ///     println!("CIK {}: {}", c.cik, c.name);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_company_name_by_cik(&self, cik: &str) -> Result<Vec<CompanyName>> {
        #[derive(Serialize)]
        struct Query<'a> {
            apikey: &'a str,
        }

        let url = self.client.build_url(&format!("/cik/{}", cik));
        self.client
            .get_with_query(
                &url,
                &Query {
                    apikey: self.client.api_key(),
                },
            )
            .await
    }

    /// Get Form 4 filings (insider ownership changes)
    ///
    /// Returns Form 4 filings showing changes in beneficial ownership by insiders.
    ///
    /// # Arguments
    /// * `symbol` - Stock symbol (e.g., "AAPL")
    /// * `limit` - Maximum number of filings to return (optional)
    ///
    /// # Example
    /// ```no_run
    /// # use fmp_rs::FmpClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = FmpClient::new()?;
    /// let form4 = client.sec_filings().get_form_4("AAPL", Some(20)).await?;
    /// for filing in form4 {
    ///     println!("{}: {} - {} shares at ${}",
    ///         filing.reporting_name.as_deref().unwrap_or("N/A"),
    ///         filing.transaction_type.as_deref().unwrap_or("N/A"),
    ///         filing.securities_transacted.unwrap_or(0.0),
    ///         filing.price.unwrap_or(0.0));
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_form_4(&self, symbol: &str, limit: Option<u32>) -> Result<Vec<Form4>> {
        #[derive(Serialize)]
        struct Query<'a> {
            #[serde(skip_serializing_if = "Option::is_none")]
            limit: Option<u32>,
            apikey: &'a str,
        }

        let url = self.client.build_url(&format!("/form-four/{}", symbol));
        self.client
            .get_with_query(
                &url,
                &Query {
                    limit,
                    apikey: self.client.api_key(),
                },
            )
            .await
    }

    /// Get insider ownership summary
    ///
    /// Returns a summary of insider ownership from Forms 3, 4, and 5.
    ///
    /// # Arguments
    /// * `symbol` - Stock symbol (e.g., "AAPL")
    /// * `limit` - Maximum number of records to return (optional)
    ///
    /// # Example
    /// ```no_run
    /// # use fmp_rs::FmpClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = FmpClient::new()?;
    /// let ownership = client.sec_filings().get_insider_ownership("AAPL", Some(10)).await?;
    /// for record in ownership {
    ///     println!("{}: owns {} shares",
    ///         record.reporting_name.as_deref().unwrap_or("N/A"),
    ///         record.securities_owned.unwrap_or(0));
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_insider_ownership(
        &self,
        symbol: &str,
        limit: Option<u32>,
    ) -> Result<Vec<InsiderOwnership>> {
        #[derive(Serialize)]
        struct Query<'a> {
            #[serde(skip_serializing_if = "Option::is_none")]
            limit: Option<u32>,
            apikey: &'a str,
        }

        let url = self
            .client
            .build_url(&format!("/insider-ownership/{}", symbol));
        self.client
            .get_with_query(
                &url,
                &Query {
                    limit,
                    apikey: self.client.api_key(),
                },
            )
            .await
    }
}

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

    // Golden path tests
    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_sec_filings() {
        let client = FmpClient::new().unwrap();
        let result = client.sec_filings().get_sec_filings("AAPL", Some(10)).await;
        assert!(result.is_ok());
        let filings = result.unwrap();
        assert!(!filings.is_empty());
        assert!(filings.len() <= 10);
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_sec_rss_feed() {
        let client = FmpClient::new().unwrap();
        let result = client.sec_filings().get_sec_rss_feed(Some(20)).await;
        assert!(result.is_ok());
        let rss = result.unwrap();
        assert!(!rss.is_empty());
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_search_cik() {
        let client = FmpClient::new().unwrap();
        let result = client.sec_filings().search_cik("Apple").await;
        assert!(result.is_ok());
        let results = result.unwrap();
        assert!(!results.is_empty());
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_form_4() {
        let client = FmpClient::new().unwrap();
        let result = client.sec_filings().get_form_4("AAPL", Some(10)).await;
        assert!(result.is_ok());
    }

    // Edge case tests
    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_sec_filings_no_limit() {
        let client = FmpClient::new().unwrap();
        let result = client.sec_filings().get_sec_filings("AAPL", None).await;
        assert!(result.is_ok());
        let filings = result.unwrap();
        assert!(!filings.is_empty());
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_search_cik_partial_match() {
        let client = FmpClient::new().unwrap();
        let result = client.sec_filings().search_cik("Tech").await;
        assert!(result.is_ok());
        // Should return multiple companies with "Tech" in name
    }

    // Error handling tests
    #[tokio::test]
    async fn test_invalid_api_key() {
        let client = FmpClient::builder()
            .api_key("invalid_key_12345")
            .build()
            .unwrap();
        let result = client.sec_filings().get_sec_filings("AAPL", Some(10)).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_invalid_symbol() {
        let client = FmpClient::new().unwrap();
        let result = client
            .sec_filings()
            .get_sec_filings("INVALID_XYZ123", Some(10))
            .await;
        assert!(result.is_ok());
        if let Ok(filings) = result {
            assert!(filings.is_empty());
        }
    }

    // Missing endpoint tests
    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_form_13f() {
        let client = FmpClient::new().unwrap();
        let result = client.sec_filings().get_form_13f("0000320193", None).await; // Apple's CIK
        assert!(result.is_ok());
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_form_13f_with_date() {
        let client = FmpClient::new().unwrap();
        let result = client
            .sec_filings()
            .get_form_13f("0000320193", Some("2023-12-31"))
            .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_cusip_mapper() {
        let client = FmpClient::new().unwrap();
        let result = client.sec_filings().get_cusip_mapper("037833100").await; // Apple CUSIP
        assert!(result.is_ok());
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_cusip_mapper_invalid() {
        let client = FmpClient::new().unwrap();
        let result = client.sec_filings().get_cusip_mapper("INVALID123").await;
        match result {
            Ok(results) => assert!(results.is_empty()),
            Err(_) => {} // Error is acceptable for invalid CUSIP
        }
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_company_name_by_cik() {
        let client = FmpClient::new().unwrap();
        let result = client
            .sec_filings()
            .get_company_name_by_cik("0000320193")
            .await; // Apple
        assert!(result.is_ok());
        let names = result.unwrap();
        if !names.is_empty() {
            assert!(
                names[0]
                    .name
                    .as_ref()
                    .map_or(false, |n| n.to_lowercase().contains("apple"))
            );
        }
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_company_name_by_invalid_cik() {
        let client = FmpClient::new().unwrap();
        let result = client
            .sec_filings()
            .get_company_name_by_cik("9999999999")
            .await;
        match result {
            Ok(names) => assert!(names.is_empty()),
            Err(_) => {} // Error is acceptable for invalid CIK
        }
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_insider_ownership() {
        let client = FmpClient::new().unwrap();
        let result = client
            .sec_filings()
            .get_insider_ownership("AAPL", Some(5))
            .await;
        assert!(result.is_ok());
        let ownership = result.unwrap();
        assert!(ownership.len() <= 5);
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_insider_ownership_no_limit() {
        let client = FmpClient::new().unwrap();
        let result = client
            .sec_filings()
            .get_insider_ownership("AAPL", None)
            .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    #[ignore = "requires FMP API key"]
    async fn test_get_insider_ownership_invalid_symbol() {
        let client = FmpClient::new().unwrap();
        let result = client
            .sec_filings()
            .get_insider_ownership("INVALID_SYMBOL_12345", Some(1))
            .await;
        match result {
            Ok(ownership) => assert!(ownership.is_empty()),
            Err(_) => {} // Error is acceptable for invalid symbol
        }
    }
}