nautilus_analysis/statistics/
cagr.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//! Compound Annual Growth Rate (CAGR) statistic.
17
18use std::collections::BTreeMap;
19
20use nautilus_core::UnixNanos;
21
22use crate::statistic::PortfolioStatistic;
23
24/// Calculates the Compound Annual Growth Rate (CAGR) for returns.
25///
26/// CAGR represents the mean annual growth rate of an investment over a specified period,
27/// assuming the profits were reinvested at the end of each period.
28///
29/// Formula: CAGR = (Ending Value / Beginning Value)^(Period/Days) - 1
30///
31/// For returns: CAGR = ((1 + Total Return)^(Period/Days)) - 1
32#[repr(C)]
33#[derive(Debug, Clone)]
34#[cfg_attr(
35    feature = "python",
36    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.analysis")
37)]
38pub struct CAGR {
39    /// The number of periods per year for annualization (e.g., 252 for trading days).
40    pub period: usize,
41}
42
43impl CAGR {
44    /// Creates a new [`CAGR`] instance.
45    #[must_use]
46    pub fn new(period: Option<usize>) -> Self {
47        Self {
48            period: period.unwrap_or(252),
49        }
50    }
51}
52
53impl PortfolioStatistic for CAGR {
54    type Item = f64;
55
56    fn name(&self) -> String {
57        format!("CAGR ({} days)", self.period)
58    }
59
60    fn calculate_from_returns(&self, returns: &BTreeMap<UnixNanos, f64>) -> Option<Self::Item> {
61        if returns.is_empty() {
62            return Some(0.0);
63        }
64
65        // Downsample to daily bins to count actual trading days (not calendar days or trade count)
66        let daily_returns = self.downsample_to_daily_bins(returns);
67
68        // Calculate total return (cumulative)
69        let total_return: f64 = daily_returns.values().map(|&r| 1.0 + r).product::<f64>() - 1.0;
70
71        // Use the number of trading days (bins) for annualization
72        // Minimum of 1 day to handle intraday-only strategies
73        let days = daily_returns.len().max(1) as f64;
74
75        // CAGR = (1 + total_return)^(period/days) - 1
76        let cagr = (1.0 + total_return).powf(self.period as f64 / days) - 1.0;
77
78        if cagr.is_finite() {
79            Some(cagr)
80        } else {
81            Some(0.0)
82        }
83    }
84}
85
86////////////////////////////////////////////////////////////////////////////////
87// Tests
88////////////////////////////////////////////////////////////////////////////////
89
90#[cfg(test)]
91mod tests {
92    use rstest::rstest;
93
94    use super::*;
95
96    fn create_returns(values: Vec<f64>) -> BTreeMap<UnixNanos, f64> {
97        let mut returns = BTreeMap::new();
98        let nanos_per_day = 86_400_000_000_000;
99        let start_time = 1_600_000_000_000_000_000;
100
101        for (i, &value) in values.iter().enumerate() {
102            let timestamp = start_time + i as u64 * nanos_per_day;
103            returns.insert(UnixNanos::from(timestamp), value);
104        }
105
106        returns
107    }
108
109    #[rstest]
110    fn test_name() {
111        let cagr = CAGR::new(Some(252));
112        assert_eq!(cagr.name(), "CAGR (252 days)");
113    }
114
115    #[rstest]
116    fn test_empty_returns() {
117        let cagr = CAGR::new(Some(252));
118        let returns = BTreeMap::new();
119        let result = cagr.calculate_from_returns(&returns);
120        assert_eq!(result, Some(0.0));
121    }
122
123    #[rstest]
124    fn test_positive_cagr() {
125        let cagr = CAGR::new(Some(252));
126        // Simulate 252 days with 0.1% daily return
127        // Total return = (1.001)^252 - 1 ≈ 0.288 (28.8%)
128        // CAGR should be approximately same as total return for full year
129        let returns = create_returns(vec![0.001; 252]);
130        let result = cagr.calculate_from_returns(&returns).unwrap();
131
132        // For 252 days of 0.1% daily return
133        // CAGR = (1 + 0.288)^(252/252) - 1 = 0.288
134        assert!((result - 0.288).abs() < 0.01);
135    }
136
137    #[rstest]
138    fn test_cagr_half_year() {
139        let cagr = CAGR::new(Some(252));
140        // Simulate 126 days (half year) with total return of 10%
141        let daily_return = (1.10_f64.powf(1.0 / 126.0)) - 1.0;
142        let returns = create_returns(vec![daily_return; 126]);
143        let result = cagr.calculate_from_returns(&returns).unwrap();
144
145        // CAGR should annualize the 10% half-year return
146        // CAGR = (1.10)^(252/126) - 1 = (1.10)^2 - 1 ≈ 0.21 (21%)
147        assert!((result - 0.21).abs() < 0.01);
148    }
149
150    #[rstest]
151    fn test_negative_returns() {
152        let cagr = CAGR::new(Some(252));
153        // Simulate losses
154        let returns = create_returns(vec![-0.001; 252]);
155        let result = cagr.calculate_from_returns(&returns).unwrap();
156
157        // Should be negative
158        assert!(result < 0.0);
159    }
160
161    #[rstest]
162    fn test_multiple_trades_per_day() {
163        let cagr = CAGR::new(Some(252));
164
165        // Simulate 500 trades over 252 days
166        let mut returns = BTreeMap::new();
167        let nanos_per_day = 86_400_000_000_000;
168        let start_time = 1_600_000_000_000_000_000;
169
170        // Create 500 trades with small returns spread across 252 days (~2 trades per day)
171        for i in 0..500 {
172            let day = (i * 252) / 500; // Map trade index to day
173            let timestamp =
174                start_time + day as u64 * nanos_per_day + (i % 3) as u64 * 1_000_000_000;
175            returns.insert(UnixNanos::from(timestamp), 0.0005);
176        }
177
178        let result = cagr.calculate_from_returns(&returns).unwrap();
179
180        // With downsample_to_daily_bins, we get 252 bins (trading days)
181        // Daily returns are aggregated, then we compound and annualize
182        // The CAGR should reflect 252 trading days, NOT 500 trades
183        assert!((result - 0.285).abs() < 0.02);
184        assert!(result > 0.2); // Should be much higher than what trade-count formula would give
185    }
186
187    #[rstest]
188    fn test_intraday_trading() {
189        let cagr = CAGR::new(Some(252));
190
191        // Simulate multiple trades within a single day
192        let mut returns = BTreeMap::new();
193        let start_time = 1_600_000_000_000_000_000;
194
195        // 10 trades within the same day, each with 1% return
196        for i in 0..10 {
197            let timestamp = start_time + i as u64 * 3_600_000_000_000; // 1 hour apart
198            returns.insert(UnixNanos::from(timestamp), 0.01);
199        }
200
201        let result = cagr.calculate_from_returns(&returns).unwrap();
202
203        // Total return: (1.01)^10 - 1 ≈ 0.1046 (10.46%)
204        // This should be treated as 1 trading day
205        // Annualized: (1.1046)^(252/1) - 1 = very large number
206        // The key is it should NOT return 0.0
207        assert!(result > 0.0);
208        assert!(result.is_finite());
209    }
210}