nautilus_analysis/statistics/
profit_factor.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/// Calculates the profit factor based on portfolio returns.
23///
24/// Profit factor is defined as the ratio of gross profits to gross losses:
25/// `Sum(Positive Returns) / Abs(Sum(Negative Returns))`
26///
27/// A profit factor greater than 1.0 indicates a profitable strategy, while
28/// a factor less than 1.0 indicates losses exceed gains.
29///
30/// Generally:
31/// - 1.0-1.5: Modest profitability
32/// - 1.5-2.0: Good profitability
33/// - > 2.0: Excellent profitability
34///
35/// # References
36///
37/// - Tharp, V. K. (1998). *Trade Your Way to Financial Freedom*. McGraw-Hill.
38/// - Kaufman, P. J. (2013). *Trading Systems and Methods* (5th ed.). Wiley.
39#[repr(C)]
40#[derive(Debug, Clone)]
41#[cfg_attr(
42    feature = "python",
43    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.analysis")
44)]
45pub struct ProfitFactor {}
46
47impl Display for ProfitFactor {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        write!(f, "Profit Factor")
50    }
51}
52
53impl PortfolioStatistic for ProfitFactor {
54    type Item = f64;
55
56    fn name(&self) -> String {
57        self.to_string()
58    }
59
60    fn calculate_from_returns(&self, returns: &Returns) -> Option<Self::Item> {
61        if !self.check_valid_returns(returns) {
62            return Some(f64::NAN);
63        }
64
65        // Zero returns are excluded from both sums (neither profit nor loss)
66        let (positive_returns_sum, negative_returns_sum) =
67            returns
68                .values()
69                .fold((0.0, 0.0), |(pos_sum, neg_sum), &pnl| {
70                    if pnl > 0.0 {
71                        (pos_sum + pnl, neg_sum)
72                    } else if pnl < 0.0 {
73                        (pos_sum, neg_sum + pnl)
74                    } else {
75                        (pos_sum, neg_sum)
76                    }
77                });
78
79        if negative_returns_sum == 0.0 {
80            return Some(f64::NAN);
81        }
82        Some((positive_returns_sum / negative_returns_sum).abs())
83    }
84    fn calculate_from_realized_pnls(&self, _realized_pnls: &[f64]) -> Option<Self::Item> {
85        None
86    }
87
88    fn calculate_from_positions(&self, _positions: &[Position]) -> Option<Self::Item> {
89        None
90    }
91}
92
93#[cfg(test)]
94mod profit_factor_tests {
95    use std::collections::BTreeMap;
96
97    use nautilus_core::{UnixNanos, approx_eq};
98    use rstest::rstest;
99
100    use super::*;
101
102    fn create_returns(values: Vec<f64>) -> Returns {
103        let mut new_return = BTreeMap::new();
104        for (i, value) in values.iter().enumerate() {
105            new_return.insert(UnixNanos::from(i as u64), *value);
106        }
107
108        new_return
109    }
110
111    #[rstest]
112    fn test_empty_returns() {
113        let profit_factor = ProfitFactor {};
114        let returns = create_returns(vec![]);
115        let result = profit_factor.calculate_from_returns(&returns);
116        assert!(result.is_some());
117        assert!(result.unwrap().is_nan());
118    }
119
120    #[rstest]
121    fn test_all_positive() {
122        let profit_factor = ProfitFactor {};
123        let returns = create_returns(vec![10.0, 20.0, 30.0]);
124        let result = profit_factor.calculate_from_returns(&returns);
125        assert!(result.is_some());
126        assert!(result.unwrap().is_nan());
127    }
128
129    #[rstest]
130    fn test_all_negative() {
131        let profit_factor = ProfitFactor {};
132        let returns = create_returns(vec![-10.0, -20.0, -30.0]);
133        let result = profit_factor.calculate_from_returns(&returns);
134        assert!(result.is_some());
135        assert!(approx_eq!(f64, result.unwrap(), 0.0, epsilon = 1e-9));
136    }
137
138    #[rstest]
139    fn test_mixed_returns() {
140        let profit_factor = ProfitFactor {};
141        let returns = create_returns(vec![10.0, -20.0, 30.0, -40.0]);
142        let result = profit_factor.calculate_from_returns(&returns);
143        assert!(result.is_some());
144        // (10.0 + 30.0) / |-20.0 + -40.0| = 40 / 60 = 0.666...
145        assert!(approx_eq!(
146            f64,
147            result.unwrap(),
148            0.6666666666666666,
149            epsilon = 1e-9
150        ));
151    }
152
153    #[rstest]
154    fn test_with_zero() {
155        let profit_factor = ProfitFactor {};
156        let returns = create_returns(vec![10.0, 0.0, -20.0, -30.0]);
157        let result = profit_factor.calculate_from_returns(&returns);
158        assert!(result.is_some());
159        // Zero excluded: 10.0 / |-20.0 + -30.0| = 10 / 50 = 0.2
160        assert!(approx_eq!(f64, result.unwrap(), 0.2, epsilon = 1e-9));
161    }
162
163    #[rstest]
164    fn test_equal_positive_negative() {
165        let profit_factor = ProfitFactor {};
166        let returns = create_returns(vec![20.0, -20.0]);
167        let result = profit_factor.calculate_from_returns(&returns);
168        assert!(result.is_some());
169        assert!(approx_eq!(f64, result.unwrap(), 1.0, epsilon = 1e-9));
170    }
171
172    #[rstest]
173    fn test_name() {
174        let profit_factor = ProfitFactor {};
175        assert_eq!(profit_factor.name(), "Profit Factor");
176    }
177}