libfmp 1.3.1

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
//! ETF and mutual-fund endpoint query contracts.

use crate::{
    Client, Result,
    endpoints::{
        EndpointSpec, QueryEncoder, QueryParameters,
        metadata::{EndpointMetadata, GeographicAvailability},
    },
    query::{Quarter, Year},
    responses::funds::{
        EtfAssetExposure, EtfCountryWeighting, EtfFundHolding, EtfFundInfo, EtfSectorWeighting,
        FundDisclosure, FundDisclosureDate, FundDisclosureHolder, FundDisclosureSearchResult,
    },
    types::{Cik, SearchTerm, Ticker},
};

macro_rules! required_symbol_query {
    ($name:ident, $description:literal) => {
        #[doc = $description]
        #[derive(Debug, Clone, PartialEq, Eq)]
        pub struct $name {
            symbol: Ticker,
        }

        impl $name {
            /// Creates a query for one ticker.
            pub const fn new(symbol: Ticker) -> Self {
                Self { symbol }
            }

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

        impl From<Ticker> for $name {
            fn from(symbol: Ticker) -> Self {
                Self::new(symbol)
            }
        }

        impl From<&Ticker> for $name {
            fn from(symbol: &Ticker) -> Self {
                Self::new(symbol.clone())
            }
        }

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

required_symbol_query!(
    EtfHoldingsQuery,
    "Required fund ticker for retrieving ETF or mutual-fund holdings."
);
required_symbol_query!(
    EtfInfoQuery,
    "Required fund ticker for retrieving ETF or mutual-fund information."
);
required_symbol_query!(
    EtfCountryWeightingsQuery,
    "Required fund ticker for retrieving country allocation."
);
required_symbol_query!(
    EtfAssetExposureQuery,
    "Required asset ticker for discovering ETF exposure."
);
required_symbol_query!(
    EtfSectorWeightingsQuery,
    "Required fund ticker for retrieving sector allocation."
);
required_symbol_query!(
    LatestFundDisclosureHoldersQuery,
    "Required asset ticker for retrieving the latest disclosed fund holders."
);

/// Required fund and reporting period plus an optional filer CIK.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FundDisclosureQuery {
    symbol: Ticker,
    year: Year,
    quarter: Quarter,
    cik: Option<Cik>,
}

impl FundDisclosureQuery {
    /// Creates a disclosure query without an undocumented CIK default.
    pub const fn new(symbol: Ticker, year: Year, quarter: Quarter) -> Self {
        Self {
            symbol,
            year,
            quarter,
            cik: None,
        }
    }

    /// Restricts the query to one provider filer CIK.
    pub fn with_cik(mut self, cik: Cik) -> Self {
        self.cik = Some(cik);
        self
    }

    /// Borrows the requested fund 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 provider query quarter.
    pub const fn quarter(&self) -> Quarter {
        self.quarter
    }

    /// Borrows the optional filer CIK.
    pub const fn cik(&self) -> Option<&Cik> {
        self.cik.as_ref()
    }
}

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

/// Required representation-preserving fund or ETF name search term.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FundDisclosureHolderSearchQuery {
    name: SearchTerm,
}

impl FundDisclosureHolderSearchQuery {
    /// Creates a disclosure-holder name search.
    pub const fn new(name: SearchTerm) -> Self {
        Self { name }
    }

    /// Borrows the exact requested name.
    pub const fn name(&self) -> &SearchTerm {
        &self.name
    }
}

impl From<SearchTerm> for FundDisclosureHolderSearchQuery {
    fn from(name: SearchTerm) -> Self {
        Self::new(name)
    }
}

impl From<&SearchTerm> for FundDisclosureHolderSearchQuery {
    fn from(name: &SearchTerm) -> Self {
        Self::new(name.clone())
    }
}

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

/// Required fund ticker and optional filer CIK for available disclosure dates.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FundDisclosureDatesQuery {
    symbol: Ticker,
    cik: Option<Cik>,
}

impl FundDisclosureDatesQuery {
    /// Creates a query without an undocumented CIK default.
    pub const fn new(symbol: Ticker) -> Self {
        Self { symbol, cik: None }
    }

    /// Restricts the query to one provider filer CIK.
    pub fn with_cik(mut self, cik: Cik) -> Self {
        self.cik = Some(cik);
        self
    }

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

    /// Borrows the optional filer CIK.
    pub const fn cik(&self) -> Option<&Cik> {
        self.cik.as_ref()
    }
}

impl From<Ticker> for FundDisclosureDatesQuery {
    fn from(symbol: Ticker) -> Self {
        Self::new(symbol)
    }
}

impl From<&Ticker> for FundDisclosureDatesQuery {
    fn from(symbol: &Ticker) -> Self {
        Self::new(symbol.clone())
    }
}

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

const WORLDWIDE: EndpointMetadata =
    EndpointMetadata::new().with_geography(GeographicAvailability::Worldwide);
const US_ONLY: EndpointMetadata =
    EndpointMetadata::new().with_geography(GeographicAvailability::UsOnly);

/// Describes `GET etf/holdings` without binding a transport.
pub fn etf_holdings(
    query: EtfHoldingsQuery,
) -> EndpointSpec<EtfHoldingsQuery, Vec<EtfFundHolding>> {
    EndpointSpec::get("etf/holdings", "etf/holdings", query).with_metadata(WORLDWIDE)
}

/// Describes `GET etf/info` without binding a transport.
pub fn etf_info(query: EtfInfoQuery) -> EndpointSpec<EtfInfoQuery, Vec<EtfFundInfo>> {
    EndpointSpec::get("etf/info", "etf/info", query).with_metadata(WORLDWIDE)
}

/// Describes `GET etf/country-weightings` without binding a transport.
pub fn etf_country_weightings(
    query: EtfCountryWeightingsQuery,
) -> EndpointSpec<EtfCountryWeightingsQuery, Vec<EtfCountryWeighting>> {
    EndpointSpec::get("etf/country-weightings", "etf/country-weightings", query)
        .with_metadata(WORLDWIDE)
}

/// Describes `GET etf/asset-exposure` without binding a transport.
pub fn etf_asset_exposure(
    query: EtfAssetExposureQuery,
) -> EndpointSpec<EtfAssetExposureQuery, Vec<EtfAssetExposure>> {
    EndpointSpec::get("etf/asset-exposure", "etf/asset-exposure", query).with_metadata(WORLDWIDE)
}

/// Describes `GET etf/sector-weightings` without binding a transport.
pub fn etf_sector_weightings(
    query: EtfSectorWeightingsQuery,
) -> EndpointSpec<EtfSectorWeightingsQuery, Vec<EtfSectorWeighting>> {
    EndpointSpec::get("etf/sector-weightings", "etf/sector-weightings", query)
        .with_metadata(WORLDWIDE)
}

/// Describes `GET funds/disclosure-holders-latest` without binding a transport.
pub fn latest_fund_disclosure_holders(
    query: LatestFundDisclosureHoldersQuery,
) -> EndpointSpec<LatestFundDisclosureHoldersQuery, Vec<FundDisclosureHolder>> {
    EndpointSpec::get(
        "funds/disclosure-holders-latest",
        "funds/disclosure-holders-latest",
        query,
    )
    .with_metadata(US_ONLY)
}

/// Describes `GET funds/disclosure` without binding a transport.
pub fn fund_disclosures(
    query: FundDisclosureQuery,
) -> EndpointSpec<FundDisclosureQuery, Vec<FundDisclosure>> {
    EndpointSpec::get("funds/disclosure", "funds/disclosure", query).with_metadata(US_ONLY)
}

/// Describes `GET funds/disclosure-holders-search` without binding a transport.
pub fn search_fund_disclosure_holders(
    query: FundDisclosureHolderSearchQuery,
) -> EndpointSpec<FundDisclosureHolderSearchQuery, Vec<FundDisclosureSearchResult>> {
    EndpointSpec::get(
        "funds/disclosure-holders-search",
        "funds/disclosure-holders-search",
        query,
    )
    .with_metadata(US_ONLY)
}

/// Describes `GET funds/disclosure-dates` without binding a transport.
pub fn fund_disclosure_dates(
    query: FundDisclosureDatesQuery,
) -> EndpointSpec<FundDisclosureDatesQuery, Vec<FundDisclosureDate>> {
    EndpointSpec::get("funds/disclosure-dates", "funds/disclosure-dates", query)
        .with_metadata(US_ONLY)
}

impl Client {
    /// Retrieves the worldwide holdings of one ETF or mutual fund.
    pub async fn etf_holdings(&self, query: EtfHoldingsQuery) -> Result<Vec<EtfFundHolding>> {
        self.execute(&etf_holdings(query)).await
    }

    /// Retrieves worldwide descriptive and trading information for one fund.
    pub async fn etf_info(&self, query: EtfInfoQuery) -> Result<Vec<EtfFundInfo>> {
        self.execute(&etf_info(query)).await
    }

    /// Retrieves the worldwide country allocation for one ETF or mutual fund.
    pub async fn etf_country_weightings(
        &self,
        query: EtfCountryWeightingsQuery,
    ) -> Result<Vec<EtfCountryWeighting>> {
        self.execute(&etf_country_weightings(query)).await
    }

    /// Retrieves the worldwide ETF exposure to one requested asset.
    pub async fn etf_asset_exposure(
        &self,
        query: EtfAssetExposureQuery,
    ) -> Result<Vec<EtfAssetExposure>> {
        self.execute(&etf_asset_exposure(query)).await
    }

    /// Retrieves the worldwide sector allocation for one ETF or mutual fund.
    pub async fn etf_sector_weightings(
        &self,
        query: EtfSectorWeightingsQuery,
    ) -> Result<Vec<EtfSectorWeighting>> {
        self.execute(&etf_sector_weightings(query)).await
    }

    /// Retrieves the latest US fund disclosures holding one requested asset.
    pub async fn latest_fund_disclosure_holders(
        &self,
        query: LatestFundDisclosureHoldersQuery,
    ) -> Result<Vec<FundDisclosureHolder>> {
        self.execute(&latest_fund_disclosure_holders(query)).await
    }

    /// Retrieves positions from one US mutual-fund disclosure period.
    pub async fn fund_disclosures(
        &self,
        query: FundDisclosureQuery,
    ) -> Result<Vec<FundDisclosure>> {
        self.execute(&fund_disclosures(query)).await
    }

    /// Searches US mutual-fund and ETF disclosure holders by exact name text.
    pub async fn search_fund_disclosure_holders(
        &self,
        query: FundDisclosureHolderSearchQuery,
    ) -> Result<Vec<FundDisclosureSearchResult>> {
        self.execute(&search_fund_disclosure_holders(query)).await
    }

    /// Retrieves available US fund-disclosure reporting dates.
    pub async fn fund_disclosure_dates(
        &self,
        query: FundDisclosureDatesQuery,
    ) -> Result<Vec<FundDisclosureDate>> {
        self.execute(&fund_disclosure_dates(query)).await
    }
}

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

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

    #[test]
    fn symbol_queries_emit_the_exact_only_pair() {
        let symbol = Ticker::new("BRK.B / Class A").unwrap();

        macro_rules! assert_symbol_query {
            ($query:ty) => {
                assert_eq!(
                    pairs(&<$query>::from(&symbol)),
                    [("symbol".to_owned(), "BRK.B / Class A".to_owned())]
                );
            };
        }

        assert_symbol_query!(EtfHoldingsQuery);
        assert_symbol_query!(EtfInfoQuery);
        assert_symbol_query!(EtfCountryWeightingsQuery);
        assert_symbol_query!(EtfAssetExposureQuery);
        assert_symbol_query!(EtfSectorWeightingsQuery);
        assert_symbol_query!(LatestFundDisclosureHoldersQuery);
    }

    #[test]
    fn disclosures_emit_required_values_then_optional_cik() {
        let base =
            FundDisclosureQuery::new(Ticker::new("000089.SZ").unwrap(), Year(0), Quarter::Q4);
        assert_eq!(
            pairs(&base),
            [
                ("symbol".to_owned(), "000089.SZ".to_owned()),
                ("year".to_owned(), "0".to_owned()),
                ("quarter".to_owned(), "4".to_owned()),
            ]
        );

        let with_cik = base.with_cik(Cik::new("0000857489").unwrap());
        assert_eq!(
            pairs(&with_cik),
            [
                ("symbol".to_owned(), "000089.SZ".to_owned()),
                ("year".to_owned(), "0".to_owned()),
                ("quarter".to_owned(), "4".to_owned()),
                ("cik".to_owned(), "0000857489".to_owned()),
            ]
        );
    }

    #[test]
    fn search_and_dates_preserve_exact_values_order_and_omission() {
        let name = SearchTerm::new("Federated Hermes Government Income Securities, Inc.").unwrap();
        assert_eq!(
            pairs(&FundDisclosureHolderSearchQuery::from(&name)),
            [("name".to_owned(), name.to_string())]
        );

        let dates = FundDisclosureDatesQuery::new(Ticker::new("VWO").unwrap());
        assert_eq!(pairs(&dates), [("symbol".to_owned(), "VWO".to_owned())]);
        assert_eq!(
            pairs(&dates.with_cik(Cik::new("0000036405").unwrap())),
            [
                ("symbol".to_owned(), "VWO".to_owned()),
                ("cik".to_owned(), "0000036405".to_owned()),
            ]
        );
    }
}