Skip to main content

nautilus_analysis/statistics/
down_capture_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
16//! Down capture ratio statistic (benchmark-relative).
17
18use std::fmt::Display;
19
20use nautilus_model::position::Position;
21
22use crate::{
23    Returns,
24    statistic::PortfolioStatistic,
25    statistics::up_capture_ratio::{MarketSide, capture_ratio},
26};
27
28/// Calculates the down capture ratio of portfolio returns relative to a benchmark.
29///
30/// The down capture ratio measures how the portfolio performed, on average, during the
31/// periods when the benchmark return was negative. It is the ratio of the portfolio's
32/// geometric annualized return to the benchmark's geometric annualized return, both
33/// computed over the down-market subset only:
34///
35/// `DownCapture = annualized_return(portfolio | benchmark < 0) / annualized_return(benchmark | benchmark < 0)`
36///
37/// where each side's annualized return is the geometric (CAGR-style) value
38/// `(prod(1 + x_i))^(period / m) - 1` and `m` is the number of down-market periods (the
39/// size of the filtered subset, not the full aligned length). The period defaults to
40/// 252 trading days. A value below 1.0 means the portfolio lost less than the benchmark
41/// in down markets (smaller drawdowns), which is desirable.
42///
43/// This is the `empyrical.down_capture` convention (geometric annualized-return ratio
44/// over the `benchmark < 0` subset). Note that this differs from the Morningstar
45/// definition, which uses a ratio of *cumulative* (non-annualized) returns; the two
46/// coincide only when both subsets contain the same number of periods.
47///
48/// # References
49///
50/// - empyrical `down_capture` / `capture` / `annual_return`
51///   (<https://github.com/quantopian/empyrical>).
52/// - CFA Institute Investment Foundations, 3rd Edition
53#[repr(C)]
54#[derive(Debug, Clone)]
55#[cfg_attr(
56    feature = "python",
57    pyo3::pyclass(module = "nautilus_trader.analysis", from_py_object)
58)]
59#[cfg_attr(
60    feature = "python",
61    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.analysis")
62)]
63pub struct DownCaptureRatio {
64    /// The annualization period (default: 252 for daily data).
65    period: usize,
66}
67
68impl DownCaptureRatio {
69    /// Creates a new [`DownCaptureRatio`] instance.
70    #[must_use]
71    pub fn new(period: Option<usize>) -> Self {
72        Self {
73            period: period.unwrap_or(252),
74        }
75    }
76}
77
78impl Display for DownCaptureRatio {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        write!(f, "Down Capture Ratio ({} days)", self.period)
81    }
82}
83
84impl PortfolioStatistic for DownCaptureRatio {
85    type Item = f64;
86
87    fn name(&self) -> String {
88        self.to_string()
89    }
90
91    fn calculate_from_returns(&self, _returns: &Returns) -> Option<Self::Item> {
92        None
93    }
94
95    fn calculate_from_realized_pnls(&self, _realized_pnls: &[f64]) -> Option<Self::Item> {
96        None
97    }
98
99    fn calculate_from_positions(&self, _positions: &[Position]) -> Option<Self::Item> {
100        None
101    }
102
103    fn calculate_from_returns_with_benchmark(
104        &self,
105        returns: &Returns,
106        benchmark: &Returns,
107    ) -> Option<Self::Item> {
108        let (r, b) = self.align_returns(returns, benchmark);
109        if r.len() < 2 {
110            return Some(f64::NAN);
111        }
112
113        Some(capture_ratio(&r, &b, self.period, MarketSide::Down))
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use std::collections::BTreeMap;
120
121    use nautilus_core::{UnixNanos, approx_eq};
122    use rstest::rstest;
123
124    use super::*;
125
126    fn create_returns(values: &[f64]) -> BTreeMap<UnixNanos, f64> {
127        let mut new_return = BTreeMap::new();
128        let one_day_in_nanos = 86_400_000_000_000;
129        let start_time = 1_600_000_000_000_000_000;
130
131        for (i, &value) in values.iter().enumerate() {
132            let timestamp = start_time + i as u64 * one_day_in_nanos;
133            new_return.insert(UnixNanos::from(timestamp), value);
134        }
135
136        new_return
137    }
138
139    #[rstest]
140    fn test_name() {
141        let stat = DownCaptureRatio::new(None);
142        assert_eq!(stat.name(), "Down Capture Ratio (252 days)");
143    }
144
145    #[rstest]
146    fn test_name_non_default_period() {
147        let stat = DownCaptureRatio::new(Some(63));
148        assert_eq!(stat.name(), "Down Capture Ratio (63 days)");
149    }
150
151    #[rstest]
152    fn test_known_value_small_period() {
153        // Small period = 4 keeps the geometric annualization hand-checkable.
154        //   b = [0.01, -0.02, 0.015, -0.005], r = [0.02, -0.04, 0.030, -0.010]
155        // down subset (b < 0) is days 1,3: b_dn = [-0.02, -0.005],
156        // r_dn = [-0.04, -0.010], m = 2, period = 4.
157        //   annual_r = (0.96*0.99)^(4/2) - 1 = (0.9504)^2 - 1 = -0.09673984
158        //   annual_b = (0.98*0.995)^(4/2) - 1 = (0.9751)^2 - 1 = -0.04917999
159        //   down_capture = annual_r / annual_b = 1.967056927014422
160        // Cross-validated against empyrical 0.5.5 down_capture (ann_factor=4).
161        let benchmark = create_returns(&[0.01, -0.02, 0.015, -0.005]);
162        let returns = create_returns(&[0.02, -0.04, 0.030, -0.010]);
163        let stat = DownCaptureRatio::new(Some(4));
164        let result = stat
165            .calculate_from_returns_with_benchmark(&returns, &benchmark)
166            .unwrap();
167        assert!(approx_eq!(
168            f64,
169            result,
170            1.967_056_927_014_422,
171            epsilon = 1e-9
172        ));
173    }
174
175    #[rstest]
176    fn test_known_value_default_period() {
177        // Default period = 252; same down subset as above but exercises the 252 path.
178        //   r_dn = [-0.04, -0.010], b_dn = [-0.02, -0.005], m = 2, period = 252.
179        //   annual_r = (0.96*0.99)^(252/2) - 1
180        //   annual_b = (0.98*0.995)^(252/2) - 1
181        //   down_capture = annual_r / annual_b = 1.0418038205588374
182        // Cross-validated against empyrical 0.5.5 down_capture (period='daily').
183        let benchmark = create_returns(&[0.01, -0.02, 0.015, -0.005]);
184        let returns = create_returns(&[0.02, -0.04, 0.030, -0.010]);
185        let stat = DownCaptureRatio::new(None);
186        let result = stat
187            .calculate_from_returns_with_benchmark(&returns, &benchmark)
188            .unwrap();
189        assert!(approx_eq!(
190            f64,
191            result,
192            1.041_803_820_558_837_4,
193            epsilon = 1e-9
194        ));
195    }
196
197    #[rstest]
198    fn test_no_down_periods_is_nan() {
199        // Benchmark never negative -> down subset empty -> NaN.
200        let benchmark = create_returns(&[0.01, 0.02, 0.015, 0.005]);
201        let returns = create_returns(&[0.02, -0.04, 0.030, -0.010]);
202        let stat = DownCaptureRatio::new(None);
203        let result = stat
204            .calculate_from_returns_with_benchmark(&returns, &benchmark)
205            .unwrap();
206        assert!(result.is_nan());
207    }
208
209    #[rstest]
210    fn test_partial_overlap_inner_join() {
211        // Strategy on days 0..5, benchmark on days 2..7 -> overlap on days 2,3,4 only.
212        let one_day = 86_400_000_000_000_u64;
213        let start = 1_600_000_000_000_000_000_u64;
214
215        let mut returns = BTreeMap::new();
216        for (i, v) in [0.02, -0.04, 0.030, -0.010, 0.050].iter().enumerate() {
217            returns.insert(UnixNanos::from(start + i as u64 * one_day), *v);
218        }
219        let mut benchmark = BTreeMap::new();
220        for (i, v) in [0.015, -0.005, 0.025, -0.02, 0.01].iter().enumerate() {
221            benchmark.insert(UnixNanos::from(start + (i as u64 + 2) * one_day), *v);
222        }
223
224        // Overlap days 2,3,4: r = [0.030, -0.010, 0.050], b = [0.015, -0.005, 0.025].
225        // down subset (b < 0) is day 3 only: r_dn = [-0.010], b_dn = [-0.005],
226        // m = 1, period = 252.
227        //   annual_r = (0.99)^(252/1) - 1 = -0.9205545483094462
228        //   annual_b = (0.995)^(252/1) - 1 = -0.7172410580445943
229        //   down_capture = annual_r / annual_b = 1.2834660508966722
230        // Cross-validated against empyrical 0.5.5 down_capture on the subset (period='daily').
231        let stat = DownCaptureRatio::new(Some(252));
232        let result = stat
233            .calculate_from_returns_with_benchmark(&returns, &benchmark)
234            .unwrap();
235        assert!(approx_eq!(
236            f64,
237            result,
238            1.283_466_050_896_672_2,
239            epsilon = 1e-9
240        ));
241    }
242
243    #[rstest]
244    fn test_empty_returns_is_nan() {
245        let stat = DownCaptureRatio::new(None);
246        let result = stat
247            .calculate_from_returns_with_benchmark(&create_returns(&[]), &create_returns(&[]))
248            .unwrap();
249        assert!(result.is_nan());
250    }
251
252    #[rstest]
253    fn test_single_overlap_is_nan() {
254        let benchmark = create_returns(&[0.01, -0.02, 0.015]);
255        let returns = create_returns(&[0.02]);
256        let stat = DownCaptureRatio::new(None);
257        let result = stat
258            .calculate_from_returns_with_benchmark(&returns, &benchmark)
259            .unwrap();
260        assert!(result.is_nan());
261    }
262}