nautilus_analysis/statistics/
loser_min.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::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 MinLoser {}
29
30impl Display for MinLoser {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        write!(f, "Min Loser")
33    }
34}
35
36impl PortfolioStatistic for MinLoser {
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(f64::NAN);
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(f64::NAN);
56        }
57
58        losers
59            .iter()
60            .max_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#[cfg(test)]
74mod tests {
75    use nautilus_core::approx_eq;
76    use rstest::rstest;
77
78    use super::*;
79
80    #[rstest]
81    fn test_empty_pnls() {
82        let min_loser = MinLoser {};
83        let result = min_loser.calculate_from_realized_pnls(&[]);
84        assert!(result.is_some());
85        assert!(result.unwrap().is_nan());
86    }
87
88    #[rstest]
89    fn test_all_positive() {
90        let min_loser = MinLoser {};
91        let pnls = vec![10.0, 20.0, 30.0];
92        let result = min_loser.calculate_from_realized_pnls(&pnls);
93        assert!(result.is_some());
94        assert!(result.unwrap().is_nan());
95    }
96
97    #[rstest]
98    fn test_all_negative() {
99        let min_loser = MinLoser {};
100        let pnls = vec![-10.0, -20.0, -30.0];
101        let result = min_loser.calculate_from_realized_pnls(&pnls);
102        assert!(result.is_some());
103        assert!(approx_eq!(f64, result.unwrap(), -10.0, epsilon = 1e-9));
104    }
105
106    #[rstest]
107    fn test_mixed_pnls() {
108        let min_loser = MinLoser {};
109        let pnls = vec![10.0, -20.0, 30.0, -40.0];
110        let result = min_loser.calculate_from_realized_pnls(&pnls);
111        assert!(result.is_some());
112        assert!(approx_eq!(f64, result.unwrap(), -20.0, epsilon = 1e-9));
113    }
114
115    #[rstest]
116    fn test_with_zero() {
117        let min_loser = MinLoser {};
118        let pnls = vec![10.0, 0.0, -20.0, -30.0];
119        let result = min_loser.calculate_from_realized_pnls(&pnls);
120        assert!(result.is_some());
121        // Zero is excluded, so min loser is -20.0 (least negative loss)
122        assert!(approx_eq!(f64, result.unwrap(), -20.0, epsilon = 1e-9));
123    }
124
125    #[rstest]
126    fn test_single_negative() {
127        let min_loser = MinLoser {};
128        let pnls = vec![-10.0];
129        let result = min_loser.calculate_from_realized_pnls(&pnls);
130        assert!(result.is_some());
131        assert!(approx_eq!(f64, result.unwrap(), -10.0, epsilon = 1e-9));
132    }
133
134    #[rstest]
135    fn test_name() {
136        let min_loser = MinLoser {};
137        assert_eq!(min_loser.name(), "Min Loser");
138    }
139}