Skip to main content

nautilus_analysis/statistics/
loser_max.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
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", from_py_object)
27)]
28#[cfg_attr(
29    feature = "python",
30    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.analysis")
31)]
32pub struct MaxLoser {}
33
34impl Display for MaxLoser {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        write!(f, "Max Loser")
37    }
38}
39
40impl PortfolioStatistic for MaxLoser {
41    type Item = f64;
42
43    fn name(&self) -> String {
44        self.to_string()
45    }
46
47    fn calculate_from_realized_pnls(&self, realized_pnls: &[f64]) -> Option<Self::Item> {
48        if realized_pnls.is_empty() {
49            return Some(f64::NAN);
50        }
51
52        let losers: Vec<f64> = realized_pnls
53            .iter()
54            .filter(|&&pnl| pnl < 0.0)
55            .copied()
56            .collect();
57
58        if losers.is_empty() {
59            return Some(f64::NAN);
60        }
61
62        losers
63            .iter()
64            .min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
65            .copied()
66    }
67
68    fn calculate_from_returns(&self, _returns: &Returns) -> Option<Self::Item> {
69        None
70    }
71
72    fn calculate_from_positions(&self, _positions: &[Position]) -> Option<Self::Item> {
73        None
74    }
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!(result.unwrap().is_nan());
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        assert!(result.unwrap().is_nan());
99    }
100
101    #[rstest]
102    fn test_all_negative() {
103        let max_loser = MaxLoser {};
104        let pnls = vec![-10.0, -20.0, -30.0];
105        let result = max_loser.calculate_from_realized_pnls(&pnls);
106        assert!(result.is_some());
107        assert!(approx_eq!(f64, result.unwrap(), -30.0, epsilon = 1e-9));
108    }
109
110    #[rstest]
111    fn test_mixed_pnls() {
112        let max_loser = MaxLoser {};
113        let pnls = vec![10.0, -20.0, 30.0, -40.0];
114        let result = max_loser.calculate_from_realized_pnls(&pnls);
115        assert!(result.is_some());
116        assert!(approx_eq!(f64, result.unwrap(), -40.0, epsilon = 1e-9));
117    }
118
119    #[rstest]
120    fn test_with_zero() {
121        let max_loser = MaxLoser {};
122        let pnls = vec![10.0, 0.0, -20.0, -30.0];
123        let result = max_loser.calculate_from_realized_pnls(&pnls);
124        assert!(result.is_some());
125        assert!(approx_eq!(f64, result.unwrap(), -30.0, epsilon = 1e-9));
126    }
127
128    #[rstest]
129    fn test_single_value() {
130        let max_loser = MaxLoser {};
131        let pnls = vec![-10.0];
132        let result = max_loser.calculate_from_realized_pnls(&pnls);
133        assert!(result.is_some());
134        assert!(approx_eq!(f64, result.unwrap(), -10.0, epsilon = 1e-9));
135    }
136
137    #[rstest]
138    fn test_name() {
139        let max_loser = MaxLoser {};
140        assert_eq!(max_loser.name(), "Max Loser");
141    }
142}