diff --git a/crates/RustQuant_math/src/lib.rs b/crates/RustQuant_math/src/lib.rs index 018db858..8cee417d 100644 --- a/crates/RustQuant_math/src/lib.rs +++ b/crates/RustQuant_math/src/lib.rs @@ -98,3 +98,7 @@ pub use sequences::*; /// Statistic trait. pub mod statistic; pub use statistic::*; + +/// Value-at-Risk and Expected Shortfall computation. +pub mod var; +pub use var::*; diff --git a/crates/RustQuant_math/src/var.rs b/crates/RustQuant_math/src/var.rs new file mode 100644 index 00000000..cb6a00a0 --- /dev/null +++ b/crates/RustQuant_math/src/var.rs @@ -0,0 +1,167 @@ +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// RustQuant: A Rust library for quantitative finance tools. +// Copyright (C) 2023 https://github.com/avhz +// Dual licensed under Apache 2.0 and MIT. +// See: +// - LICENSE-APACHE.md +// - LICENSE-MIT.md +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +//! Value-at-Risk (VaR) and Expected Shortfall (CVaR) computation. +//! +//! Sign convention: inputs are periodic simple returns expressed as decimals +//! (e.g. `-0.021` means a 2.1% loss). VaR and Expected Shortfall are returned +//! as signed losses (positive for losses, negative for gains) in decimal units, so a VaR of +//! `0.03` at 95% means "with 95% confidence we do not lose more than 3% over +//! one period". + +use crate::distributions::{Distribution, N}; +use crate::statistic::Statistic; + +/// Historical Value-at-Risk. +/// +/// The negative of the lower-tail empirical quantile of the return series, +/// using the same type-7 (linear interpolation) quantile as +/// [`Statistic::quantile`]. `alpha` is the left-tail probability +/// (`0.05` for 95% confidence, `0.01` for 99%). +/// +/// # Examples +/// ``` +/// use RustQuant::math::var::historical_var; +/// +/// let returns = vec![-0.05, -0.04, -0.03, -0.02, -0.01, 0.00, 0.01, 0.02, 0.03, 0.04]; +/// // type-7 quantile at 0.05 over 10 points -> -0.0455, negated -> 0.0455 +/// assert!((historical_var(returns, 0.05) - 0.0455).abs() < 1e-12); +/// ``` +#[must_use] +pub fn historical_var(returns: Vec, alpha: f64) -> f64 { + assert!( + !returns.is_empty(), + "Returns must have at least one element." + ); + assert!( + (0.0..=1.0).contains(&alpha), + "Alpha must be between 0 and 1." + ); + + -returns.quantile(alpha) +} + +/// Parametric (Gaussian) Value-at-Risk. +/// +/// Assumes returns are normally distributed and computes +/// `-(mu + Phi^{-1}(alpha) * sigma)` using the population standard deviation, +/// so the observed sample is treated as the entire distribution. `alpha` is +/// the left-tail probability. +/// +/// # Examples +/// ``` +/// use RustQuant::math::var::parametric_var; +/// +/// // Standard normal returns with alpha = 0.05: Phi^{-1}(0.05) = -1.64485... +/// let returns = vec![-0.02, -0.01, 0.00, 0.01, 0.02]; +/// let var = parametric_var(returns, 0.05); +/// assert!(var > 0.0); +/// ``` +#[must_use] +pub fn parametric_var(returns: Vec, alpha: f64) -> f64 { + assert!( + returns.len() > 1, + "Returns must have at least two elements." + ); + assert!(alpha > 0.0 && alpha < 1.0, "Alpha must be between 0 and 1."); + + let mu = returns.mean(); + let sigma = returns.population_standard_deviation(); + // Inverse standard-normal CDF (Phi^{-1}(alpha)); negative for alpha < 0.5. + let z = N.inv_cdf(alpha); + + -(mu + z * sigma) +} + +/// Historical Expected Shortfall / Conditional VaR. +/// +/// The negative of the mean of all returns at or below the `alpha` quantile. +/// By construction this is greater than or equal to +/// [`historical_var`](historical_var) for the same `alpha`. +/// +/// # Examples +/// ``` +/// use RustQuant::math::var::{historical_var, expected_shortfall}; +/// +/// let returns = vec![-0.05, -0.04, -0.03, -0.02, -0.01, 0.00, 0.01, 0.02, 0.03, 0.04]; +/// let es = expected_shortfall(returns.clone(), 0.05); +/// assert!(es >= historical_var(returns, 0.05)); +/// ``` +#[must_use] +pub fn expected_shortfall(returns: Vec, alpha: f64) -> f64 { + assert!( + !returns.is_empty(), + "Returns must have at least one element." + ); + assert!( + (0.0..=1.0).contains(&alpha), + "Alpha must be between 0 and 1." + ); + + let q = returns.quantile(alpha); + let tail: Vec = returns.iter().copied().filter(|r| *r <= q).collect(); + + if tail.is_empty() { + return q.abs(); + } + + -tail.mean() +} + +// ############################################################################ +// TESTS +// ############################################################################ + +#[cfg(test)] +mod tests_var { + use super::*; + use crate::distributions::{Distribution, N}; + use crate::statistic::Statistic; + use RustQuant_utils::{assert_approx_equal, RUSTQUANT_EPSILON as EPS}; + + #[test] + fn test_historical_var_known() { + // Sorted: -5%, ..., +4% (10 points). type-7 q(0.05): h = 9*0.05 = 0.45, + // interpolate -5% -> -4% gives -4.55%, so VaR = 0.0455. + let returns = vec![ + -0.05, -0.04, -0.03, -0.02, -0.01, 0.00, 0.01, 0.02, 0.03, 0.04, + ]; + let var = historical_var(returns, 0.05); + assert_approx_equal!(var, 0.0455, EPS); + } + + #[test] + fn test_parametric_var_known() { + // Standard-normal sample, alpha = 0.05 -> z = -1.64485... + let returns = vec![-2.0, -1.0, 0.0, 1.0, 2.0]; + let mu = returns.mean(); // 0.0 + let sigma = returns.population_standard_deviation(); + let z = N.inv_cdf(0.05); + let var = parametric_var(returns, 0.05); + assert_approx_equal!(var, -(mu + z * sigma), EPS); + } + + #[test] + fn test_expected_shortfall_bounds_var() { + let returns = vec![ + -0.05, -0.04, -0.03, -0.02, -0.01, 0.00, 0.01, 0.02, 0.03, 0.04, + ]; + let es = expected_shortfall(returns.clone(), 0.05); + let var = historical_var(returns, 0.05); + assert!(es >= var, "expected shortfall must bound VaR"); + } + + #[test] + fn test_expected_shortfall_known() { + // 5 returns, alpha = 0.2 -> tail is the single worst return -0.05. + let returns = vec![-0.05, -0.01, 0.00, 0.01, 0.02]; + let es = expected_shortfall(returns, 0.2); + assert_approx_equal!(es, 0.05, EPS); + } +}