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
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
//! Insider-trading endpoint query contracts.
//!
//! The provider documents every insider-trading route as available for
//! US-based companies only, so each descriptor carries
//! [`GeographicAvailability::UsOnly`]. The Python binding exposes the same six
//! methods under `client.insider_trading`.

use crate::{
    Client, Result,
    endpoints::{
        EndpointSpec, QueryEncoder, QueryParameters,
        metadata::{EndpointBounds, EndpointMetadata, GeographicAvailability},
    },
    responses::insider_trading::{
        BeneficialOwnershipAcquisition, InsiderReportingName, InsiderTrade, InsiderTradeStatistics,
        InsiderTransactionType,
    },
    types::{Cik, Date, Limit, Page, SearchTerm, Ticker, TransactionTypeCode},
};

/// Optional date and pagination filters for the latest insider trades.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct LatestInsiderTradesQuery {
    date: Option<Date>,
    page: Option<Page>,
    limit: Option<Limit>,
}

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

    /// Sets the optional provider date filter.
    pub const fn with_date(mut self, date: Date) -> Self {
        self.date = Some(date);
        self
    }

    /// 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 date filter.
    pub const fn date(&self) -> Option<Date> {
        self.date
    }

    /// 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 LatestInsiderTradesQuery {
    fn encode(&self, encoder: &mut QueryEncoder<'_>) {
        encoder.optional("date", self.date);
        encoder.optional("page", self.page);
        encoder.optional("limit", self.limit);
    }
}

/// Optional filters for searching insider trades.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct InsiderTradesSearchQuery {
    symbol: Option<Ticker>,
    page: Option<Page>,
    limit: Option<Limit>,
    reporting_cik: Option<Cik>,
    company_cik: Option<Cik>,
    transaction_type: Option<TransactionTypeCode>,
}

impl InsiderTradesSearchQuery {
    /// Creates a search without undocumented defaults.
    pub const fn new() -> Self {
        Self {
            symbol: None,
            page: None,
            limit: None,
            reporting_cik: None,
            company_cik: None,
            transaction_type: None,
        }
    }

    /// Sets the optional ticker filter.
    pub fn with_symbol(mut self, symbol: Ticker) -> Self {
        self.symbol = Some(symbol);
        self
    }

    /// 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
    }

    /// Sets the optional reporting-person CIK filter.
    pub fn with_reporting_cik(mut self, reporting_cik: Cik) -> Self {
        self.reporting_cik = Some(reporting_cik);
        self
    }

    /// Sets the optional company CIK filter.
    pub fn with_company_cik(mut self, company_cik: Cik) -> Self {
        self.company_cik = Some(company_cik);
        self
    }

    /// Sets the optional open transaction-type filter.
    pub fn with_transaction_type(mut self, transaction_type: TransactionTypeCode) -> Self {
        self.transaction_type = Some(transaction_type);
        self
    }

    /// Borrows the optional ticker filter.
    pub const fn symbol(&self) -> Option<&Ticker> {
        self.symbol.as_ref()
    }

    /// 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
    }

    /// Borrows the optional reporting-person CIK filter.
    pub const fn reporting_cik(&self) -> Option<&Cik> {
        self.reporting_cik.as_ref()
    }

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

    /// Borrows the optional transaction-type filter.
    pub const fn transaction_type(&self) -> Option<&TransactionTypeCode> {
        self.transaction_type.as_ref()
    }
}

impl QueryParameters for InsiderTradesSearchQuery {
    fn encode(&self, encoder: &mut QueryEncoder<'_>) {
        encoder.optional("symbol", self.symbol.as_ref());
        encoder.optional("page", self.page);
        encoder.optional("limit", self.limit);
        encoder.optional("reportingCik", self.reporting_cik.as_ref());
        encoder.optional("companyCik", self.company_cik.as_ref());
        encoder.optional("transactionType", self.transaction_type.as_ref());
    }
}

/// Required reporting-name search text.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InsiderReportingNameSearchQuery {
    name: SearchTerm,
}

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

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

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

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

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

/// Required ticker for insider-trade statistics.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InsiderTradeStatisticsQuery {
    symbol: Ticker,
}

impl InsiderTradeStatisticsQuery {
    /// Creates a statistics 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 InsiderTradeStatisticsQuery {
    fn from(symbol: Ticker) -> Self {
        Self::new(symbol)
    }
}

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

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

/// Required ticker and optional limit for beneficial-ownership acquisitions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BeneficialOwnershipAcquisitionsQuery {
    symbol: Ticker,
    limit: Option<Limit>,
}

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

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

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

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

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

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

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

const PAGINATED_US_ONLY: EndpointMetadata = EndpointMetadata::new()
    .with_geography(GeographicAvailability::UsOnly)
    .with_bounds(
        EndpointBounds::new()
            .with_response_rows(1_000)
            .with_page(100),
    );

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

/// Describes `GET insider-trading/latest` without binding a transport.
pub fn latest_insider_trades(
    query: LatestInsiderTradesQuery,
) -> EndpointSpec<LatestInsiderTradesQuery, Vec<InsiderTrade>> {
    EndpointSpec::get("insider-trading/latest", "insider-trading/latest", query)
        .with_metadata(PAGINATED_US_ONLY)
}

/// Describes `GET insider-trading/search` without binding a transport.
pub fn search_insider_trades(
    query: InsiderTradesSearchQuery,
) -> EndpointSpec<InsiderTradesSearchQuery, Vec<InsiderTrade>> {
    EndpointSpec::get("insider-trading/search", "insider-trading/search", query)
        .with_metadata(PAGINATED_US_ONLY)
}

/// Describes `GET insider-trading/reporting-name` without binding a transport.
pub fn search_insider_reporting_names(
    query: InsiderReportingNameSearchQuery,
) -> EndpointSpec<InsiderReportingNameSearchQuery, Vec<InsiderReportingName>> {
    EndpointSpec::get(
        "insider-trading/reporting-name",
        "insider-trading/reporting-name",
        query,
    )
    .with_metadata(US_ONLY)
}

/// Describes `GET insider-trading-transaction-type` without binding a transport.
pub fn insider_transaction_types() -> EndpointSpec<(), Vec<InsiderTransactionType>> {
    EndpointSpec::get(
        "insider-trading-transaction-type",
        "insider-trading-transaction-type",
        (),
    )
    .with_metadata(US_ONLY)
}

/// Describes `GET insider-trading/statistics` without binding a transport.
pub fn insider_trade_statistics(
    query: InsiderTradeStatisticsQuery,
) -> EndpointSpec<InsiderTradeStatisticsQuery, Vec<InsiderTradeStatistics>> {
    EndpointSpec::get(
        "insider-trading/statistics",
        "insider-trading/statistics",
        query,
    )
    .with_metadata(US_ONLY)
}

/// Describes `GET acquisition-of-beneficial-ownership` without binding a transport.
pub fn beneficial_ownership_acquisitions(
    query: BeneficialOwnershipAcquisitionsQuery,
) -> EndpointSpec<BeneficialOwnershipAcquisitionsQuery, Vec<BeneficialOwnershipAcquisition>> {
    EndpointSpec::get(
        "acquisition-of-beneficial-ownership",
        "acquisition-of-beneficial-ownership",
        query,
    )
    .with_metadata(US_ONLY)
}

impl Client {
    /// Retrieves the latest US insider trades with optional date and pagination filters.
    pub async fn latest_insider_trades(
        &self,
        query: LatestInsiderTradesQuery,
    ) -> Result<Vec<InsiderTrade>> {
        self.execute(&latest_insider_trades(query)).await
    }

    /// Searches US insider trades using independently optional filters.
    pub async fn search_insider_trades(
        &self,
        query: InsiderTradesSearchQuery,
    ) -> Result<Vec<InsiderTrade>> {
        self.execute(&search_insider_trades(query)).await
    }

    /// Searches US insider-reporting identities by name.
    pub async fn search_insider_reporting_names(
        &self,
        query: impl Into<InsiderReportingNameSearchQuery>,
    ) -> Result<Vec<InsiderReportingName>> {
        self.execute(&search_insider_reporting_names(query.into()))
            .await
    }

    /// Retrieves the US insider transaction-type taxonomy.
    pub async fn insider_transaction_types(&self) -> Result<Vec<InsiderTransactionType>> {
        self.execute(&insider_transaction_types()).await
    }

    /// Retrieves quarterly US insider-trade statistics for one ticker.
    pub async fn insider_trade_statistics(
        &self,
        query: impl Into<InsiderTradeStatisticsQuery>,
    ) -> Result<Vec<InsiderTradeStatistics>> {
        self.execute(&insider_trade_statistics(query.into())).await
    }

    /// Retrieves US beneficial-ownership acquisition filings for one ticker.
    pub async fn beneficial_ownership_acquisitions(
        &self,
        query: impl Into<BeneficialOwnershipAcquisitionsQuery>,
    ) -> Result<Vec<BeneficialOwnershipAcquisition>> {
        self.execute(&beneficial_ownership_acquisitions(query.into()))
            .await
    }
}

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

    fn encoded(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 latest_query_omits_all_filters_and_preserves_full_domains() {
        assert!(encoded(&LatestInsiderTradesQuery::new()).is_empty());
        let query = LatestInsiderTradesQuery::new()
            .with_date(Date::parse("2026-01-27").unwrap())
            .with_page(Page(0))
            .with_limit(Limit(u32::MAX));
        assert_eq!(
            encoded(&query),
            [
                ("date".into(), "2026-01-27".into()),
                ("page".into(), "0".into()),
                ("limit".into(), u32::MAX.to_string()),
            ]
        );
    }

    #[test]
    fn search_query_emits_exact_keys_in_documented_order() {
        assert!(encoded(&InsiderTradesSearchQuery::new()).is_empty());
        let query = InsiderTradesSearchQuery::new()
            .with_symbol(Ticker::new("AAPL").unwrap())
            .with_page(Page(u32::MAX))
            .with_limit(Limit(0))
            .with_reporting_cik(Cik::new("0001496686").unwrap())
            .with_company_cik(Cik::new("0000320193").unwrap())
            .with_transaction_type(TransactionTypeCode::new("S-Sale / future").unwrap());
        assert_eq!(
            encoded(&query),
            [
                ("symbol".into(), "AAPL".into()),
                ("page".into(), u32::MAX.to_string()),
                ("limit".into(), "0".into()),
                ("reportingCik".into(), "0001496686".into()),
                ("companyCik".into(), "0000320193".into()),
                ("transactionType".into(), "S-Sale / future".into()),
            ]
        );
    }

    #[test]
    fn required_queries_and_unit_taxonomy_query_have_exact_shapes() {
        let name =
            InsiderReportingNameSearchQuery::new(SearchTerm::new("Zuckerberg, Mark").unwrap());
        assert_eq!(encoded(&name), [("name".into(), "Zuckerberg, Mark".into())]);

        let statistics = InsiderTradeStatisticsQuery::new(Ticker::new("AAPL").unwrap());
        assert_eq!(encoded(&statistics), [("symbol".into(), "AAPL".into())]);

        let ownership =
            BeneficialOwnershipAcquisitionsQuery::new(Ticker::new("000001.SZ").unwrap())
                .with_limit(Limit(u32::MAX));
        assert_eq!(
            encoded(&ownership),
            [
                ("symbol".into(), "000001.SZ".into()),
                ("limit".into(), u32::MAX.to_string()),
            ]
        );

        assert!(encoded(&()).is_empty());
    }
}