nautilus_analysis/statistics/
win_rate.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.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 = "posei_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 rstest::rstest;
55
56    use super::*;
57
58    #[rstest]
59    fn test_empty_pnls() {
60        let win_rate = WinRate {};
61        let result = win_rate.calculate_from_realized_pnls(&[]);
62        assert!(result.is_some());
63        assert_eq!(result.unwrap(), 0.0);
64    }
65
66    #[rstest]
67    fn test_all_winning_trades() {
68        let win_rate = WinRate {};
69        let realized_pnls = vec![100.0, 50.0, 200.0];
70        let result = win_rate.calculate_from_realized_pnls(&realized_pnls);
71        assert!(result.is_some());
72        assert_eq!(result.unwrap(), 1.0);
73    }
74
75    #[rstest]
76    fn test_all_losing_trades() {
77        let win_rate = WinRate {};
78        let realized_pnls = vec![-100.0, -50.0, -200.0];
79        let result = win_rate.calculate_from_realized_pnls(&realized_pnls);
80        assert!(result.is_some());
81        assert_eq!(result.unwrap(), 0.0);
82    }
83
84    #[rstest]
85    fn test_mixed_trades() {
86        let win_rate = WinRate {};
87        let realized_pnls = vec![100.0, -50.0, 200.0, -100.0];
88        let result = win_rate.calculate_from_realized_pnls(&realized_pnls);
89        assert!(result.is_some());
90        assert_eq!(result.unwrap(), 0.5);
91    }
92
93    #[rstest]
94    fn test_name() {
95        let win_rate = WinRate {};
96        assert_eq!(win_rate.name(), "WinRate");
97    }
98}