libfmp 0.12.0

Async, typed Rust client for the Financial Modeling Prep 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
//! Institutional-ownership filing endpoints and query contracts.

use crate::{
    Client, Result,
    endpoints::{
        EndpointSpec, QueryEncoder, QueryParameters,
        metadata::{EndpointBounds, EndpointMetadata, GeographicAvailability},
    },
    query::{Quarter, Year},
    responses::institutional_ownership::{
        Form13fFilingDate, HolderIndustryBreakdown, HolderPerformanceSummary,
        InstitutionalHolderAnalytics, InstitutionalHolding, InstitutionalIndustrySummary,
        InstitutionalOwnershipFiling, InstitutionalPositionSummary,
    },
    types::{Cik, Limit, Page, Ticker},
};

/// Optional page and limit for the latest institutional-ownership filings.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct LatestInstitutionalOwnershipFilingsQuery {
    page: Option<Page>,
    limit: Option<Limit>,
}

impl LatestInstitutionalOwnershipFilingsQuery {
    /// Creates a query without undocumented page or limit defaults.
    pub const fn new() -> Self {
        Self {
            page: None,
            limit: None,
        }
    }

    /// Sets the optional provider page index.
    pub const fn with_page(mut self, page: Page) -> Self {
        self.page = Some(page);
        self
    }

    /// Sets the optional provider result limit.
    pub const fn with_limit(mut self, limit: Limit) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Returns the optional provider page index.
    pub const fn page(&self) -> Option<Page> {
        self.page
    }

    /// Returns the optional provider result limit.
    pub const fn limit(&self) -> Option<Limit> {
        self.limit
    }
}

impl QueryParameters for LatestInstitutionalOwnershipFilingsQuery {
    fn encode(&self, encoder: &mut QueryEncoder<'_>) {
        encoder.optional("page", self.page);
        encoder.optional("limit", self.limit);
    }
}

/// Required filing identity for extracting one institutional holder's positions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstitutionalOwnershipExtractQuery {
    cik: Cik,
    year: Year,
    quarter: Quarter,
}

impl InstitutionalOwnershipExtractQuery {
    /// Creates a query for one CIK, query year, and textual query quarter.
    pub const fn new(cik: Cik, year: Year, quarter: Quarter) -> Self {
        Self { cik, year, quarter }
    }

    /// Borrows the required Central Index Key.
    pub const fn cik(&self) -> &Cik {
        &self.cik
    }

    /// Returns the required provider query year.
    pub const fn year(&self) -> Year {
        self.year
    }

    /// Returns the required textual provider query quarter.
    pub const fn quarter(&self) -> Quarter {
        self.quarter
    }
}

impl QueryParameters for InstitutionalOwnershipExtractQuery {
    fn encode(&self, encoder: &mut QueryEncoder<'_>) {
        encoder.required("cik", &self.cik);
        encoder.required("year", self.year);
        encoder.required("quarter", self.quarter);
    }
}

/// Required CIK for retrieving available Form 13F filing dates.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Form13fFilingDatesQuery {
    cik: Cik,
}

impl Form13fFilingDatesQuery {
    /// Creates a query for one Central Index Key.
    pub const fn new(cik: Cik) -> Self {
        Self { cik }
    }

    /// Borrows the required Central Index Key.
    pub const fn cik(&self) -> &Cik {
        &self.cik
    }
}

impl From<Cik> for Form13fFilingDatesQuery {
    fn from(cik: Cik) -> Self {
        Self::new(cik)
    }
}

impl From<&Cik> for Form13fFilingDatesQuery {
    fn from(cik: &Cik) -> Self {
        Self::new(cik.clone())
    }
}

impl QueryParameters for Form13fFilingDatesQuery {
    fn encode(&self, encoder: &mut QueryEncoder<'_>) {
        encoder.required("cik", &self.cik);
    }
}

/// Required security period and optional pagination for holder analytics.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstitutionalHolderAnalyticsQuery {
    symbol: Ticker,
    year: Year,
    quarter: Quarter,
    page: Option<Page>,
    limit: Option<Limit>,
}

impl InstitutionalHolderAnalyticsQuery {
    /// Creates a query for one security and reporting period.
    pub fn new(symbol: Ticker, year: Year, quarter: Quarter) -> Self {
        Self {
            symbol,
            year,
            quarter,
            page: None,
            limit: None,
        }
    }

    /// Sets the optional provider page index.
    pub const fn with_page(mut self, page: Page) -> Self {
        self.page = Some(page);
        self
    }

    /// Sets the optional provider result limit.
    pub const fn with_limit(mut self, limit: Limit) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Borrows the required security ticker.
    pub const fn symbol(&self) -> &Ticker {
        &self.symbol
    }

    /// Returns the required provider query year.
    pub const fn year(&self) -> Year {
        self.year
    }

    /// Returns the required textual provider query quarter.
    pub const fn quarter(&self) -> Quarter {
        self.quarter
    }

    /// Returns the optional provider page index.
    pub const fn page(&self) -> Option<Page> {
        self.page
    }

    /// Returns the optional provider result limit.
    pub const fn limit(&self) -> Option<Limit> {
        self.limit
    }
}

impl QueryParameters for InstitutionalHolderAnalyticsQuery {
    fn encode(&self, encoder: &mut QueryEncoder<'_>) {
        encoder.required("symbol", &self.symbol);
        encoder.required("year", self.year);
        encoder.required("quarter", self.quarter);
        encoder.optional("page", self.page);
        encoder.optional("limit", self.limit);
    }
}

/// Required holder CIK and optional pagination for performance summaries.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HolderPerformanceSummaryQuery {
    cik: Cik,
    page: Option<Page>,
}

impl HolderPerformanceSummaryQuery {
    /// Creates a query for one Central Index Key without a page default.
    pub const fn new(cik: Cik) -> Self {
        Self { cik, page: None }
    }

    /// Sets the optional provider page index.
    pub const fn with_page(mut self, page: Page) -> Self {
        self.page = Some(page);
        self
    }

    /// Borrows the required Central Index Key.
    pub const fn cik(&self) -> &Cik {
        &self.cik
    }

    /// Returns the optional provider page index.
    pub const fn page(&self) -> Option<Page> {
        self.page
    }
}

impl From<Cik> for HolderPerformanceSummaryQuery {
    fn from(cik: Cik) -> Self {
        Self::new(cik)
    }
}

impl From<&Cik> for HolderPerformanceSummaryQuery {
    fn from(cik: &Cik) -> Self {
        Self::new(cik.clone())
    }
}

impl QueryParameters for HolderPerformanceSummaryQuery {
    fn encode(&self, encoder: &mut QueryEncoder<'_>) {
        encoder.required("cik", &self.cik);
        encoder.optional("page", self.page);
    }
}

/// Required holder CIK and reporting period for an industry breakdown.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HolderIndustryBreakdownQuery {
    cik: Cik,
    year: Year,
    quarter: Quarter,
}

impl HolderIndustryBreakdownQuery {
    /// Creates a query for one holder and reporting period.
    pub const fn new(cik: Cik, year: Year, quarter: Quarter) -> Self {
        Self { cik, year, quarter }
    }

    /// Borrows the required Central Index Key.
    pub const fn cik(&self) -> &Cik {
        &self.cik
    }

    /// Returns the required provider query year.
    pub const fn year(&self) -> Year {
        self.year
    }

    /// Returns the required textual provider query quarter.
    pub const fn quarter(&self) -> Quarter {
        self.quarter
    }
}

impl QueryParameters for HolderIndustryBreakdownQuery {
    fn encode(&self, encoder: &mut QueryEncoder<'_>) {
        encoder.required("cik", &self.cik);
        encoder.required("year", self.year);
        encoder.required("quarter", self.quarter);
    }
}

/// Required security and reporting period for a cross-holder position summary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstitutionalPositionsSummaryQuery {
    symbol: Ticker,
    year: Year,
    quarter: Quarter,
}

impl InstitutionalPositionsSummaryQuery {
    /// Creates a query for one security and reporting period.
    pub fn new(symbol: Ticker, year: Year, quarter: Quarter) -> Self {
        Self {
            symbol,
            year,
            quarter,
        }
    }

    /// Borrows the required security ticker.
    pub const fn symbol(&self) -> &Ticker {
        &self.symbol
    }

    /// Returns the required provider query year.
    pub const fn year(&self) -> Year {
        self.year
    }

    /// Returns the required textual provider query quarter.
    pub const fn quarter(&self) -> Quarter {
        self.quarter
    }
}

impl QueryParameters for InstitutionalPositionsSummaryQuery {
    fn encode(&self, encoder: &mut QueryEncoder<'_>) {
        encoder.required("symbol", &self.symbol);
        encoder.required("year", self.year);
        encoder.required("quarter", self.quarter);
    }
}

/// Required reporting period for the cross-holder industry summary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InstitutionalIndustrySummaryQuery {
    year: Year,
    quarter: Quarter,
}

impl InstitutionalIndustrySummaryQuery {
    /// Creates a query for one reporting period.
    pub const fn new(year: Year, quarter: Quarter) -> Self {
        Self { year, quarter }
    }

    /// Returns the required provider query year.
    pub const fn year(&self) -> Year {
        self.year
    }

    /// Returns the required textual provider query quarter.
    pub const fn quarter(&self) -> Quarter {
        self.quarter
    }
}

impl QueryParameters for InstitutionalIndustrySummaryQuery {
    fn encode(&self, encoder: &mut QueryEncoder<'_>) {
        encoder.required("year", self.year);
        encoder.required("quarter", self.quarter);
    }
}

const US_ONLY: EndpointMetadata =
    EndpointMetadata::new().with_geography(GeographicAvailability::UsOnly);
const LATEST_FILINGS_METADATA: EndpointMetadata =
    US_ONLY.with_bounds(EndpointBounds::new().with_page(100));

/// Describes `GET institutional-ownership/latest` without binding a transport.
pub fn latest_institutional_ownership_filings(
    query: LatestInstitutionalOwnershipFilingsQuery,
) -> EndpointSpec<LatestInstitutionalOwnershipFilingsQuery, Vec<InstitutionalOwnershipFiling>> {
    EndpointSpec::get(
        "institutional-ownership/latest",
        "institutional-ownership/latest",
        query,
    )
    .with_metadata(LATEST_FILINGS_METADATA)
}

/// Describes `GET institutional-ownership/extract` without binding a transport.
pub fn institutional_ownership_extract(
    query: InstitutionalOwnershipExtractQuery,
) -> EndpointSpec<InstitutionalOwnershipExtractQuery, Vec<InstitutionalHolding>> {
    EndpointSpec::get(
        "institutional-ownership/extract",
        "institutional-ownership/extract",
        query,
    )
    .with_metadata(US_ONLY)
}

/// Describes `GET institutional-ownership/dates` without binding a transport.
pub fn form_13f_filing_dates(
    query: Form13fFilingDatesQuery,
) -> EndpointSpec<Form13fFilingDatesQuery, Vec<Form13fFilingDate>> {
    EndpointSpec::get(
        "institutional-ownership/dates",
        "institutional-ownership/dates",
        query,
    )
    .with_metadata(US_ONLY)
}

/// Describes `GET institutional-ownership/extract-analytics/holder`.
pub fn institutional_holder_analytics(
    query: InstitutionalHolderAnalyticsQuery,
) -> EndpointSpec<InstitutionalHolderAnalyticsQuery, Vec<InstitutionalHolderAnalytics>> {
    EndpointSpec::get(
        "institutional-ownership/extract-analytics/holder",
        "institutional-ownership/extract-analytics/holder",
        query,
    )
    .with_metadata(US_ONLY)
}

/// Describes `GET institutional-ownership/holder-performance-summary`.
pub fn holder_performance_summary(
    query: HolderPerformanceSummaryQuery,
) -> EndpointSpec<HolderPerformanceSummaryQuery, Vec<HolderPerformanceSummary>> {
    EndpointSpec::get(
        "institutional-ownership/holder-performance-summary",
        "institutional-ownership/holder-performance-summary",
        query,
    )
    .with_metadata(US_ONLY)
}

/// Describes `GET institutional-ownership/holder-industry-breakdown`.
pub fn holder_industry_breakdown(
    query: HolderIndustryBreakdownQuery,
) -> EndpointSpec<HolderIndustryBreakdownQuery, Vec<HolderIndustryBreakdown>> {
    EndpointSpec::get(
        "institutional-ownership/holder-industry-breakdown",
        "institutional-ownership/holder-industry-breakdown",
        query,
    )
    .with_metadata(US_ONLY)
}

/// Describes `GET institutional-ownership/symbol-positions-summary`.
pub fn institutional_positions_summary(
    query: InstitutionalPositionsSummaryQuery,
) -> EndpointSpec<InstitutionalPositionsSummaryQuery, Vec<InstitutionalPositionSummary>> {
    EndpointSpec::get(
        "institutional-ownership/symbol-positions-summary",
        "institutional-ownership/symbol-positions-summary",
        query,
    )
    .with_metadata(US_ONLY)
}

/// Describes `GET institutional-ownership/industry-summary`.
pub fn institutional_industry_summary(
    query: InstitutionalIndustrySummaryQuery,
) -> EndpointSpec<InstitutionalIndustrySummaryQuery, Vec<InstitutionalIndustrySummary>> {
    EndpointSpec::get(
        "institutional-ownership/industry-summary",
        "institutional-ownership/industry-summary",
        query,
    )
    .with_metadata(US_ONLY)
}

impl Client {
    /// Retrieves the latest US institutional-ownership filings.
    pub async fn latest_institutional_ownership_filings(
        &self,
        query: impl Into<LatestInstitutionalOwnershipFilingsQuery>,
    ) -> Result<Vec<InstitutionalOwnershipFiling>> {
        self.execute(&latest_institutional_ownership_filings(query.into()))
            .await
    }

    /// Extracts the positions from one US institutional-ownership filing period.
    pub async fn institutional_ownership_extract(
        &self,
        query: impl Into<InstitutionalOwnershipExtractQuery>,
    ) -> Result<Vec<InstitutionalHolding>> {
        self.execute(&institutional_ownership_extract(query.into()))
            .await
    }

    /// Retrieves available Form 13F filing dates for one US institutional holder.
    pub async fn form_13f_filing_dates(
        &self,
        query: impl Into<Form13fFilingDatesQuery>,
    ) -> Result<Vec<Form13fFilingDate>> {
        self.execute(&form_13f_filing_dates(query.into())).await
    }

    /// Retrieves holder-level analytics for one US security and filing period.
    pub async fn institutional_holder_analytics(
        &self,
        query: impl Into<InstitutionalHolderAnalyticsQuery>,
    ) -> Result<Vec<InstitutionalHolderAnalytics>> {
        self.execute(&institutional_holder_analytics(query.into()))
            .await
    }

    /// Retrieves a US institutional holder's portfolio performance summary.
    pub async fn holder_performance_summary(
        &self,
        query: impl Into<HolderPerformanceSummaryQuery>,
    ) -> Result<Vec<HolderPerformanceSummary>> {
        self.execute(&holder_performance_summary(query.into()))
            .await
    }

    /// Retrieves a US institutional holder's industry breakdown for one period.
    pub async fn holder_industry_breakdown(
        &self,
        query: impl Into<HolderIndustryBreakdownQuery>,
    ) -> Result<Vec<HolderIndustryBreakdown>> {
        self.execute(&holder_industry_breakdown(query.into())).await
    }

    /// Retrieves the US institutional position summary for one security and period.
    pub async fn institutional_positions_summary(
        &self,
        query: impl Into<InstitutionalPositionsSummaryQuery>,
    ) -> Result<Vec<InstitutionalPositionSummary>> {
        self.execute(&institutional_positions_summary(query.into()))
            .await
    }

    /// Retrieves US institutional industry values for one reporting period.
    pub async fn institutional_industry_summary(
        &self,
        query: impl Into<InstitutionalIndustrySummaryQuery>,
    ) -> Result<Vec<InstitutionalIndustrySummary>> {
        self.execute(&institutional_industry_summary(query.into()))
            .await
    }
}

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

    fn pairs(query: &impl QueryParameters) -> Vec<(String, String)> {
        let mut pairs = Vec::new();
        query.encode(&mut QueryEncoder::new(&mut |name, value| {
            pairs.push((name.to_owned(), value.to_owned()));
        }));
        pairs
    }

    #[test]
    fn latest_query_omits_absent_values_and_encodes_page_then_limit() {
        assert!(pairs(&LatestInstitutionalOwnershipFilingsQuery::new()).is_empty());
        let query = LatestInstitutionalOwnershipFilingsQuery::new()
            .with_page(Page(0))
            .with_limit(Limit(100));
        assert_eq!(
            pairs(&query),
            [
                ("page".to_owned(), "0".to_owned()),
                ("limit".to_owned(), "100".to_owned()),
            ]
        );
    }

    #[test]
    fn extract_query_encodes_cik_year_then_quarter() {
        let query = InstitutionalOwnershipExtractQuery::new(
            Cik::new("0001388838").unwrap(),
            Year(2023),
            Quarter::Q3,
        );
        assert_eq!(
            pairs(&query),
            [
                ("cik".to_owned(), "0001388838".to_owned()),
                ("year".to_owned(), "2023".to_owned()),
                ("quarter".to_owned(), "3".to_owned()),
            ]
        );
    }

    #[test]
    fn dates_query_encodes_only_leading_zero_cik() {
        let query = Form13fFilingDatesQuery::new(Cik::new("0001067983").unwrap());
        assert_eq!(pairs(&query), [("cik".to_owned(), "0001067983".to_owned())]);
    }

    #[test]
    fn holder_analytics_encodes_symbol_year_quarter_page_then_limit() {
        let query = InstitutionalHolderAnalyticsQuery::new(
            Ticker::new("AAPL").unwrap(),
            Year(2023),
            Quarter::Q3,
        )
        .with_page(Page(0))
        .with_limit(Limit(10));
        assert_eq!(
            pairs(&query),
            [
                ("symbol".to_owned(), "AAPL".to_owned()),
                ("year".to_owned(), "2023".to_owned()),
                ("quarter".to_owned(), "3".to_owned()),
                ("page".to_owned(), "0".to_owned()),
                ("limit".to_owned(), "10".to_owned()),
            ]
        );
    }

    #[test]
    fn holder_summary_queries_encode_required_values_in_exact_order() {
        let cik = Cik::new("0001067983").unwrap();
        assert_eq!(
            pairs(&HolderPerformanceSummaryQuery::new(cik.clone()).with_page(Page(0))),
            [
                ("cik".to_owned(), "0001067983".to_owned()),
                ("page".to_owned(), "0".to_owned()),
            ]
        );
        assert_eq!(
            pairs(&HolderIndustryBreakdownQuery::new(
                cik,
                Year(2023),
                Quarter::Q3,
            )),
            [
                ("cik".to_owned(), "0001067983".to_owned()),
                ("year".to_owned(), "2023".to_owned()),
                ("quarter".to_owned(), "3".to_owned()),
            ]
        );
    }

    #[test]
    fn position_and_industry_summaries_encode_required_values_in_exact_order() {
        assert_eq!(
            pairs(&InstitutionalPositionsSummaryQuery::new(
                Ticker::new("AAPL").unwrap(),
                Year(2023),
                Quarter::Q3,
            )),
            [
                ("symbol".to_owned(), "AAPL".to_owned()),
                ("year".to_owned(), "2023".to_owned()),
                ("quarter".to_owned(), "3".to_owned()),
            ]
        );
        assert_eq!(
            pairs(&InstitutionalIndustrySummaryQuery::new(
                Year(2023),
                Quarter::Q3,
            )),
            [
                ("year".to_owned(), "2023".to_owned()),
                ("quarter".to_owned(), "3".to_owned()),
            ]
        );
    }
}