Skip to main content

nautilus_analysis/statistics/
risk_return_ratio.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::fmt::Display;
17
18use nautilus_model::position::Position;
19
20use crate::{Returns, statistic::PortfolioStatistic};
21
22/// Calculates the risk-return ratio (mean/std) for portfolio returns.
23///
24/// This is a non-annualized ratio of mean return to standard deviation.
25/// For an annualized version, use `SharpeRatio`.
26///
27/// Downsamples high-frequency returns to daily bins before calculation
28/// for consistency with other ratio-based statistics.
29#[repr(C)]
30#[derive(Debug, Clone, Default)]
31#[cfg_attr(
32    feature = "python",
33    pyo3::pyclass(module = "nautilus_trader.analysis", from_py_object)
34)]
35#[cfg_attr(
36    feature = "python",
37    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.analysis")
38)]
39pub struct RiskReturnRatio {}
40
41impl RiskReturnRatio {
42    /// Creates a new [`RiskReturnRatio`] instance.
43    #[must_use]
44    pub fn new() -> Self {
45        Self {}
46    }
47}
48
49impl Display for RiskReturnRatio {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        write!(f, "Risk Return Ratio")
52    }
53}
54
55impl PortfolioStatistic for RiskReturnRatio {
56    type Item = f64;
57
58    fn name(&self) -> String {
59        self.to_string()
60    }
61
62    fn calculate_from_returns(&self, raw_returns: &Returns) -> Option<Self::Item> {
63        if !self.check_valid_returns(raw_returns) {
64            return Some(f64::NAN);
65        }
66
67        let returns = self.downsample_to_daily_bins(raw_returns);
68        let mean = returns.values().sum::<f64>() / returns.len() as f64;
69        let std = self.calculate_std(&returns);
70
71        if std < f64::EPSILON || std.is_nan() {
72            Some(f64::NAN)
73        } else {
74            Some(mean / std)
75        }
76    }
77    fn calculate_from_realized_pnls(&self, _realized_pnls: &[f64]) -> Option<Self::Item> {
78        None
79    }
80
81    fn calculate_from_positions(&self, _positions: &[Position]) -> Option<Self::Item> {
82        None
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use std::collections::BTreeMap;
89
90    use nautilus_core::{UnixNanos, approx_eq};
91    use rstest::rstest;
92
93    use super::*;
94
95    fn create_returns(values: &[f64]) -> Returns {
96        let mut new_return = BTreeMap::new();
97        let one_day_in_nanos = 86_400_000_000_000;
98        let start_time = 1_600_000_000_000_000_000;
99
100        for (i, &value) in values.iter().enumerate() {
101            let timestamp = start_time + i as u64 * one_day_in_nanos;
102            new_return.insert(UnixNanos::from(timestamp), value);
103        }
104
105        new_return
106    }
107
108    #[rstest]
109    fn test_empty_returns() {
110        let ratio = RiskReturnRatio::new();
111        let returns = create_returns(&[]);
112        let result = ratio.calculate_from_returns(&returns);
113        assert!(result.is_some());
114        assert!(result.unwrap().is_nan());
115    }
116
117    #[rstest]
118    fn test_zero_std_dev() {
119        let ratio = RiskReturnRatio::new();
120        let returns = create_returns(&[0.05; 10]);
121        let result = ratio.calculate_from_returns(&returns);
122        assert!(result.is_some());
123        assert!(result.unwrap().is_nan());
124    }
125
126    #[rstest]
127    fn test_valid_risk_return_ratio() {
128        let ratio = RiskReturnRatio::new();
129        let returns = create_returns(&[0.1, -0.05, 0.2, -0.1, 0.15]);
130        let result = ratio.calculate_from_returns(&returns);
131        assert!(result.is_some());
132        assert!(approx_eq!(
133            f64,
134            result.unwrap(),
135            0.46360044557175345,
136            epsilon = 1e-9
137        ));
138    }
139
140    #[rstest]
141    fn test_name() {
142        let ratio = RiskReturnRatio::new();
143        assert_eq!(ratio.name(), "Risk Return Ratio");
144    }
145}