finance-query 2.8.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
440
use crate::providers::{Capability, Operation, Provider};
use thiserror::Error;

fn join_providers(providers: &[Provider]) -> String {
    providers
        .iter()
        .map(|p| p.as_str())
        .collect::<Vec<_>>()
        .join(", ")
}

/// Main error type for the library
#[derive(Error, Debug)]
pub enum FinanceError {
    /// Authentication failed (Yahoo Finance, SEC EDGAR, etc.)
    #[error("Authentication failed: {context}")]
    AuthenticationFailed {
        /// Error context
        context: String,
    },

    /// The requested symbol was not found
    #[error("Symbol not found: {}", symbol.as_deref().unwrap_or("unknown"))]
    SymbolNotFound {
        /// The symbol that was not found
        symbol: Option<String>,
        /// Additional context
        context: String,
    },

    /// Rate limit exceeded
    #[error("Rate limited (retry after {retry_after:?}s)")]
    RateLimited {
        /// Seconds until retry is allowed
        retry_after: Option<u64>,
    },

    /// HTTP request error
    #[error("HTTP request failed: {0}")]
    HttpError(#[from] reqwest::Error),

    /// Failed to parse JSON response
    #[error("JSON parse error: {0}")]
    JsonParseError(#[from] serde_json::Error),

    /// Response structure error - missing or malformed fields
    #[error("Response structure error in '{field}': {context}")]
    ResponseStructureError {
        /// Field name that caused the error
        field: String,
        /// Error context
        context: String,
    },

    /// Invalid parameter provided
    #[error("Invalid parameter '{param}': {reason}")]
    InvalidParameter {
        /// Parameter name
        param: String,
        /// Reason for invalidity
        reason: String,
    },

    /// Network timeout
    #[error("Request timeout after {timeout_ms}ms")]
    Timeout {
        /// Timeout duration in milliseconds
        timeout_ms: u64,
    },

    /// Server error (5xx status codes)
    #[error("Server error {status}: {context}")]
    ServerError {
        /// HTTP status code
        status: u16,
        /// Error context
        context: String,
    },

    /// Unexpected API response
    #[error("Unexpected response: {0}")]
    UnexpectedResponse(String),

    /// Internal error
    #[error("Internal error: {0}")]
    InternalError(String),

    /// General API error
    #[error("API error: {0}")]
    ApiError(String),

    /// Tokio runtime error
    #[error("Runtime error: {0}")]
    RuntimeError(#[from] std::io::Error),

    /// Indicator calculation error
    #[cfg(feature = "indicators")]
    #[error("Indicator calculation error: {0}")]
    IndicatorError(#[from] crate::indicators::IndicatorError),

    /// Error from an external (non-Yahoo) data API
    #[error("External API error from '{api}': HTTP {status}")]
    ExternalApiError {
        /// Name of the external API (e.g., "alternative.me", "coingecko")
        api: String,
        /// HTTP status code returned
        status: u16,
    },

    /// Error fetching or parsing macro-economic data (FRED, Treasury, BLS)
    #[error("Macro data error from '{provider}': {context}")]
    MacroDataError {
        /// Provider name (e.g., "FRED", "US Treasury")
        provider: String,
        /// Error context
        context: String,
    },

    /// Error parsing an RSS/Atom feed
    #[error("Feed parse error for '{url}': {context}")]
    FeedParseError {
        /// Feed URL that failed
        url: String,
        /// Error context
        context: String,
    },

    /// The requested operation is not supported by this provider.
    #[error(
        "{provider} does not support {operation} (supported by: {}; route it via Providers::builder().route(...))",
        join_providers(candidates)
    )]
    NotSupported {
        /// Provider identifier
        provider: Provider,
        /// The specific operation that isn't implemented
        operation: Operation,
        /// Other providers whose `capabilities()` declare this operation
        /// (informational — may still need a feature flag enabled and/or routing).
        candidates: Vec<Provider>,
    },

    /// No configured provider supports this operation or all providers failed.
    #[error(
        "no provider available for {operation} (supported by: {}; route it via Providers::builder().route(...))",
        join_providers(candidates)
    )]
    NoProviderAvailable {
        /// The capability no configured provider declared
        operation: Capability,
        /// Providers whose `capabilities()` declare this operation
        /// (informational — may still need a feature flag enabled and/or routing).
        candidates: Vec<Provider>,
    },

    /// Translation backend failure (model download, load, or inference)
    #[cfg(feature = "translation")]
    #[error("Translation error: {context}")]
    TranslationError {
        /// Error context
        context: String,
    },
}

/// Error category for logging and metrics
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorCategory {
    /// Authentication errors
    Auth,
    /// Rate limiting errors
    RateLimit,
    /// Timeout errors
    Timeout,
    /// Server errors (5xx)
    Server,
    /// Not found errors
    NotFound,
    /// Validation errors
    Validation,
    /// Parsing errors
    Parsing,
    /// Other errors
    Other,
}

/// Result type alias for library operations
pub type Result<T> = std::result::Result<T, FinanceError>;

impl FinanceError {
    /// Check if this error is retriable
    pub fn is_retriable(&self) -> bool {
        matches!(
            self,
            FinanceError::Timeout { .. }
                | FinanceError::RateLimited { .. }
                | FinanceError::HttpError(_)
                | FinanceError::AuthenticationFailed { .. }
                | FinanceError::ServerError { .. }
        ) || matches!(self, FinanceError::ExternalApiError { status, .. } if *status >= 500)
    }

    /// Check if this error indicates an authentication issue
    pub fn is_auth_error(&self) -> bool {
        matches!(self, FinanceError::AuthenticationFailed { .. })
    }

    /// Check if this error indicates a not found issue
    pub fn is_not_found(&self) -> bool {
        matches!(self, FinanceError::SymbolNotFound { .. })
    }

    /// Get retry delay in seconds (for exponential backoff)
    pub fn retry_after_secs(&self) -> Option<u64> {
        match self {
            Self::RateLimited { retry_after } => *retry_after,
            Self::Timeout { .. } => Some(2),
            Self::ServerError { status, .. } if *status >= 500 => Some(5),
            Self::AuthenticationFailed { .. } => Some(1),
            _ => None,
        }
    }

    /// Categorize errors for logging/metrics
    pub fn category(&self) -> ErrorCategory {
        match self {
            Self::AuthenticationFailed { .. } => ErrorCategory::Auth,
            Self::RateLimited { .. } => ErrorCategory::RateLimit,
            Self::Timeout { .. } => ErrorCategory::Timeout,
            Self::ServerError { .. } => ErrorCategory::Server,
            Self::SymbolNotFound { .. } => ErrorCategory::NotFound,
            Self::InvalidParameter { .. } => ErrorCategory::Validation,
            Self::JsonParseError(_)
            | Self::ResponseStructureError { .. }
            | Self::MacroDataError { .. }
            | Self::FeedParseError { .. } => ErrorCategory::Parsing,
            Self::NotSupported { .. } | Self::NoProviderAvailable { .. } => {
                ErrorCategory::Validation
            }
            Self::ExternalApiError { .. } => ErrorCategory::Server,
            _ => ErrorCategory::Other,
        }
    }

    /// Add symbol context to error (fluent API)
    pub fn with_symbol(mut self, symbol: impl Into<String>) -> Self {
        if let Self::SymbolNotFound {
            symbol: ref mut s, ..
        } = self
        {
            *s = Some(symbol.into());
        }
        self
    }

    /// Add context to error (fluent API)
    pub fn with_context(mut self, context: impl Into<String>) -> Self {
        match self {
            Self::AuthenticationFailed {
                context: ref mut c, ..
            } => {
                *c = context.into();
            }
            Self::SymbolNotFound {
                context: ref mut c, ..
            } => {
                *c = context.into();
            }
            Self::ResponseStructureError {
                context: ref mut c, ..
            } => {
                *c = context.into();
            }
            Self::ServerError {
                context: ref mut c, ..
            } => {
                *c = context.into();
            }
            Self::MacroDataError {
                context: ref mut c, ..
            } => {
                *c = context.into();
            }
            Self::FeedParseError {
                context: ref mut c, ..
            } => {
                *c = context.into();
            }
            _ => {}
        }
        self
    }
}

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

    #[test]
    fn test_error_is_retriable() {
        assert!(FinanceError::Timeout { timeout_ms: 5000 }.is_retriable());
        assert!(FinanceError::RateLimited { retry_after: None }.is_retriable());
        assert!(
            FinanceError::AuthenticationFailed {
                context: "test".to_string()
            }
            .is_retriable()
        );
        assert!(
            FinanceError::ServerError {
                status: 500,
                context: "test".to_string()
            }
            .is_retriable()
        );
        assert!(
            !FinanceError::SymbolNotFound {
                symbol: Some("AAPL".to_string()),
                context: "test".to_string()
            }
            .is_retriable()
        );
        assert!(
            !FinanceError::InvalidParameter {
                param: "test".to_string(),
                reason: "invalid".to_string()
            }
            .is_retriable()
        );
    }

    #[test]
    fn test_error_is_auth_error() {
        assert!(
            FinanceError::AuthenticationFailed {
                context: "test".to_string()
            }
            .is_auth_error()
        );
        assert!(!FinanceError::Timeout { timeout_ms: 5000 }.is_auth_error());
    }

    #[test]
    fn test_error_is_not_found() {
        assert!(
            FinanceError::SymbolNotFound {
                symbol: Some("AAPL".to_string()),
                context: "test".to_string()
            }
            .is_not_found()
        );
        assert!(!FinanceError::Timeout { timeout_ms: 5000 }.is_not_found());
    }

    #[test]
    fn test_retry_after_secs() {
        assert_eq!(
            FinanceError::RateLimited {
                retry_after: Some(10)
            }
            .retry_after_secs(),
            Some(10)
        );
        assert_eq!(
            FinanceError::Timeout { timeout_ms: 5000 }.retry_after_secs(),
            Some(2)
        );
        assert_eq!(
            FinanceError::ServerError {
                status: 503,
                context: "test".to_string()
            }
            .retry_after_secs(),
            Some(5)
        );
        assert_eq!(
            FinanceError::SymbolNotFound {
                symbol: None,
                context: "test".to_string()
            }
            .retry_after_secs(),
            None
        );
    }

    #[test]
    fn test_error_category() {
        assert_eq!(
            FinanceError::AuthenticationFailed {
                context: "test".to_string()
            }
            .category(),
            ErrorCategory::Auth
        );
        assert_eq!(
            FinanceError::RateLimited { retry_after: None }.category(),
            ErrorCategory::RateLimit
        );
        assert_eq!(
            FinanceError::Timeout { timeout_ms: 5000 }.category(),
            ErrorCategory::Timeout
        );
        assert_eq!(
            FinanceError::SymbolNotFound {
                symbol: None,
                context: "test".to_string()
            }
            .category(),
            ErrorCategory::NotFound
        );
    }

    #[test]
    fn test_with_symbol() {
        let error = FinanceError::SymbolNotFound {
            symbol: None,
            context: "test".to_string(),
        }
        .with_symbol("AAPL");

        if let FinanceError::SymbolNotFound { symbol, .. } = error {
            assert_eq!(symbol, Some("AAPL".to_string()));
        } else {
            panic!("Expected SymbolNotFound");
        }
    }

    #[test]
    fn test_with_context() {
        let error = FinanceError::AuthenticationFailed {
            context: "old".to_string(),
        }
        .with_context("new context");

        if let FinanceError::AuthenticationFailed { context } = error {
            assert_eq!(context, "new context");
        } else {
            panic!("Expected AuthenticationFailed");
        }
    }
}