nautilus_analysis/statistics/
winner_avg.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 AvgWinner {}
29
30impl Display for AvgWinner {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        write!(f, "Avg Winner")
33    }
34}
35
36impl PortfolioStatistic for AvgWinner {
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 winners: Vec<f64> = realized_pnls
49            .iter()
50            .filter(|&&pnl| pnl > 0.0)
51            .copied()
52            .collect();
53
54        if winners.is_empty() {
55            return Some(f64::NAN);
56        }
57
58        let sum: f64 = winners.iter().sum();
59        Some(sum / winners.len() as f64)
60    }
61
62    fn calculate_from_returns(&self, _returns: &Returns) -> Option<Self::Item> {
63        None
64    }
65
66    fn calculate_from_positions(&self, _positions: &[Position]) -> Option<Self::Item> {
67        None
68    }
69}
70
71#[cfg(test)]
72mod tests {
73    use nautilus_core::approx_eq;
74    use rstest::rstest;
75
76    use super::*;
77
78    #[rstest]
79    fn test_empty_pnls() {
80        let avg_winner = AvgWinner {};
81        let result = avg_winner.calculate_from_realized_pnls(&[]);
82        assert!(result.is_some());
83        assert!(result.unwrap().is_nan());
84    }
85
86    #[rstest]
87    fn test_no_winning_trades() {
88        let avg_winner = AvgWinner {};
89        let realized_pnls = vec![-100.0, -50.0, -200.0];
90        let result = avg_winner.calculate_from_realized_pnls(&realized_pnls);
91        assert!(result.is_some());
92        assert!(result.unwrap().is_nan());
93    }
94
95    #[rstest]
96    fn test_all_winning_trades() {
97        let avg_winner = AvgWinner {};
98        let realized_pnls = vec![100.0, 50.0, 200.0];
99        let result = avg_winner.calculate_from_realized_pnls(&realized_pnls);
100        assert!(result.is_some());
101        assert!(approx_eq!(
102            f64,
103            result.unwrap(),
104            116.66666666666667,
105            epsilon = 1e-9
106        ));
107    }
108
109    #[rstest]
110    fn test_mixed_trades() {
111        let avg_winner = AvgWinner {};
112        let realized_pnls = vec![100.0, -50.0, 200.0, -100.0];
113        let result = avg_winner.calculate_from_realized_pnls(&realized_pnls);
114        assert!(result.is_some());
115        assert!(approx_eq!(f64, result.unwrap(), 150.0, epsilon = 1e-9));
116    }
117
118    #[rstest]
119    fn test_name() {
120        let avg_winner = AvgWinner {};
121        assert_eq!(avg_winner.name(), "Avg Winner");
122    }
123}