libfmp 1.2.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
//! Bulk endpoint contracts.
//!
//! Every bulk route answers one `GET` with one headed `text/csv` body (ADR
//! 0035), and each convenience method sends exactly one request: the client
//! never paginates a `part`, retries, or fans out on the caller's behalf. Each
//! record decodes into one row by header name; an empty or header-only body is
//! no rows. Numeric cells are preserved verbatim as
//! [`crate::codecs::NumericString`] on every route except `profile-bulk`, and
//! an empty numeric cell is `None`.
//!
//! Bulk descriptors buffer up to
//! [`crate::client::DEFAULT_BULK_MAX_RESPONSE_BODY_BYTES`] (256 MiB) while the
//! client limit is unset: whole-market bodies such as `ratios-ttm-bulk`
//! exceed the 64 MiB general default. A limit set with
//! [`crate::client::ClientBuilder::max_response_body_bytes`] applies to bulk
//! routes too, and every bulk call shares the client's single logical
//! timeout, which [`crate::client::ClientBuilder::timeout`] can raise. The
//! Python binding exposes the same eighteen methods under `client.bulk`.

use crate::{
    Client, Result,
    endpoints::{
        EndpointSpec, QueryEncoder, QueryParameters,
        metadata::{EndpointMetadata, GeographicAvailability},
    },
    query::{FiscalPeriod, Year},
    responses::{
        bulk::{
            BulkBalanceSheetStatement, BulkBalanceSheetStatementGrowth, BulkCashFlowStatement,
            BulkCashFlowStatementGrowth, BulkDcfValuation, BulkEarningsSurprise, BulkEodBar,
            BulkEtfHolding, BulkFinancialRatiosTtm, BulkFinancialScore, BulkIncomeStatement,
            BulkIncomeStatementGrowth, BulkKeyMetricsTtm, BulkPriceTargetSummary, BulkStockPeer,
            BulkStockRating, BulkUpgradesDowngradesConsensus,
        },
        company::CompanyProfile,
    },
    types::{BulkPart, Date},
};

/// Required provider partition shared by partitioned bulk routes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BulkPartQuery {
    part: BulkPart,
}

impl BulkPartQuery {
    /// Creates a partitioned bulk query without inferring a numeric range.
    pub const fn new(part: BulkPart) -> Self {
        Self { part }
    }

    /// Borrows the original provider partition representation.
    pub const fn part(&self) -> &BulkPart {
        &self.part
    }
}

impl From<BulkPart> for BulkPartQuery {
    fn from(part: BulkPart) -> Self {
        Self::new(part)
    }
}

impl From<&BulkPart> for BulkPartQuery {
    fn from(part: &BulkPart) -> Self {
        Self::new(part.clone())
    }
}

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

/// Required provider year for the annual earnings-surprises bulk route.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BulkYearQuery {
    year: Year,
}

impl BulkYearQuery {
    /// Creates a bulk year query without inferring an undocumented range.
    pub const fn new(year: Year) -> Self {
        Self { year }
    }

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

impl From<Year> for BulkYearQuery {
    fn from(year: Year) -> Self {
        Self::new(year)
    }
}

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

/// Required provider year and fiscal period shared by bulk statement routes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BulkStatementQuery {
    year: Year,
    period: FiscalPeriod,
}

impl BulkStatementQuery {
    /// Creates a bulk statement query with both documented required values.
    pub const fn new(year: Year, period: FiscalPeriod) -> Self {
        Self { year, period }
    }

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

    /// Returns the requested fiscal period.
    pub const fn period(&self) -> FiscalPeriod {
        self.period
    }
}

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

/// Required provider date for the bulk end-of-day route.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BulkEodQuery {
    date: Date,
}

impl BulkEodQuery {
    /// Creates a bulk end-of-day query for the documented required date.
    pub const fn new(date: Date) -> Self {
        Self { date }
    }

    /// Returns the requested provider date.
    pub const fn date(&self) -> Date {
        self.date
    }
}

impl From<Date> for BulkEodQuery {
    fn from(date: Date) -> Self {
        Self::new(date)
    }
}

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

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

/// Describes `GET profile-bulk` without binding a transport.
pub fn bulk_company_profiles(
    query: BulkPartQuery,
) -> EndpointSpec<BulkPartQuery, Vec<CompanyProfile>> {
    EndpointSpec::get_csv("profile-bulk", "profile-bulk", query).with_metadata(WORLDWIDE)
}

/// Describes `GET rating-bulk` without binding a transport.
pub fn bulk_stock_ratings() -> EndpointSpec<(), Vec<BulkStockRating>> {
    EndpointSpec::get_csv("rating-bulk", "rating-bulk", ()).with_metadata(WORLDWIDE)
}

/// Describes `GET dcf-bulk` without binding a transport.
pub fn bulk_dcf_valuations() -> EndpointSpec<(), Vec<BulkDcfValuation>> {
    EndpointSpec::get_csv("dcf-bulk", "dcf-bulk", ()).with_metadata(WORLDWIDE)
}

/// Describes `GET scores-bulk` without binding a transport.
pub fn bulk_financial_scores() -> EndpointSpec<(), Vec<BulkFinancialScore>> {
    EndpointSpec::get_csv("scores-bulk", "scores-bulk", ()).with_metadata(WORLDWIDE)
}

/// Describes `GET price-target-summary-bulk` without binding a transport.
pub fn bulk_price_target_summaries() -> EndpointSpec<(), Vec<BulkPriceTargetSummary>> {
    EndpointSpec::get_csv("price-target-summary-bulk", "price-target-summary-bulk", ())
        .with_metadata(US_ONLY)
}

/// Describes `GET etf-holder-bulk` without binding a transport.
pub fn bulk_etf_holdings(query: BulkPartQuery) -> EndpointSpec<BulkPartQuery, Vec<BulkEtfHolding>> {
    EndpointSpec::get_csv("etf-holder-bulk", "etf-holder-bulk", query).with_metadata(WORLDWIDE)
}

/// Describes `GET upgrades-downgrades-consensus-bulk` without binding a transport.
pub fn bulk_upgrades_downgrades_consensus() -> EndpointSpec<(), Vec<BulkUpgradesDowngradesConsensus>>
{
    EndpointSpec::get_csv(
        "upgrades-downgrades-consensus-bulk",
        "upgrades-downgrades-consensus-bulk",
        (),
    )
    .with_metadata(WORLDWIDE)
}

/// Describes `GET key-metrics-ttm-bulk` without binding a transport.
pub fn bulk_key_metrics_ttm() -> EndpointSpec<(), Vec<BulkKeyMetricsTtm>> {
    EndpointSpec::get_csv("key-metrics-ttm-bulk", "key-metrics-ttm-bulk", ())
        .with_metadata(WORLDWIDE)
}

/// Describes `GET ratios-ttm-bulk` without binding a transport.
pub fn bulk_financial_ratios_ttm() -> EndpointSpec<(), Vec<BulkFinancialRatiosTtm>> {
    EndpointSpec::get_csv("ratios-ttm-bulk", "ratios-ttm-bulk", ()).with_metadata(WORLDWIDE)
}

/// Describes `GET peers-bulk` without binding a transport.
pub fn bulk_stock_peers() -> EndpointSpec<(), Vec<BulkStockPeer>> {
    EndpointSpec::get_csv("peers-bulk", "peers-bulk", ()).with_metadata(WORLDWIDE)
}

/// Describes `GET earnings-surprises-bulk` without binding a transport.
pub fn bulk_earnings_surprises(
    query: BulkYearQuery,
) -> EndpointSpec<BulkYearQuery, Vec<BulkEarningsSurprise>> {
    EndpointSpec::get_csv("earnings-surprises-bulk", "earnings-surprises-bulk", query)
        .with_metadata(WORLDWIDE)
}

/// Describes `GET income-statement-bulk` without binding a transport.
pub fn bulk_income_statements(
    query: BulkStatementQuery,
) -> EndpointSpec<BulkStatementQuery, Vec<BulkIncomeStatement>> {
    EndpointSpec::get_csv("income-statement-bulk", "income-statement-bulk", query)
        .with_metadata(WORLDWIDE)
}

/// Describes `GET income-statement-growth-bulk` without binding a transport.
pub fn bulk_income_statement_growth(
    query: BulkStatementQuery,
) -> EndpointSpec<BulkStatementQuery, Vec<BulkIncomeStatementGrowth>> {
    EndpointSpec::get_csv(
        "income-statement-growth-bulk",
        "income-statement-growth-bulk",
        query,
    )
    .with_metadata(WORLDWIDE)
}

/// Describes `GET balance-sheet-statement-bulk` without binding a transport.
pub fn bulk_balance_sheet_statements(
    query: BulkStatementQuery,
) -> EndpointSpec<BulkStatementQuery, Vec<BulkBalanceSheetStatement>> {
    EndpointSpec::get_csv(
        "balance-sheet-statement-bulk",
        "balance-sheet-statement-bulk",
        query,
    )
    .with_metadata(WORLDWIDE)
}

/// Describes `GET balance-sheet-statement-growth-bulk` without binding a transport.
pub fn bulk_balance_sheet_statement_growth(
    query: BulkStatementQuery,
) -> EndpointSpec<BulkStatementQuery, Vec<BulkBalanceSheetStatementGrowth>> {
    EndpointSpec::get_csv(
        "balance-sheet-statement-growth-bulk",
        "balance-sheet-statement-growth-bulk",
        query,
    )
    .with_metadata(WORLDWIDE)
}

/// Describes `GET cash-flow-statement-bulk` without binding a transport.
pub fn bulk_cash_flow_statements(
    query: BulkStatementQuery,
) -> EndpointSpec<BulkStatementQuery, Vec<BulkCashFlowStatement>> {
    EndpointSpec::get_csv(
        "cash-flow-statement-bulk",
        "cash-flow-statement-bulk",
        query,
    )
    .with_metadata(WORLDWIDE)
}

/// Describes `GET cash-flow-statement-growth-bulk` without binding a transport.
pub fn bulk_cash_flow_statement_growth(
    query: BulkStatementQuery,
) -> EndpointSpec<BulkStatementQuery, Vec<BulkCashFlowStatementGrowth>> {
    EndpointSpec::get_csv(
        "cash-flow-statement-growth-bulk",
        "cash-flow-statement-growth-bulk",
        query,
    )
    .with_metadata(WORLDWIDE)
}

/// Describes `GET eod-bulk` without binding a transport.
pub fn bulk_eod(query: BulkEodQuery) -> EndpointSpec<BulkEodQuery, Vec<BulkEodBar>> {
    EndpointSpec::get_csv("eod-bulk", "eod-bulk", query).with_metadata(WORLDWIDE)
}

impl Client {
    /// Retrieves one provider partition of worldwide company profiles.
    pub async fn bulk_company_profiles(
        &self,
        query: impl Into<BulkPartQuery>,
    ) -> Result<Vec<CompanyProfile>> {
        self.execute(&bulk_company_profiles(query.into())).await
    }

    /// Retrieves worldwide stock ratings in one provider bulk response.
    pub async fn bulk_stock_ratings(&self) -> Result<Vec<BulkStockRating>> {
        self.execute(&bulk_stock_ratings()).await
    }

    /// Retrieves worldwide discounted-cash-flow valuations in one provider bulk response.
    pub async fn bulk_dcf_valuations(&self) -> Result<Vec<BulkDcfValuation>> {
        self.execute(&bulk_dcf_valuations()).await
    }

    /// Retrieves worldwide financial scores in one provider bulk response.
    pub async fn bulk_financial_scores(&self) -> Result<Vec<BulkFinancialScore>> {
        self.execute(&bulk_financial_scores()).await
    }

    /// Retrieves US price-target summaries in one provider bulk response.
    pub async fn bulk_price_target_summaries(&self) -> Result<Vec<BulkPriceTargetSummary>> {
        self.execute(&bulk_price_target_summaries()).await
    }

    /// Retrieves one provider partition of worldwide ETF holdings.
    pub async fn bulk_etf_holdings(
        &self,
        query: impl Into<BulkPartQuery>,
    ) -> Result<Vec<BulkEtfHolding>> {
        self.execute(&bulk_etf_holdings(query.into())).await
    }

    /// Retrieves worldwide upgrades/downgrades consensus in one provider bulk response.
    pub async fn bulk_upgrades_downgrades_consensus(
        &self,
    ) -> Result<Vec<BulkUpgradesDowngradesConsensus>> {
        self.execute(&bulk_upgrades_downgrades_consensus()).await
    }

    /// Retrieves worldwide trailing-twelve-month key metrics in one bulk response.
    pub async fn bulk_key_metrics_ttm(&self) -> Result<Vec<BulkKeyMetricsTtm>> {
        self.execute(&bulk_key_metrics_ttm()).await
    }

    /// Retrieves worldwide trailing-twelve-month financial ratios in one bulk response.
    pub async fn bulk_financial_ratios_ttm(&self) -> Result<Vec<BulkFinancialRatiosTtm>> {
        self.execute(&bulk_financial_ratios_ttm()).await
    }

    /// Retrieves worldwide stock peers in one provider bulk response.
    pub async fn bulk_stock_peers(&self) -> Result<Vec<BulkStockPeer>> {
        self.execute(&bulk_stock_peers()).await
    }

    /// Retrieves worldwide annual earnings surprises for one required provider year.
    pub async fn bulk_earnings_surprises(
        &self,
        query: impl Into<BulkYearQuery>,
    ) -> Result<Vec<BulkEarningsSurprise>> {
        self.execute(&bulk_earnings_surprises(query.into())).await
    }

    /// Retrieves worldwide bulk income statements for one year and fiscal period.
    pub async fn bulk_income_statements(
        &self,
        query: BulkStatementQuery,
    ) -> Result<Vec<BulkIncomeStatement>> {
        self.execute(&bulk_income_statements(query)).await
    }

    /// Retrieves worldwide bulk income-statement growth for one year and fiscal period.
    pub async fn bulk_income_statement_growth(
        &self,
        query: BulkStatementQuery,
    ) -> Result<Vec<BulkIncomeStatementGrowth>> {
        self.execute(&bulk_income_statement_growth(query)).await
    }

    /// Retrieves worldwide bulk balance sheets for one year and fiscal period.
    pub async fn bulk_balance_sheet_statements(
        &self,
        query: BulkStatementQuery,
    ) -> Result<Vec<BulkBalanceSheetStatement>> {
        self.execute(&bulk_balance_sheet_statements(query)).await
    }

    /// Retrieves worldwide bulk balance-sheet growth for one year and fiscal period.
    pub async fn bulk_balance_sheet_statement_growth(
        &self,
        query: BulkStatementQuery,
    ) -> Result<Vec<BulkBalanceSheetStatementGrowth>> {
        self.execute(&bulk_balance_sheet_statement_growth(query))
            .await
    }

    /// Retrieves worldwide bulk cash-flow statements for one year and fiscal period.
    pub async fn bulk_cash_flow_statements(
        &self,
        query: BulkStatementQuery,
    ) -> Result<Vec<BulkCashFlowStatement>> {
        self.execute(&bulk_cash_flow_statements(query)).await
    }

    /// Retrieves worldwide bulk cash-flow growth for one year and fiscal period.
    pub async fn bulk_cash_flow_statement_growth(
        &self,
        query: BulkStatementQuery,
    ) -> Result<Vec<BulkCashFlowStatementGrowth>> {
        self.execute(&bulk_cash_flow_statement_growth(query)).await
    }

    /// Retrieves worldwide bulk end-of-day prices for one required date.
    pub async fn bulk_eod(&self, query: impl Into<BulkEodQuery>) -> Result<Vec<BulkEodBar>> {
        self.execute(&bulk_eod(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 bulk_part_query_has_one_exact_required_key_and_borrowed_conversion() {
        let part = BulkPart::new("segment 01/alpha").unwrap();
        let owned = BulkPartQuery::from(part.clone());
        let borrowed = BulkPartQuery::from(&part);

        assert_eq!(owned.part(), &part);
        assert_eq!(borrowed.part(), &part);
        assert_eq!(
            encoded(&borrowed),
            [("part".into(), "segment 01/alpha".into())]
        );
    }

    #[test]
    fn bulk_year_query_has_one_exact_required_key() {
        let query = BulkYearQuery::new(Year(2026));

        assert_eq!(query.year(), Year(2026));
        assert_eq!(encoded(&query), [("year".into(), "2026".into())]);
        assert_eq!(BulkYearQuery::from(Year(7)), BulkYearQuery::new(Year(7)));
    }

    #[test]
    fn bulk_statement_query_has_two_exact_required_keys_in_documented_order() {
        let query = BulkStatementQuery::new(Year(2026), FiscalPeriod::Q1);

        assert_eq!(query.year(), Year(2026));
        assert_eq!(query.period(), FiscalPeriod::Q1);
        assert_eq!(
            encoded(&query),
            [
                ("year".into(), "2026".into()),
                ("period".into(), "Q1".into())
            ]
        );
    }

    #[test]
    fn bulk_eod_query_has_one_exact_required_key() {
        let date = Date::parse("2024-10-22").unwrap();
        let query = BulkEodQuery::new(date);

        assert_eq!(query.date(), date);
        assert_eq!(encoded(&query), [("date".into(), "2024-10-22".into())]);
        assert_eq!(BulkEodQuery::from(date), query);
    }

    #[test]
    fn bulk_descriptors_default_to_the_bulk_limit_without_overriding_the_client() {
        let bulk = crate::client::DEFAULT_BULK_MAX_RESPONSE_BODY_BYTES;
        assert_eq!(bulk_stock_ratings().max_response_body_bytes(), None);
        assert_eq!(bulk_stock_ratings().default_max_response_body_bytes(), bulk);
        assert_eq!(
            bulk_key_metrics_ttm().default_max_response_body_bytes(),
            bulk
        );
        assert_eq!(
            bulk_financial_ratios_ttm().default_max_response_body_bytes(),
            bulk
        );
        assert_eq!(
            bulk_eod(Date::parse("2025-06-02").unwrap().into()).default_max_response_body_bytes(),
            bulk
        );
    }
}