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::{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 AvgWinner {}
29
30impl Display for AvgWinner {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> 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(0.0);
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(0.0);
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////////////////////////////////////////////////////////////////////////////////
72// Tests
73////////////////////////////////////////////////////////////////////////////////
74
75#[cfg(test)]
76mod tests {
77    use nautilus_core::approx_eq;
78    use rstest::rstest;
79
80    use super::*;
81
82    #[rstest]
83    fn test_empty_pnls() {
84        let avg_winner = AvgWinner {};
85        let result = avg_winner.calculate_from_realized_pnls(&[]);
86        assert!(result.is_some());
87        assert!(approx_eq!(f64, result.unwrap(), 0.0, epsilon = 1e-9));
88    }
89
90    #[rstest]
91    fn test_no_winning_trades() {
92        let avg_winner = AvgWinner {};
93        let realized_pnls = vec![-100.0, -50.0, -200.0];
94        let result = avg_winner.calculate_from_realized_pnls(&realized_pnls);
95        assert!(result.is_some());
96        assert!(approx_eq!(f64, result.unwrap(), 0.0, epsilon = 1e-9));
97    }
98
99    #[rstest]
100    fn test_all_winning_trades() {
101        let avg_winner = AvgWinner {};
102        let realized_pnls = vec![100.0, 50.0, 200.0];
103        let result = avg_winner.calculate_from_realized_pnls(&realized_pnls);
104        assert!(result.is_some());
105        assert!(approx_eq!(
106            f64,
107            result.unwrap(),
108            116.66666666666667,
109            epsilon = 1e-9
110        ));
111    }
112
113    #[rstest]
114    fn test_mixed_trades() {
115        let avg_winner = AvgWinner {};
116        let realized_pnls = vec![100.0, -50.0, 200.0, -100.0];
117        let result = avg_winner.calculate_from_realized_pnls(&realized_pnls);
118        assert!(result.is_some());
119        assert!(approx_eq!(f64, result.unwrap(), 150.0, epsilon = 1e-9));
120    }
121
122    #[rstest]
123    fn test_name() {
124        let avg_winner = AvgWinner {};
125        assert_eq!(avg_winner.name(), "Avg Winner");
126    }
127}