nautilus_analysis/statistics/
win_rate.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 crate::statistic::PortfolioStatistic;
17
18/// Calculates the win rate of a trading strategy based on realized PnLs.
19///
20/// Win rate is the percentage of profitable trades out of total trades:
21/// Number of Winning Trades / Total Number of Trades
22///
23/// Returns a value between 0.0 and 1.0, where 1.0 represents 100% winning trades.
24#[repr(C)]
25#[derive(Debug)]
26#[cfg_attr(
27    feature = "python",
28    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.analysis")
29)]
30pub struct WinRate {}
31
32impl PortfolioStatistic for WinRate {
33    type Item = f64;
34
35    fn name(&self) -> String {
36        stringify!(WinRate).to_string()
37    }
38
39    fn calculate_from_realized_pnls(&self, realized_pnls: &[f64]) -> Option<Self::Item> {
40        if realized_pnls.is_empty() {
41            return Some(0.0);
42        }
43
44        let (winners, losers): (Vec<f64>, Vec<f64>) =
45            realized_pnls.iter().partition(|&&pnl| pnl > 0.0);
46
47        let total_trades = winners.len() + losers.len();
48        Some(winners.len() as f64 / total_trades.max(1) as f64)
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use nautilus_core::approx_eq;
55    use rstest::rstest;
56
57    use super::*;
58
59    #[rstest]
60    fn test_empty_pnls() {
61        let win_rate = WinRate {};
62        let result = win_rate.calculate_from_realized_pnls(&[]);
63        assert!(result.is_some());
64        assert!(approx_eq!(f64, result.unwrap(), 0.0, epsilon = 1e-9));
65    }
66
67    #[rstest]
68    fn test_all_winning_trades() {
69        let win_rate = WinRate {};
70        let realized_pnls = vec![100.0, 50.0, 200.0];
71        let result = win_rate.calculate_from_realized_pnls(&realized_pnls);
72        assert!(result.is_some());
73        assert!(approx_eq!(f64, result.unwrap(), 1.0, epsilon = 1e-9));
74    }
75
76    #[rstest]
77    fn test_all_losing_trades() {
78        let win_rate = WinRate {};
79        let realized_pnls = vec![-100.0, -50.0, -200.0];
80        let result = win_rate.calculate_from_realized_pnls(&realized_pnls);
81        assert!(result.is_some());
82        assert!(approx_eq!(f64, result.unwrap(), 0.0, epsilon = 1e-9));
83    }
84
85    #[rstest]
86    fn test_mixed_trades() {
87        let win_rate = WinRate {};
88        let realized_pnls = vec![100.0, -50.0, 200.0, -100.0];
89        let result = win_rate.calculate_from_realized_pnls(&realized_pnls);
90        assert!(result.is_some());
91        assert!(approx_eq!(f64, result.unwrap(), 0.5, epsilon = 1e-9));
92    }
93
94    #[rstest]
95    fn test_name() {
96        let win_rate = WinRate {};
97        assert_eq!(win_rate.name(), "WinRate");
98    }
99}