nautilus_analysis/python/statistics/value_at_risk.rs
1// -------------------------------------------------------------------------------------------------
2// Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3// https://nautechsystems.io
4//
5// Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6// You may not use this file except in compliance with the License.
7// You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::collections::BTreeMap;
17
18use nautilus_core::python::to_pyvalue_err;
19use nautilus_model::position::Position;
20use pyo3::prelude::*;
21
22use super::transform_returns;
23use crate::{statistic::PortfolioStatistic, statistics::value_at_risk::ValueAtRisk};
24
25#[pymethods]
26#[pyo3_stub_gen::derive::gen_stub_pymethods]
27impl ValueAtRisk {
28 /// Calculates the historical Value at Risk (`VaR`) of portfolio returns.
29 ///
30 /// `VaR` is the loss threshold that returns are not expected to exceed at a given
31 /// confidence level. This is the non-parametric (historical) estimator: the
32 /// empirical quantile of the return distribution at `1 - confidence`.
33 ///
34 /// `VaR(c) = quantile(returns, 1 - c)`
35 ///
36 /// The quantile uses linear interpolation between closest ranks (matching
37 /// `numpy.percentile`). `confidence` defaults to `0.95`. The result is expressed
38 /// as a return (e.g. `-0.03` is a 3% loss threshold); more negative means greater
39 /// risk. Returns `NaN` for an empty series.
40 ///
41 /// # References
42 ///
43 /// - Jorion, P. (2007). *Value at Risk: The New Benchmark for Managing Financial Risk*
44 /// (3rd ed.). McGraw-Hill.
45 /// - J.P. Morgan/Reuters (1996). *RiskMetrics Technical Document* (4th ed.).
46 #[expect(
47 clippy::doc_markdown,
48 reason = "citation contains proper nouns with intra-word capitals"
49 )]
50 #[new]
51 #[pyo3(signature = (confidence=None))]
52 fn py_new(confidence: Option<f64>) -> PyResult<Self> {
53 Self::new_checked(confidence).map_err(to_pyvalue_err)
54 }
55
56 fn __repr__(&self) -> String {
57 self.to_string()
58 }
59
60 #[getter]
61 #[pyo3(name = "name")]
62 fn py_name(&self) -> String {
63 self.name()
64 }
65
66 #[pyo3(name = "calculate_from_returns")]
67 #[expect(clippy::needless_pass_by_value)]
68 fn py_calculate_from_returns(&mut self, raw_returns: BTreeMap<u64, f64>) -> Option<f64> {
69 self.calculate_from_returns(&transform_returns(&raw_returns))
70 }
71
72 #[pyo3(name = "calculate_from_realized_pnls")]
73 fn py_calculate_from_realized_pnls(&mut self, _realized_pnls: Vec<f64>) -> Option<f64> {
74 None
75 }
76
77 #[pyo3(name = "calculate_from_positions")]
78 fn py_calculate_from_positions(&mut self, _positions: Vec<Position>) -> Option<f64> {
79 None
80 }
81}