nautilus_analysis/statistics/
calmar_ratio.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 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
16//! Calmar Ratio statistic.
17
18use std::collections::BTreeMap;
19
20use nautilus_core::UnixNanos;
21
22use crate::{
23    statistic::PortfolioStatistic,
24    statistics::{cagr::CAGR, max_drawdown::MaxDrawdown},
25};
26
27/// Calculates the Calmar Ratio for returns.
28///
29/// The Calmar Ratio is a function of the fund's average compounded annual rate
30/// of return versus its maximum drawdown. The higher the Calmar ratio, the better
31/// it performed on a risk-adjusted basis during the given time frame.
32///
33/// Formula: Calmar Ratio = CAGR / |Max Drawdown|
34///
35/// Reference: Young, T. W. (1991). "Calmar Ratio: A Smoother Tool". Futures, 20(1).
36#[repr(C)]
37#[derive(Debug, Clone)]
38#[cfg_attr(
39    feature = "python",
40    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.analysis")
41)]
42pub struct CalmarRatio {
43    /// The number of periods per year for CAGR calculation (e.g., 252 for trading days).
44    pub period: usize,
45}
46
47impl CalmarRatio {
48    /// Creates a new [`CalmarRatio`] instance.
49    #[must_use]
50    pub fn new(period: Option<usize>) -> Self {
51        Self {
52            period: period.unwrap_or(252),
53        }
54    }
55}
56
57impl PortfolioStatistic for CalmarRatio {
58    type Item = f64;
59
60    fn name(&self) -> String {
61        format!("Calmar Ratio ({} days)", self.period)
62    }
63
64    fn calculate_from_returns(&self, returns: &BTreeMap<UnixNanos, f64>) -> Option<Self::Item> {
65        if returns.is_empty() {
66            return Some(f64::NAN);
67        }
68
69        // Calculate CAGR
70        let cagr_stat = CAGR::new(Some(self.period));
71        let cagr = cagr_stat.calculate_from_returns(returns)?;
72
73        // Calculate Max Drawdown
74        let max_dd_stat = MaxDrawdown::new();
75        let max_dd = max_dd_stat.calculate_from_returns(returns)?;
76
77        // Calmar = CAGR / |Max Drawdown|
78        // Max Drawdown is already negative, so we use abs
79        // When no drawdown exists, the ratio is undefined
80        if max_dd.abs() < f64::EPSILON {
81            return Some(f64::NAN);
82        }
83
84        let calmar = cagr / max_dd.abs();
85
86        if calmar.is_finite() {
87            Some(calmar)
88        } else {
89            Some(f64::NAN)
90        }
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use rstest::rstest;
97
98    use super::*;
99
100    fn create_returns(values: Vec<f64>) -> BTreeMap<UnixNanos, f64> {
101        let mut returns = BTreeMap::new();
102        let nanos_per_day = 86_400_000_000_000;
103        let start_time = 1_600_000_000_000_000_000;
104
105        for (i, &value) in values.iter().enumerate() {
106            let timestamp = start_time + i as u64 * nanos_per_day;
107            returns.insert(UnixNanos::from(timestamp), value);
108        }
109
110        returns
111    }
112
113    #[rstest]
114    fn test_name() {
115        let ratio = CalmarRatio::new(Some(252));
116        assert_eq!(ratio.name(), "Calmar Ratio (252 days)");
117    }
118
119    #[rstest]
120    fn test_empty_returns() {
121        let ratio = CalmarRatio::new(Some(252));
122        let returns = BTreeMap::new();
123        let result = ratio.calculate_from_returns(&returns);
124        assert!(result.is_some());
125        assert!(result.unwrap().is_nan());
126    }
127
128    #[rstest]
129    fn test_no_drawdown() {
130        let ratio = CalmarRatio::new(Some(252));
131        // Only positive returns, no drawdown
132        let returns = create_returns(vec![0.01; 252]);
133        let result = ratio.calculate_from_returns(&returns);
134
135        // Should be NaN when no drawdown (undefined ratio)
136        assert!(result.is_some());
137        assert!(result.unwrap().is_nan());
138    }
139
140    #[rstest]
141    fn test_positive_ratio() {
142        let ratio = CalmarRatio::new(Some(252));
143        // Simulate a year with 20% CAGR and 10% max drawdown
144        // Daily return for 20% annual: (1.20)^(1/252) - 1
145        let mut returns_vec = vec![0.001; 200]; // Small positive returns
146        // Add a drawdown period
147        returns_vec.extend(vec![-0.002; 52]); // Small negative returns
148
149        let returns = create_returns(returns_vec);
150        let result = ratio.calculate_from_returns(&returns).unwrap();
151
152        // Calmar should be positive (CAGR / |Max DD|)
153        assert!(result > 0.0);
154    }
155
156    #[rstest]
157    fn test_high_calmar_better() {
158        let ratio = CalmarRatio::new(Some(252));
159
160        // Strategy A: Higher return, same drawdown
161        let returns_a = create_returns(vec![0.002; 252]);
162        let calmar_a = ratio.calculate_from_returns(&returns_a);
163
164        // Strategy B: Lower return
165        let returns_b = create_returns(vec![0.001; 252]);
166        let calmar_b = ratio.calculate_from_returns(&returns_b);
167
168        // Higher CAGR should give higher Calmar (assuming same drawdown pattern)
169        // This test just verifies both calculate successfully
170        assert!(calmar_a.is_some());
171        assert!(calmar_b.is_some());
172    }
173}