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(0.0);
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        if max_dd.abs() < f64::EPSILON {
80            return Some(0.0);
81        }
82
83        let calmar = cagr / max_dd.abs();
84
85        if calmar.is_finite() {
86            Some(calmar)
87        } else {
88            Some(0.0)
89        }
90    }
91}
92
93////////////////////////////////////////////////////////////////////////////////
94// Tests
95////////////////////////////////////////////////////////////////////////////////
96
97#[cfg(test)]
98mod tests {
99    use rstest::rstest;
100
101    use super::*;
102
103    fn create_returns(values: Vec<f64>) -> BTreeMap<UnixNanos, f64> {
104        let mut returns = BTreeMap::new();
105        let nanos_per_day = 86_400_000_000_000;
106        let start_time = 1_600_000_000_000_000_000;
107
108        for (i, &value) in values.iter().enumerate() {
109            let timestamp = start_time + i as u64 * nanos_per_day;
110            returns.insert(UnixNanos::from(timestamp), value);
111        }
112
113        returns
114    }
115
116    #[rstest]
117    fn test_name() {
118        let ratio = CalmarRatio::new(Some(252));
119        assert_eq!(ratio.name(), "Calmar Ratio (252 days)");
120    }
121
122    #[rstest]
123    fn test_empty_returns() {
124        let ratio = CalmarRatio::new(Some(252));
125        let returns = BTreeMap::new();
126        let result = ratio.calculate_from_returns(&returns);
127        assert_eq!(result, Some(0.0));
128    }
129
130    #[rstest]
131    fn test_no_drawdown() {
132        let ratio = CalmarRatio::new(Some(252));
133        // Only positive returns, no drawdown
134        let returns = create_returns(vec![0.01; 252]);
135        let result = ratio.calculate_from_returns(&returns);
136
137        // Should be 0.0 when no drawdown (division by zero case)
138        assert_eq!(result, Some(0.0));
139    }
140
141    #[rstest]
142    fn test_positive_ratio() {
143        let ratio = CalmarRatio::new(Some(252));
144        // Simulate a year with 20% CAGR and 10% max drawdown
145        // Daily return for 20% annual: (1.20)^(1/252) - 1
146        let mut returns_vec = vec![0.001; 200]; // Small positive returns
147        // Add a drawdown period
148        returns_vec.extend(vec![-0.002; 52]); // Small negative returns
149
150        let returns = create_returns(returns_vec);
151        let result = ratio.calculate_from_returns(&returns).unwrap();
152
153        // Calmar should be positive (CAGR / |Max DD|)
154        assert!(result > 0.0);
155    }
156
157    #[rstest]
158    fn test_high_calmar_better() {
159        let ratio = CalmarRatio::new(Some(252));
160
161        // Strategy A: Higher return, same drawdown
162        let returns_a = create_returns(vec![0.002; 252]);
163        let calmar_a = ratio.calculate_from_returns(&returns_a);
164
165        // Strategy B: Lower return
166        let returns_b = create_returns(vec![0.001; 252]);
167        let calmar_b = ratio.calculate_from_returns(&returns_b);
168
169        // Higher CAGR should give higher Calmar (assuming same drawdown pattern)
170        // This test just verifies both calculate successfully
171        assert!(calmar_a.is_some());
172        assert!(calmar_b.is_some());
173    }
174}