nautilus_analysis/statistics/
loser_max.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
16use std::fmt::{self, Display};
17
18use nautilus_model::position::Position;
19
20use crate::{Returns, statistic::PortfolioStatistic};
21
22#[repr(C)]
23#[derive(Debug, Clone)]
24#[cfg_attr(
25    feature = "python",
26    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.analysis")
27)]
28pub struct MaxLoser {}
29
30impl Display for MaxLoser {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        write!(f, "Max Loser")
33    }
34}
35
36impl PortfolioStatistic for MaxLoser {
37    type Item = f64;
38
39    fn name(&self) -> String {
40        self.to_string()
41    }
42
43    fn calculate_from_realized_pnls(&self, realized_pnls: &[f64]) -> Option<Self::Item> {
44        if realized_pnls.is_empty() {
45            return Some(0.0);
46        }
47
48        let losers: Vec<f64> = realized_pnls
49            .iter()
50            .filter(|&&pnl| pnl < 0.0)
51            .copied()
52            .collect();
53
54        if losers.is_empty() {
55            return Some(0.0); // Match old Python behavior
56        }
57
58        losers
59            .iter()
60            .min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
61            .copied()
62    }
63
64    fn calculate_from_returns(&self, _returns: &Returns) -> Option<Self::Item> {
65        None
66    }
67
68    fn calculate_from_positions(&self, _positions: &[Position]) -> Option<Self::Item> {
69        None
70    }
71}
72
73////////////////////////////////////////////////////////////////////////////////
74// Tests
75////////////////////////////////////////////////////////////////////////////////
76
77#[cfg(test)]
78mod tests {
79    use nautilus_core::approx_eq;
80    use rstest::rstest;
81
82    use super::*;
83
84    #[rstest]
85    fn test_empty_pnls() {
86        let max_loser = MaxLoser {};
87        let result = max_loser.calculate_from_realized_pnls(&[]);
88        assert!(result.is_some());
89        assert!(approx_eq!(f64, result.unwrap(), 0.0, epsilon = 1e-9));
90    }
91
92    #[rstest]
93    fn test_all_positive() {
94        let max_loser = MaxLoser {};
95        let pnls = vec![10.0, 20.0, 30.0];
96        let result = max_loser.calculate_from_realized_pnls(&pnls);
97        assert!(result.is_some());
98        // Returns 0.0 when no losers (matches old Python behavior)
99        assert!(approx_eq!(f64, result.unwrap(), 0.0, epsilon = 1e-9));
100    }
101
102    #[rstest]
103    fn test_all_negative() {
104        let max_loser = MaxLoser {};
105        let pnls = vec![-10.0, -20.0, -30.0];
106        let result = max_loser.calculate_from_realized_pnls(&pnls);
107        assert!(result.is_some());
108        assert!(approx_eq!(f64, result.unwrap(), -30.0, epsilon = 1e-9));
109    }
110
111    #[rstest]
112    fn test_mixed_pnls() {
113        let max_loser = MaxLoser {};
114        let pnls = vec![10.0, -20.0, 30.0, -40.0];
115        let result = max_loser.calculate_from_realized_pnls(&pnls);
116        assert!(result.is_some());
117        assert!(approx_eq!(f64, result.unwrap(), -40.0, epsilon = 1e-9));
118    }
119
120    #[rstest]
121    fn test_with_zero() {
122        let max_loser = MaxLoser {};
123        let pnls = vec![10.0, 0.0, -20.0, -30.0];
124        let result = max_loser.calculate_from_realized_pnls(&pnls);
125        assert!(result.is_some());
126        assert!(approx_eq!(f64, result.unwrap(), -30.0, epsilon = 1e-9));
127    }
128
129    #[rstest]
130    fn test_single_value() {
131        let max_loser = MaxLoser {};
132        let pnls = vec![-10.0];
133        let result = max_loser.calculate_from_realized_pnls(&pnls);
134        assert!(result.is_some());
135        assert!(approx_eq!(f64, result.unwrap(), -10.0, epsilon = 1e-9));
136    }
137
138    #[rstest]
139    fn test_name() {
140        let max_loser = MaxLoser {};
141        assert_eq!(max_loser.name(), "Max Loser");
142    }
143}