libfmp 0.7.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
//! Analyst endpoint query contracts.

use crate::{
    Client, Result,
    endpoints::{
        EndpointSpec, QueryEncoder, QueryParameters,
        metadata::{EndpointBounds, EndpointMetadata, GeographicAvailability},
    },
    query::RetrievalFrequency,
    responses::analyst::{
        FinancialEstimate, HistoricalRating, HistoricalStockGrade, PriceTargetConsensus,
        PriceTargetSummary, RatingSnapshot, StockGrade, StockGradesSummary,
    },
    types::{Limit, Page, Ticker},
};

/// Required security and frequency plus optional pagination for financial estimates.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FinancialEstimatesQuery {
    symbol: Ticker,
    period: RetrievalFrequency,
    page: Option<Page>,
    limit: Option<Limit>,
}

impl FinancialEstimatesQuery {
    /// Creates a query without undocumented pagination defaults.
    pub const fn new(symbol: Ticker, period: RetrievalFrequency) -> Self {
        Self {
            symbol,
            period,
            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 requested ticker.
    pub const fn symbol(&self) -> &Ticker {
        &self.symbol
    }

    /// Returns the required annual or quarterly retrieval frequency.
    pub const fn period(&self) -> RetrievalFrequency {
        self.period
    }

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

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);
            }
        }
    };
}

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

        impl $name {
            /// Creates a query for one ticker 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 $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);
                encoder.optional("limit", self.limit);
            }
        }
    };
}

required_symbol_query!(
    RatingsSnapshotQuery,
    "Required ticker for the worldwide ratings snapshot."
);
symbol_limit_query!(
    HistoricalRatingsQuery,
    "Required ticker and optional limit for historical worldwide ratings."
);
required_symbol_query!(
    PriceTargetSummaryQuery,
    "Required ticker for the US price-target summary."
);
required_symbol_query!(
    PriceTargetConsensusQuery,
    "Required ticker for the US price-target consensus."
);
required_symbol_query!(
    StockGradesQuery,
    "Required ticker for current worldwide stock grades."
);
symbol_limit_query!(
    HistoricalStockGradesQuery,
    "Required ticker and optional limit for historical worldwide stock grades."
);
required_symbol_query!(
    StockGradesSummaryQuery,
    "Required ticker for the worldwide stock-grades summary."
);

const FINANCIAL_ESTIMATES_METADATA: EndpointMetadata = EndpointMetadata::new()
    .with_geography(GeographicAvailability::Worldwide)
    .with_bounds(EndpointBounds::new().with_response_rows(1_000));
const RATINGS_SNAPSHOT_METADATA: EndpointMetadata = EndpointMetadata::new()
    .with_geography(GeographicAvailability::Worldwide)
    .with_bounds(EndpointBounds::new().with_response_rows(1));
const HISTORICAL_RATINGS_METADATA: EndpointMetadata = EndpointMetadata::new()
    .with_geography(GeographicAvailability::Worldwide)
    .with_bounds(EndpointBounds::new().with_response_rows(10_000));
const PRICE_TARGET_METADATA: EndpointMetadata =
    EndpointMetadata::new().with_geography(GeographicAvailability::UsOnly);
const STOCK_GRADES_METADATA: EndpointMetadata =
    EndpointMetadata::new().with_geography(GeographicAvailability::Worldwide);
const HISTORICAL_STOCK_GRADES_METADATA: EndpointMetadata = EndpointMetadata::new()
    .with_geography(GeographicAvailability::Worldwide)
    .with_bounds(EndpointBounds::new().with_response_rows(1_000));

/// Describes `GET analyst-estimates` without binding a transport.
pub fn financial_estimates(
    query: FinancialEstimatesQuery,
) -> EndpointSpec<FinancialEstimatesQuery, Vec<FinancialEstimate>> {
    EndpointSpec::get("analyst-estimates", "analyst-estimates", query)
        .with_metadata(FINANCIAL_ESTIMATES_METADATA)
}

/// Describes `GET ratings-snapshot` without binding a transport.
pub fn ratings_snapshot(
    query: RatingsSnapshotQuery,
) -> EndpointSpec<RatingsSnapshotQuery, Vec<RatingSnapshot>> {
    EndpointSpec::get("ratings-snapshot", "ratings-snapshot", query)
        .with_metadata(RATINGS_SNAPSHOT_METADATA)
}

/// Describes `GET ratings-historical` without binding a transport.
pub fn historical_ratings(
    query: HistoricalRatingsQuery,
) -> EndpointSpec<HistoricalRatingsQuery, Vec<HistoricalRating>> {
    EndpointSpec::get("ratings-historical", "ratings-historical", query)
        .with_metadata(HISTORICAL_RATINGS_METADATA)
}

/// Describes `GET price-target-summary` without binding a transport.
pub fn price_target_summary(
    query: PriceTargetSummaryQuery,
) -> EndpointSpec<PriceTargetSummaryQuery, Vec<PriceTargetSummary>> {
    EndpointSpec::get("price-target-summary", "price-target-summary", query)
        .with_metadata(PRICE_TARGET_METADATA)
}

/// Describes `GET price-target-consensus` without binding a transport.
pub fn price_target_consensus(
    query: PriceTargetConsensusQuery,
) -> EndpointSpec<PriceTargetConsensusQuery, Vec<PriceTargetConsensus>> {
    EndpointSpec::get("price-target-consensus", "price-target-consensus", query)
        .with_metadata(PRICE_TARGET_METADATA)
}

/// Describes `GET grades` without binding a transport.
pub fn stock_grades(query: StockGradesQuery) -> EndpointSpec<StockGradesQuery, Vec<StockGrade>> {
    EndpointSpec::get("grades", "grades", query).with_metadata(STOCK_GRADES_METADATA)
}

/// Describes `GET grades-historical` without binding a transport.
pub fn historical_stock_grades(
    query: HistoricalStockGradesQuery,
) -> EndpointSpec<HistoricalStockGradesQuery, Vec<HistoricalStockGrade>> {
    EndpointSpec::get("grades-historical", "grades-historical", query)
        .with_metadata(HISTORICAL_STOCK_GRADES_METADATA)
}

/// Describes `GET grades-consensus` without binding a transport.
pub fn stock_grades_summary(
    query: StockGradesSummaryQuery,
) -> EndpointSpec<StockGradesSummaryQuery, Vec<StockGradesSummary>> {
    EndpointSpec::get("grades-consensus", "grades-consensus", query)
        .with_metadata(STOCK_GRADES_METADATA)
}

impl Client {
    /// Retrieves worldwide analyst financial estimates for one ticker.
    pub async fn financial_estimates(
        &self,
        query: impl Into<FinancialEstimatesQuery>,
    ) -> Result<Vec<FinancialEstimate>> {
        self.execute(&financial_estimates(query.into())).await
    }

    /// Retrieves the worldwide financial-rating snapshot for one ticker.
    pub async fn ratings_snapshot(
        &self,
        query: impl Into<RatingsSnapshotQuery>,
    ) -> Result<Vec<RatingSnapshot>> {
        self.execute(&ratings_snapshot(query.into())).await
    }

    /// Retrieves worldwide historical financial ratings for one ticker.
    pub async fn historical_ratings(
        &self,
        query: impl Into<HistoricalRatingsQuery>,
    ) -> Result<Vec<HistoricalRating>> {
        self.execute(&historical_ratings(query.into())).await
    }

    /// Retrieves the US-only price-target summary for one ticker.
    pub async fn price_target_summary(
        &self,
        query: impl Into<PriceTargetSummaryQuery>,
    ) -> Result<Vec<PriceTargetSummary>> {
        self.execute(&price_target_summary(query.into())).await
    }

    /// Retrieves the US-only price-target consensus for one ticker.
    pub async fn price_target_consensus(
        &self,
        query: impl Into<PriceTargetConsensusQuery>,
    ) -> Result<Vec<PriceTargetConsensus>> {
        self.execute(&price_target_consensus(query.into())).await
    }

    /// Retrieves current worldwide stock-grade actions for one ticker.
    pub async fn stock_grades(
        &self,
        query: impl Into<StockGradesQuery>,
    ) -> Result<Vec<StockGrade>> {
        self.execute(&stock_grades(query.into())).await
    }

    /// Retrieves worldwide historical stock-grade counts for one ticker.
    pub async fn historical_stock_grades(
        &self,
        query: impl Into<HistoricalStockGradesQuery>,
    ) -> Result<Vec<HistoricalStockGrade>> {
        self.execute(&historical_stock_grades(query.into())).await
    }

    /// Retrieves the worldwide stock-grades summary for one ticker.
    pub async fn stock_grades_summary(
        &self,
        query: impl Into<StockGradesSummaryQuery>,
    ) -> Result<Vec<StockGradesSummary>> {
        self.execute(&stock_grades_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 estimates_encode_exact_keys_and_order() {
        let query = FinancialEstimatesQuery::new(
            Ticker::new("BRK.B / Class A").unwrap(),
            RetrievalFrequency::Quarterly,
        )
        .with_page(Page(0))
        .with_limit(Limit(u32::MAX));
        assert_eq!(
            pairs(&query),
            [
                ("symbol".to_owned(), "BRK.B / Class A".to_owned()),
                ("period".to_owned(), "quarter".to_owned()),
                ("page".to_owned(), "0".to_owned()),
                ("limit".to_owned(), u32::MAX.to_string()),
            ]
        );
    }

    #[test]
    fn symbol_only_and_symbol_limit_queries_encode_exact_shapes() {
        let symbol = Ticker::new("AAPL").unwrap();
        assert_eq!(
            pairs(&RatingsSnapshotQuery::new(symbol.clone())),
            [("symbol".to_owned(), "AAPL".to_owned())]
        );
        assert_eq!(
            pairs(&HistoricalRatingsQuery::new(symbol.clone())),
            [("symbol".to_owned(), "AAPL".to_owned())]
        );
        assert_eq!(
            pairs(&HistoricalRatingsQuery::new(symbol.clone()).with_limit(Limit(0))),
            [
                ("symbol".to_owned(), "AAPL".to_owned()),
                ("limit".to_owned(), "0".to_owned()),
            ]
        );
        assert_eq!(
            pairs(&HistoricalStockGradesQuery::new(symbol).with_limit(Limit(u32::MAX))),
            [
                ("symbol".to_owned(), "AAPL".to_owned()),
                ("limit".to_owned(), u32::MAX.to_string()),
            ]
        );
    }
}