finance-query 2.5.0

A Rust library for querying financial data
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
//! FMP company information endpoints.

use serde::{Deserialize, Serialize};

use crate::adapters::common::encode_path_segment;
use crate::error::Result;

// ============================================================================
// Response types
// ============================================================================

/// Company profile from FMP.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CompanyProfile {
    /// Ticker symbol.
    pub symbol: Option<String>,
    /// Current price.
    pub price: Option<f64>,
    /// Beta.
    pub beta: Option<f64>,
    /// Volume average.
    #[serde(rename = "volAvg")]
    pub vol_avg: Option<f64>,
    /// Market capitalization.
    #[serde(rename = "mktCap")]
    pub mkt_cap: Option<f64>,
    /// Last dividend.
    #[serde(rename = "lastDiv")]
    pub last_div: Option<f64>,
    /// 52-week range.
    pub range: Option<String>,
    /// Price changes.
    pub changes: Option<f64>,
    /// Company name.
    #[serde(rename = "companyName")]
    pub company_name: Option<String>,
    /// Currency.
    pub currency: Option<String>,
    /// CIK number.
    pub cik: Option<String>,
    /// ISIN.
    pub isin: Option<String>,
    /// CUSIP.
    pub cusip: Option<String>,
    /// Exchange name.
    pub exchange: Option<String>,
    /// Exchange short name.
    #[serde(rename = "exchangeShortName")]
    pub exchange_short_name: Option<String>,
    /// Industry.
    pub industry: Option<String>,
    /// Website.
    pub website: Option<String>,
    /// Company description.
    pub description: Option<String>,
    /// CEO.
    pub ceo: Option<String>,
    /// Sector.
    pub sector: Option<String>,
    /// Country.
    pub country: Option<String>,
    /// Full-time employees.
    #[serde(rename = "fullTimeEmployees")]
    pub full_time_employees: Option<String>,
    /// Phone number.
    pub phone: Option<String>,
    /// Address.
    pub address: Option<String>,
    /// City.
    pub city: Option<String>,
    /// State.
    pub state: Option<String>,
    /// ZIP code.
    pub zip: Option<String>,
    /// DCF difference.
    #[serde(rename = "dcfDiff")]
    pub dcf_diff: Option<f64>,
    /// DCF value.
    pub dcf: Option<f64>,
    /// Image/logo URL.
    pub image: Option<String>,
    /// IPO date.
    #[serde(rename = "ipoDate")]
    pub ipo_date: Option<String>,
    /// Default image flag.
    #[serde(rename = "defaultImage")]
    pub default_image: Option<bool>,
    /// Is ETF.
    #[serde(rename = "isEtf")]
    pub is_etf: Option<bool>,
    /// Is actively trading.
    #[serde(rename = "isActivelyTrading")]
    pub is_actively_trading: Option<bool>,
    /// Is ADR.
    #[serde(rename = "isAdr")]
    pub is_adr: Option<bool>,
    /// Is fund.
    #[serde(rename = "isFund")]
    pub is_fund: Option<bool>,
}

/// Key executive from FMP.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct KeyExecutive {
    /// Executive title.
    pub title: Option<String>,
    /// Executive name.
    pub name: Option<String>,
    /// Pay.
    pub pay: Option<f64>,
    /// Currency of pay.
    #[serde(rename = "currencyPay")]
    pub currency_pay: Option<String>,
    /// Gender.
    pub gender: Option<String>,
    /// Year born.
    #[serde(rename = "yearBorn")]
    pub year_born: Option<i32>,
    /// Title since.
    #[serde(rename = "titleSince")]
    pub title_since: Option<String>,
}

/// Market capitalization from FMP.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MarketCap {
    /// Ticker symbol.
    pub symbol: Option<String>,
    /// Date.
    pub date: Option<String>,
    /// Market capitalization.
    #[serde(rename = "marketCap")]
    pub market_cap: Option<f64>,
}

/// Company outlook from FMP (v4 endpoint).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CompanyOutlook {
    /// Profile section.
    pub profile: Option<CompanyProfile>,
    /// Metrics section.
    pub metrics: Option<serde_json::Value>,
    /// Ratios section.
    pub ratios: Option<Vec<serde_json::Value>>,
    /// Insider trading section.
    #[serde(rename = "insideTrades")]
    pub inside_trades: Option<Vec<serde_json::Value>>,
    /// Key executives.
    #[serde(rename = "keyExecutives")]
    pub key_executives: Option<Vec<KeyExecutive>>,
    /// Stock news.
    #[serde(rename = "stockNews")]
    pub stock_news: Option<Vec<serde_json::Value>>,
    /// Rating section.
    pub rating: Option<Vec<serde_json::Value>>,
}

/// Stock peer from FMP (v4 endpoint).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct StockPeers {
    /// Ticker symbol.
    pub symbol: Option<String>,
    /// List of peer symbols.
    #[serde(rename = "peersList")]
    pub peers_list: Option<Vec<String>>,
}

/// Delisted company from FMP.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DelistedCompany {
    /// Ticker symbol.
    pub symbol: Option<String>,
    /// Company name.
    #[serde(rename = "companyName")]
    pub company_name: Option<String>,
    /// Exchange.
    pub exchange: Option<String>,
    /// IPO date.
    #[serde(rename = "ipoDate")]
    pub ipo_date: Option<String>,
    /// Delisted date.
    #[serde(rename = "delistedDate")]
    pub delisted_date: Option<String>,
}

// ============================================================================
// Query functions
// ============================================================================

/// Fetch company profile for a symbol.
pub async fn company_profile(symbol: &str) -> Result<Vec<CompanyProfile>> {
    let client = super::build_client()?;
    client
        .get(
            &format!("/api/v3/profile/{}", encode_path_segment(symbol)),
            &[],
        )
        .await
}

/// Fetch key executives for a symbol.
pub async fn key_executives(symbol: &str) -> Result<Vec<KeyExecutive>> {
    let client = super::build_client()?;
    client
        .get(
            &format!("/api/v3/key-executives/{}", encode_path_segment(symbol)),
            &[],
        )
        .await
}

/// Fetch market capitalization for a symbol.
pub async fn market_cap(symbol: &str) -> Result<Vec<MarketCap>> {
    let client = super::build_client()?;
    client
        .get(
            &format!(
                "/api/v3/market-capitalization/{}",
                encode_path_segment(symbol)
            ),
            &[],
        )
        .await
}

/// Fetch historical market capitalization for a symbol.
pub async fn historical_market_cap(symbol: &str, limit: Option<u32>) -> Result<Vec<MarketCap>> {
    let client = super::build_client()?;
    let limit_str = limit.unwrap_or(100).to_string();
    client
        .get(
            &format!(
                "/api/v3/historical-market-capitalization/{}",
                encode_path_segment(symbol)
            ),
            &[("limit", &limit_str)],
        )
        .await
}

/// Fetch company outlook for a symbol (v4 endpoint).
pub async fn company_outlook(symbol: &str) -> Result<CompanyOutlook> {
    let client = super::build_client()?;
    client
        .get("/api/v4/company-outlook", &[("symbol", symbol)])
        .await
}

/// Fetch stock peers for a symbol (v4 endpoint).
pub async fn stock_peers(symbol: &str) -> Result<Vec<StockPeers>> {
    let client = super::build_client()?;
    client
        .get("/api/v4/stock_peers", &[("symbol", symbol)])
        .await
}

/// Fetch delisted companies.
pub async fn delisted_companies(limit: Option<u32>) -> Result<Vec<DelistedCompany>> {
    let client = super::build_client()?;
    let limit_str = limit.unwrap_or(100).to_string();
    client
        .get("/api/v3/delisted-companies", &[("limit", &limit_str)])
        .await
}

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

    #[tokio::test]
    async fn test_company_profile_mock() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/api/v3/profile/AAPL")
            .match_query(mockito::Matcher::AllOf(vec![mockito::Matcher::UrlEncoded(
                "apikey".into(),
                "test-key".into(),
            )]))
            .with_status(200)
            .with_body(
                serde_json::json!([{
                    "symbol": "AAPL",
                    "price": 178.72,
                    "beta": 1.286,
                    "volAvg": 58405568,
                    "mktCap": 2794000000000_f64,
                    "companyName": "Apple Inc.",
                    "currency": "USD",
                    "exchange": "NASDAQ Global Select",
                    "exchangeShortName": "NASDAQ",
                    "industry": "Consumer Electronics",
                    "sector": "Technology",
                    "country": "US",
                    "ceo": "Mr. Timothy D. Cook",
                    "isEtf": false,
                    "isActivelyTrading": true
                }])
                .to_string(),
            )
            .create_async()
            .await;

        let client = super::super::build_test_client(&server.url()).unwrap();
        let result: Vec<CompanyProfile> = client.get("/api/v3/profile/AAPL", &[]).await.unwrap();

        assert_eq!(result.len(), 1);
        assert_eq!(result[0].symbol.as_deref(), Some("AAPL"));
        assert_eq!(result[0].company_name.as_deref(), Some("Apple Inc."));
        assert_eq!(result[0].sector.as_deref(), Some("Technology"));
        assert_eq!(result[0].is_etf, Some(false));
    }

    #[tokio::test]
    async fn test_key_executives_mock() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", "/api/v3/key-executives/AAPL")
            .match_query(mockito::Matcher::AllOf(vec![mockito::Matcher::UrlEncoded(
                "apikey".into(),
                "test-key".into(),
            )]))
            .with_status(200)
            .with_body(
                serde_json::json!([
                    {
                        "title": "Chief Executive Officer",
                        "name": "Mr. Timothy D. Cook",
                        "pay": 16425933,
                        "currencyPay": "USD",
                        "gender": "male",
                        "yearBorn": 1960
                    },
                    {
                        "title": "Chief Financial Officer",
                        "name": "Mr. Luca Maestri",
                        "pay": 5019783,
                        "currencyPay": "USD",
                        "gender": "male",
                        "yearBorn": 1963
                    }
                ])
                .to_string(),
            )
            .create_async()
            .await;

        let client = super::super::build_test_client(&server.url()).unwrap();
        let result: Vec<KeyExecutive> = client
            .get("/api/v3/key-executives/AAPL", &[])
            .await
            .unwrap();

        assert_eq!(result.len(), 2);
        assert_eq!(result[0].name.as_deref(), Some("Mr. Timothy D. Cook"));
        assert_eq!(result[0].pay, Some(16425933.0));
    }

    #[tokio::test]
    async fn test_fmp_rate_limit_returns_rate_limited_error() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", mockito::Matcher::Any)
            .with_status(429)
            .with_body("{}")
            .create_async()
            .await;

        let client = crate::adapters::fmp::build_test_client(&server.url()).unwrap();
        let result = client.get_raw("/api/v3/profile/AAPL", &[]).await;

        assert!(matches!(
            result,
            Err(crate::error::FinanceError::RateLimited { .. })
        ));
    }

    #[tokio::test]
    async fn test_fmp_401_returns_authentication_failed() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", mockito::Matcher::Any)
            .with_status(401)
            .with_body("{}")
            .create_async()
            .await;

        let client = crate::adapters::fmp::build_test_client(&server.url()).unwrap();
        let result = client.get_raw("/api/v3/profile/AAPL", &[]).await;

        assert!(matches!(
            result,
            Err(crate::error::FinanceError::AuthenticationFailed { .. })
        ));
    }

    #[tokio::test]
    async fn test_fmp_body_error_message_returns_invalid_parameter() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", mockito::Matcher::Any)
            .with_status(200)
            .with_body(r#"{"Error Message":"Invalid API KEY."}"#)
            .create_async()
            .await;

        let client = crate::adapters::fmp::build_test_client(&server.url()).unwrap();
        let result = client.get_raw("/api/v3/profile/AAPL", &[]).await;

        assert!(matches!(
            result,
            Err(crate::error::FinanceError::InvalidParameter { .. })
        ));
    }

    #[tokio::test]
    async fn test_fmp_500_returns_server_error() {
        let mut server = mockito::Server::new_async().await;
        let _mock = server
            .mock("GET", mockito::Matcher::Any)
            .with_status(500)
            .with_body("{}")
            .create_async()
            .await;

        let client = crate::adapters::fmp::build_test_client(&server.url()).unwrap();
        let result = client.get_raw("/api/v3/profile/AAPL", &[]).await;

        assert!(matches!(
            result,
            Err(crate::error::FinanceError::ServerError { .. })
        ));
    }
}