nautilus_analysis/statistics/
winner_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 MaxWinner {}
29
30impl Display for MaxWinner {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        write!(f, "Max Winner")
33    }
34}
35
36impl PortfolioStatistic for MaxWinner {
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        // Match old Python behavior: max(all_pnls) regardless of sign
49        // If all trades are losses, returns the "least bad" loss
50        realized_pnls
51            .iter()
52            .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
53            .copied()
54    }
55
56    fn calculate_from_returns(&self, _returns: &Returns) -> Option<Self::Item> {
57        None
58    }
59
60    fn calculate_from_positions(&self, _positions: &[Position]) -> Option<Self::Item> {
61        None
62    }
63}
64
65////////////////////////////////////////////////////////////////////////////////
66// Tests
67////////////////////////////////////////////////////////////////////////////////
68
69#[cfg(test)]
70mod tests {
71    use nautilus_core::approx_eq;
72    use rstest::rstest;
73
74    use super::*;
75
76    #[rstest]
77    fn test_empty_pnls() {
78        let max_winner = MaxWinner {};
79        let result = max_winner.calculate_from_realized_pnls(&[]);
80        assert!(result.is_some());
81        assert!(approx_eq!(f64, result.unwrap(), 0.0, epsilon = 1e-9));
82    }
83
84    #[rstest]
85    fn test_no_winning_trades() {
86        let max_winner = MaxWinner {};
87        let realized_pnls = vec![-100.0, -50.0, -200.0];
88        let result = max_winner.calculate_from_realized_pnls(&realized_pnls);
89        assert!(result.is_some());
90        // Returns the "least bad" loss (matches old Python behavior)
91        assert!(approx_eq!(f64, result.unwrap(), -50.0, epsilon = 1e-9));
92    }
93
94    #[rstest]
95    fn test_all_winning_trades() {
96        let max_winner = MaxWinner {};
97        let realized_pnls = vec![100.0, 50.0, 200.0];
98        let result = max_winner.calculate_from_realized_pnls(&realized_pnls);
99        assert!(result.is_some());
100        assert!(approx_eq!(f64, result.unwrap(), 200.0, epsilon = 1e-9));
101    }
102
103    #[rstest]
104    fn test_mixed_trades() {
105        let max_winner = MaxWinner {};
106        let realized_pnls = vec![100.0, -50.0, 200.0, -100.0];
107        let result = max_winner.calculate_from_realized_pnls(&realized_pnls);
108        assert!(result.is_some());
109        assert!(approx_eq!(f64, result.unwrap(), 200.0, epsilon = 1e-9));
110    }
111
112    #[rstest]
113    fn test_name() {
114        let max_winner = MaxWinner {};
115        assert_eq!(max_winner.name(), "Max Winner");
116    }
117}