Skip to main content

nautilus_analysis/statistics/
long_ratio.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 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::{enums::OrderSide, position::Position};
19
20use crate::{Returns, statistic::PortfolioStatistic};
21
22/// Calculates the ratio of long positions to total positions.
23///
24/// A position counts as long when its entry (opening order) side is `Buy`.
25/// The result is in `[0, 1]`, rounded to `precision` decimal places, and is
26/// `None` for an empty position list.
27#[repr(C)]
28#[derive(Debug, Clone)]
29#[cfg_attr(
30    feature = "python",
31    pyo3::pyclass(module = "nautilus_trader.analysis", from_py_object)
32)]
33#[cfg_attr(
34    feature = "python",
35    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.analysis")
36)]
37pub struct LongRatio {
38    /// The number of decimal places to round the ratio to (default: 2).
39    pub precision: usize,
40}
41
42impl LongRatio {
43    /// Creates a new [`LongRatio`] instance.
44    #[must_use]
45    pub fn new(precision: Option<usize>) -> Self {
46        Self {
47            precision: precision.unwrap_or(2),
48        }
49    }
50}
51
52impl Display for LongRatio {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        write!(f, "Long Ratio")
55    }
56}
57
58impl PortfolioStatistic for LongRatio {
59    type Item = f64;
60
61    fn name(&self) -> String {
62        self.to_string()
63    }
64
65    fn calculate_from_positions(&self, positions: &[Position]) -> Option<Self::Item> {
66        if positions.is_empty() {
67            return None;
68        }
69
70        // Use `entry` (the opening order side) rather than `side` because
71        // closed positions have side == PositionSide::Flat
72        let long_count = positions
73            .iter()
74            .filter(|p| p.entry == OrderSide::Buy)
75            .count();
76
77        let value = long_count as f64 / positions.len() as f64;
78
79        let scale = 10f64.powi(self.precision as i32);
80        Some((value * scale).round() / scale)
81    }
82    fn calculate_from_returns(&self, _returns: &Returns) -> Option<Self::Item> {
83        None
84    }
85
86    fn calculate_from_realized_pnls(&self, _realized_pnls: &[f64]) -> Option<Self::Item> {
87        None
88    }
89}
90
91#[cfg(test)]
92mod tests {
93    use ahash::AHashSet;
94    use indexmap::IndexMap;
95    use nautilus_core::{UnixNanos, approx_eq};
96    use nautilus_model::{
97        enums::{InstrumentClass, OrderSide, PositionSide},
98        identifiers::{
99            AccountId, ClientOrderId, PositionId,
100            stubs::{instrument_id_aud_usd_sim, strategy_id_ema_cross, trader_id},
101        },
102        stubs::TestDefault,
103        types::{Currency, Quantity},
104    };
105    use rstest::rstest;
106
107    use super::*;
108
109    /// Creates a closed position with the given entry side.
110    /// Closed positions have side == Flat, so we test with `entry` field.
111    fn create_closed_position(entry: OrderSide) -> Position {
112        Position {
113            events: Vec::new(),
114            replay_events: Vec::new(),
115            fill_voids: Vec::new(),
116            trader_id: trader_id(),
117            strategy_id: strategy_id_ema_cross(),
118            instrument_id: instrument_id_aud_usd_sim(),
119            id: PositionId::new("test-position"),
120            account_id: AccountId::new("test-account"),
121            opening_order_id: ClientOrderId::test_default(),
122            closing_order_id: None,
123            entry,
124            side: PositionSide::Flat, // Closed positions are Flat
125            signed_qty: 0.0,
126            quantity: Quantity::default(),
127            peak_qty: Quantity::default(),
128            price_precision: 2,
129            size_precision: 2,
130            multiplier: Quantity::default(),
131            is_inverse: false,
132            base_currency: None,
133            quote_currency: Currency::USD(),
134            settlement_currency: Currency::USD(),
135            ts_init: UnixNanos::default(),
136            ts_opened: UnixNanos::default(),
137            ts_last: UnixNanos::default(),
138            ts_closed: Some(UnixNanos::from(1)), // Mark as closed
139            duration_ns: 2,
140            avg_px_open: 0.0,
141            avg_px_close: Some(0.0),
142            realized_return: 0.0,
143            realized_pnl: None,
144            trade_ids: AHashSet::new(),
145            buy_qty: Quantity::default(),
146            sell_qty: Quantity::default(),
147            commissions: IndexMap::new(),
148            adjustments: Vec::new(),
149            instrument_class: InstrumentClass::Spot,
150            is_currency_pair: true,
151        }
152    }
153
154    #[rstest]
155    fn test_empty_positions() {
156        let long_ratio = LongRatio::new(None);
157        let result = long_ratio.calculate_from_positions(&[]);
158        assert!(result.is_none());
159    }
160
161    #[rstest]
162    fn test_all_long_positions() {
163        let long_ratio = LongRatio::new(None);
164        let positions = vec![
165            create_closed_position(OrderSide::Buy),
166            create_closed_position(OrderSide::Buy),
167            create_closed_position(OrderSide::Buy),
168        ];
169
170        let result = long_ratio.calculate_from_positions(&positions);
171        assert!(result.is_some());
172        assert!(approx_eq!(f64, result.unwrap(), 1.00, epsilon = 1e-9));
173    }
174
175    #[rstest]
176    fn test_all_short_positions() {
177        let long_ratio = LongRatio::new(None);
178        let positions = vec![
179            create_closed_position(OrderSide::Sell),
180            create_closed_position(OrderSide::Sell),
181            create_closed_position(OrderSide::Sell),
182        ];
183
184        let result = long_ratio.calculate_from_positions(&positions);
185        assert!(result.is_some());
186        assert!(approx_eq!(f64, result.unwrap(), 0.00, epsilon = 1e-9));
187    }
188
189    #[rstest]
190    fn test_mixed_positions() {
191        let long_ratio = LongRatio::new(None);
192        let positions = vec![
193            create_closed_position(OrderSide::Buy),
194            create_closed_position(OrderSide::Sell),
195            create_closed_position(OrderSide::Buy),
196            create_closed_position(OrderSide::Sell),
197        ];
198
199        let result = long_ratio.calculate_from_positions(&positions);
200        assert!(result.is_some());
201        assert!(approx_eq!(f64, result.unwrap(), 0.50, epsilon = 1e-9));
202    }
203
204    #[rstest]
205    fn test_custom_precision() {
206        let long_ratio = LongRatio::new(Some(3));
207        let positions = vec![
208            create_closed_position(OrderSide::Buy),
209            create_closed_position(OrderSide::Buy),
210            create_closed_position(OrderSide::Sell),
211        ];
212
213        let result = long_ratio.calculate_from_positions(&positions);
214        assert!(result.is_some());
215        assert!(approx_eq!(f64, result.unwrap(), 0.667, epsilon = 1e-9));
216    }
217
218    #[rstest]
219    fn test_single_position_long() {
220        let long_ratio = LongRatio::new(None);
221        let positions = vec![create_closed_position(OrderSide::Buy)];
222
223        let result = long_ratio.calculate_from_positions(&positions);
224        assert!(result.is_some());
225        assert!(approx_eq!(f64, result.unwrap(), 1.00, epsilon = 1e-9));
226    }
227
228    #[rstest]
229    fn test_single_position_short() {
230        let long_ratio = LongRatio::new(None);
231        let positions = vec![create_closed_position(OrderSide::Sell)];
232
233        let result = long_ratio.calculate_from_positions(&positions);
234        assert!(result.is_some());
235        assert!(approx_eq!(f64, result.unwrap(), 0.00, epsilon = 1e-9));
236    }
237
238    #[rstest]
239    fn test_zero_precision() {
240        let long_ratio = LongRatio::new(Some(0));
241        let positions = vec![
242            create_closed_position(OrderSide::Buy),
243            create_closed_position(OrderSide::Buy),
244            create_closed_position(OrderSide::Sell),
245        ];
246
247        let result = long_ratio.calculate_from_positions(&positions);
248        assert!(result.is_some());
249        assert!(approx_eq!(f64, result.unwrap(), 1.00, epsilon = 1e-9));
250    }
251
252    #[rstest]
253    fn test_name() {
254        let long_ratio = LongRatio::new(None);
255        assert_eq!(long_ratio.name(), "Long Ratio");
256    }
257}