finance-query 3.0.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
//! Standalone risk analytics.
//!
//! Requires the **`risk`** feature flag (which implies **`indicators`**).
//!
//! Provides Value at Risk, Conditional VaR (Expected Shortfall),
//! Sharpe/Sortino/Calmar ratios, Omega Ratio, Kelly Criterion, beta, max
//! drawdown, Ulcer Index, Information Ratio, and tracking error as standalone
//! metrics — independent of the backtesting engine.
//!
//! # Quick Start
//!
//! ```no_run
//! use finance_query::{Ticker, Interval, TimeRange};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let ticker = Ticker::new("AAPL").await?;
//! let summary = ticker.risk(Interval::OneDay, TimeRange::OneYear, None).await?;
//!
//! println!("VaR (95%):      {:.2}%", summary.var_95 * 100.0);
//! println!("Max drawdown:   {:.2}%", summary.max_drawdown * 100.0);
//! if let Some(sharpe) = summary.sharpe {
//!     println!("Sharpe ratio:   {sharpe:.2}");
//! }
//! # Ok(())
//! # }
//! ```

mod beta;
mod cvar;
mod drawdown;
mod ratios;
mod var;

pub use self::beta::beta;
pub use self::cvar::{historical_cvar, parametric_cvar};
pub use self::drawdown::max_drawdown;
pub use self::ratios::{
    calmar_ratio, information_ratio, kelly_criterion, omega_ratio, sharpe_ratio, sortino_ratio,
    tracking_error, ulcer_index, win_loss_stats,
};
pub use self::var::{historical_var, parametric_var};

use crate::models::chart::Candle;
use serde::{Deserialize, Serialize};

/// Comprehensive risk summary for a symbol.
///
/// Obtain via [`Ticker::risk`](crate::Ticker::risk).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RiskSummary {
    /// 1-day historical Value at Risk at 95% confidence (expressed as positive loss fraction)
    pub var_95: f64,
    /// 1-day historical Value at Risk at 99% confidence
    pub var_99: f64,
    /// 1-day parametric VaR at 95% confidence (assumes normally distributed returns)
    pub parametric_var_95: f64,
    /// 1-day historical Conditional VaR (Expected Shortfall) at 95% confidence —
    /// the average loss in the worst 5% of historical periods.
    pub cvar_95: f64,
    /// 1-day historical Conditional VaR at 99% confidence.
    pub cvar_99: f64,
    /// 1-day parametric Conditional VaR at 95% confidence (assumes normally
    /// distributed returns).
    pub parametric_cvar_95: f64,
    /// Omega Ratio at a 0.0 threshold: probability-weighted ratio of gains to
    /// losses over the full return distribution. `f64::MAX` when there are no
    /// negative-return periods.
    pub omega: f64,
    /// Kelly Criterion: optimal fraction of capital to risk, treating each
    /// positive-return period as a "win" and each negative-return period as a
    /// "loss". `f64::MAX` when there are no losing periods and wins are
    /// positive (unbounded edge).
    pub kelly: f64,
    /// Annualised Sharpe Ratio (risk-free rate = 0, 252 trading days/year).
    /// `None` when fewer than 2 periods or zero volatility.
    pub sharpe: Option<f64>,
    /// Annualised Sortino Ratio (penalises only downside volatility).
    /// `None` when fewer than 2 periods or zero downside deviation.
    pub sortino: Option<f64>,
    /// Calmar Ratio (annualised return / max drawdown).
    /// `None` when max drawdown is zero.
    pub calmar: Option<f64>,
    /// Beta vs benchmark. `None` when no benchmark is provided or data is insufficient.
    pub beta: Option<f64>,
    /// Maximum drawdown as a positive fraction (e.g., 0.30 = 30%)
    pub max_drawdown: f64,
    /// Number of trading periods to recover from the maximum drawdown.
    /// `None` when no recovery occurred within the data window.
    pub max_drawdown_recovery_periods: Option<u64>,
    /// Ulcer Index: root-mean-square of drawdown depth across all periods,
    /// expressed as a percentage (0–100). Penalises both depth and duration of
    /// drawdowns, unlike `max_drawdown` which only reports the worst single one.
    pub ulcer_index: f64,
    /// Information Ratio vs benchmark: annualised mean excess return divided by
    /// tracking error. `None` when no benchmark is provided or data is insufficient.
    pub information_ratio: Option<f64>,
    /// Tracking error vs benchmark: annualised standard deviation of
    /// (asset − benchmark) periodic returns. `None` when no benchmark is
    /// provided or data is insufficient.
    pub tracking_error: Option<f64>,
}

/// Compute returns from a slice of candles (simple daily returns: close-to-close).
pub(crate) fn candles_to_returns(candles: &[Candle]) -> Vec<f64> {
    candles
        .windows(2)
        .map(|w| (w[1].close - w[0].close) / w[0].close)
        .collect()
}

/// Trading calendar used to annualise risk ratios — different asset classes
/// have different period counts per year.
// Which variants are constructed depends on enabled provider features (each
// domain handle picks one), so some are unused under a given feature set.
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TradingCalendar {
    /// Exchange-traded (equities, indices, futures, commodities): 252 trading
    /// days, ~6.5h sessions.
    Exchange,
    /// Foreign exchange: 24h trading, 5 days/week (~260 days/year).
    Forex,
    /// Crypto: continuous 24/7 trading (365 days/year).
    Crypto,
}

// Only constructed/called by the domain-handle `risk()` macro in
// `src/domains/mod.rs`, gated behind provider features (alphavantage, fmp,
// polygon, crypto, ...) that may all be disabled under a narrower feature
// set (e.g. `--features indicators,risk,backtesting` alone), same reasoning
// as the `#[allow(dead_code)]` on `TradingCalendar` above.
#[allow(dead_code)]
impl TradingCalendar {
    fn trading_days(self) -> f64 {
        match self {
            TradingCalendar::Exchange => 252.0,
            TradingCalendar::Forex => 260.0,
            TradingCalendar::Crypto => 365.0,
        }
    }

    fn session_hours(self) -> f64 {
        match self {
            TradingCalendar::Exchange => 6.5,
            TradingCalendar::Forex | TradingCalendar::Crypto => 24.0,
        }
    }
}

/// Number of `interval` periods in a trading year for the given calendar — the
/// annualisation factor for Sharpe/Sortino/Calmar. Day/week/month/quarter are
/// exact; intraday scales the daily count by the session length.
#[allow(dead_code)]
pub(crate) fn periods_per_year(interval: crate::Interval, cal: TradingCalendar) -> f64 {
    use crate::Interval;
    let days = cal.trading_days();
    match interval {
        Interval::OneDay => days,
        Interval::FiveDays | Interval::OneWeek => 52.0,
        Interval::OneMonth => 12.0,
        Interval::ThreeMonths => 4.0,
        Interval::NinetyMinutes => days * cal.session_hours() / 1.5,
        Interval::OneHour => days * cal.session_hours(),
        Interval::ThirtyMinutes => days * cal.session_hours() * 2.0,
        Interval::FifteenMinutes => days * cal.session_hours() * 4.0,
        Interval::FiveMinutes => days * cal.session_hours() * 12.0,
        Interval::TwoMinutes => days * cal.session_hours() * 30.0,
        Interval::OneMinute => days * cal.session_hours() * 60.0,
    }
}

/// Build a [`RiskSummary`] from candle data and an optional benchmark return
/// series, using the default daily exchange calendar (252 periods/year).
pub(crate) fn compute_risk_summary(
    candles: &[Candle],
    benchmark_returns: Option<&[f64]>,
) -> RiskSummary {
    compute_risk_summary_with_periods(candles, benchmark_returns, 252.0)
}

/// Build a [`RiskSummary`] with an explicit annualisation factor
/// (`periods_per_year`), so non-daily intervals and non-equity asset classes
/// annualise correctly. See [`periods_per_year`].
pub(crate) fn compute_risk_summary_with_periods(
    candles: &[Candle],
    benchmark_returns: Option<&[f64]>,
    periods_per_year: f64,
) -> RiskSummary {
    let returns = candles_to_returns(candles);

    let mut sorted = returns.clone();
    sorted.sort_by(|a, b| a.total_cmp(b));
    let stats = ratios::mean_and_std(&returns);

    let var_95 = var::historical_var_sorted(&sorted, 0.95).unwrap_or(0.0);
    let var_99 = var::historical_var_sorted(&sorted, 0.99).unwrap_or(0.0);
    let parametric_var_95 = stats
        .map(|(m, s)| var::parametric_var_with_stats(m, s, 0.95))
        .unwrap_or(0.0);

    let cvar_95 = cvar::historical_cvar_sorted(&sorted, 0.95).unwrap_or(0.0);
    let cvar_99 = cvar::historical_cvar_sorted(&sorted, 0.99).unwrap_or(0.0);
    let parametric_cvar_95 = stats
        .map(|(m, s)| cvar::parametric_cvar_with_stats(m, s, 0.95))
        .unwrap_or(0.0);

    let omega = omega_ratio(&returns);
    let (win_rate, avg_win_pct, avg_loss_pct) = win_loss_stats(&returns);
    let kelly = kelly_criterion(win_rate, avg_win_pct, avg_loss_pct);

    let sharpe = stats.and_then(|(m, s)| ratios::sharpe_with_stats(m, s, 0.0, periods_per_year));
    let sortino = sortino_ratio(&returns, 0.0, periods_per_year);

    let dd = max_drawdown(&returns);
    let total_return = returns.iter().fold(1.0_f64, |acc, r| acc * (1.0 + r)) - 1.0;
    let years = returns.len() as f64 / periods_per_year;
    let calmar = calmar_ratio(total_return, years, dd.max_drawdown);
    let ulcer_index_val = ulcer_index(&returns);

    let beta_val = benchmark_returns.and_then(|br| beta(&returns, br));
    let information_ratio_val =
        benchmark_returns.and_then(|br| information_ratio(&returns, br, periods_per_year));
    let tracking_error_val =
        benchmark_returns.and_then(|br| tracking_error(&returns, br, periods_per_year));

    RiskSummary {
        var_95,
        var_99,
        parametric_var_95,
        cvar_95,
        cvar_99,
        parametric_cvar_95,
        omega,
        kelly,
        sharpe,
        sortino,
        calmar,
        beta: beta_val,
        max_drawdown: dd.max_drawdown,
        max_drawdown_recovery_periods: dd.recovery_periods,
        ulcer_index: ulcer_index_val,
        information_ratio: information_ratio_val,
        tracking_error: tracking_error_val,
    }
}

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

    fn make_candle(close: f64) -> Candle {
        Candle {
            timestamp: 0,
            open: close,
            high: close,
            low: close,
            close,
            volume: 1_000_000,
            adj_close: None,
            provider_id: None,
        }
    }

    #[test]
    fn test_compute_risk_summary_flat() {
        // Constant prices → zero returns → zero VaR, no ratios
        let candles: Vec<Candle> = (0..=252).map(|_| make_candle(100.0)).collect();
        let summary = compute_risk_summary(&candles, None);
        assert_eq!(summary.var_95, 0.0);
        assert_eq!(summary.max_drawdown, 0.0);
        assert!(summary.sharpe.is_none());
        // New metrics: degenerate for a flat (zero-return) series.
        assert_eq!(summary.cvar_95, 0.0);
        assert_eq!(summary.cvar_99, 0.0);
        assert_eq!(summary.parametric_cvar_95, 0.0);
        assert_eq!(summary.omega, 0.0);
        assert_eq!(summary.kelly, 0.0);
        assert_eq!(summary.ulcer_index, 0.0);
        assert!(summary.information_ratio.is_none());
        assert!(summary.tracking_error.is_none());
    }

    #[test]
    fn test_cvar_at_least_as_severe_as_var() {
        // A volatile, mostly-declining series should have CVaR >= VaR (CVaR
        // averages the tail beyond the VaR threshold, so it's at least as bad).
        let closes: Vec<f64> = (0..60)
            .map(|i| 100.0 - i as f64 * 0.5 + if i % 5 == 0 { -8.0 } else { 0.0 })
            .collect();
        let candles: Vec<Candle> = closes.into_iter().map(make_candle).collect();
        let summary = compute_risk_summary(&candles, None);
        assert!(
            summary.cvar_95 >= summary.var_95,
            "cvar_95 ({}) should be >= var_95 ({})",
            summary.cvar_95,
            summary.var_95
        );
        assert!(summary.parametric_cvar_95 >= summary.parametric_var_95);
    }

    #[test]
    fn test_drawdown_produces_positive_ulcer_index() {
        // A single sharp drawdown followed by recovery should score a
        // positive (nonzero) Ulcer Index.
        let closes = [100.0, 110.0, 80.0, 85.0, 105.0, 115.0];
        let candles: Vec<Candle> = closes.into_iter().map(make_candle).collect();
        let summary = compute_risk_summary(&candles, None);
        assert!(summary.ulcer_index > 0.0);
        assert!(summary.max_drawdown > 0.0);
    }

    #[test]
    fn test_information_ratio_and_tracking_error_with_benchmark() {
        let asset_closes: Vec<f64> = (0..30).map(|i| 100.0 + i as f64 * 1.2).collect();
        let bench_closes: Vec<f64> = (0..30).map(|i| 100.0 + i as f64 * 0.8).collect();
        let candles: Vec<Candle> = asset_closes.into_iter().map(make_candle).collect();
        let bench_candles: Vec<Candle> = bench_closes.into_iter().map(make_candle).collect();
        let bench_returns = candles_to_returns(&bench_candles);

        let summary = compute_risk_summary(&candles, Some(&bench_returns));
        assert!(summary.information_ratio.is_some());
        assert!(summary.tracking_error.is_some());
        assert!(summary.tracking_error.unwrap() > 0.0);
        // Asset outperforms the benchmark every period -> positive excess return.
        assert!(summary.information_ratio.unwrap() > 0.0);
    }

    #[test]
    fn test_candles_to_returns_basic() {
        let candles = vec![make_candle(100.0), make_candle(110.0), make_candle(99.0)];
        let returns = candles_to_returns(&candles);
        assert_eq!(returns.len(), 2);
        assert!((returns[0] - 0.10).abs() < 1e-9);
        assert!((returns[1] - (-0.1)).abs() < 0.01);
    }

    #[test]
    fn test_candles_to_returns_empty_and_single() {
        assert!(candles_to_returns(&[]).is_empty());
        assert!(candles_to_returns(&[make_candle(100.0)]).is_empty());

        let empty_summary = compute_risk_summary(&[], None);
        assert_eq!(empty_summary.var_95, 0.0);
        assert_eq!(empty_summary.var_99, 0.0);
        assert_eq!(empty_summary.parametric_var_95, 0.0);
        assert!(empty_summary.sharpe.is_none());

        let single_summary = compute_risk_summary(&[make_candle(100.0)], None);
        assert_eq!(single_summary.var_95, 0.0);
        assert_eq!(single_summary.var_99, 0.0);
        assert_eq!(single_summary.parametric_var_95, 0.0);
        assert!(single_summary.sharpe.is_none());
    }

    #[test]
    fn test_periods_per_year_by_calendar() {
        use crate::Interval;
        // Daily differs by asset class; calendar periodicity is shared.
        assert_eq!(
            periods_per_year(Interval::OneDay, TradingCalendar::Exchange),
            252.0
        );
        assert_eq!(
            periods_per_year(Interval::OneDay, TradingCalendar::Forex),
            260.0
        );
        assert_eq!(
            periods_per_year(Interval::OneDay, TradingCalendar::Crypto),
            365.0
        );
        assert_eq!(
            periods_per_year(Interval::OneWeek, TradingCalendar::Crypto),
            52.0
        );
        // Intraday scales daily count by session length (24h crypto > 6.5h exchange).
        assert!(
            periods_per_year(Interval::OneHour, TradingCalendar::Crypto)
                > periods_per_year(Interval::OneHour, TradingCalendar::Exchange)
        );
    }

    #[test]
    fn test_annualization_factor_changes_sharpe() {
        // Same returns, different periods_per_year → different annualised Sharpe.
        let candles: Vec<Candle> = (0..50).map(|i| make_candle(100.0 + i as f64)).collect();
        let daily = compute_risk_summary_with_periods(&candles, None, 252.0);
        let crypto = compute_risk_summary_with_periods(&candles, None, 365.0);
        assert!(daily.sharpe.is_some() && crypto.sharpe.is_some());
        assert!(crypto.sharpe.unwrap() > daily.sharpe.unwrap());
    }

    #[test]
    fn shared_stats_match_standalone_functions() {
        let returns: Vec<f64> = (0..2_000)
            .map(|i| ((i as f64 * 0.37).sin()) * 0.02 - 0.0001)
            .collect();

        let mut sorted = returns.clone();
        sorted.sort_by(|a, b| a.total_cmp(b));
        let (mean, std_dev) = crate::risk::ratios::mean_and_std(&returns).unwrap();

        assert_eq!(
            crate::risk::var::historical_var_sorted(&sorted, 0.95),
            crate::risk::historical_var(&returns, 0.95)
        );
        assert_eq!(
            crate::risk::var::historical_var_sorted(&sorted, 0.99),
            crate::risk::historical_var(&returns, 0.99)
        );
        assert_eq!(
            Some(crate::risk::var::parametric_var_with_stats(
                mean, std_dev, 0.95
            )),
            crate::risk::parametric_var(&returns, 0.95)
        );
        assert_eq!(
            crate::risk::ratios::sharpe_with_stats(mean, std_dev, 0.0, 252.0),
            crate::risk::sharpe_ratio(&returns, 0.0, 252.0)
        );
    }
}