nautilus_analysis/statistics/
omega_ratio.rs1use std::fmt::Display;
19
20use nautilus_core::correctness::check_predicate_true;
21use nautilus_model::position::Position;
22
23use crate::{Returns, statistic::PortfolioStatistic};
24
25#[repr(C)]
43#[derive(Debug, Clone)]
44#[cfg_attr(
45 feature = "python",
46 pyo3::pyclass(module = "nautilus_trader.analysis", from_py_object)
47)]
48#[cfg_attr(
49 feature = "python",
50 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.analysis")
51)]
52pub struct OmegaRatio {
53 threshold: f64,
55}
56
57impl OmegaRatio {
58 pub fn new_checked(threshold: Option<f64>) -> anyhow::Result<Self> {
64 let threshold = threshold.unwrap_or(0.0);
65 check_predicate_true(threshold.is_finite(), "threshold must be finite")?;
66 Ok(Self { threshold })
67 }
68
69 #[must_use]
75 pub fn new(threshold: Option<f64>) -> Self {
76 Self::new_checked(threshold).expect("Invalid `threshold` for `OmegaRatio`")
77 }
78}
79
80impl Display for OmegaRatio {
81 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82 write!(f, "Omega Ratio (threshold {})", self.threshold)
83 }
84}
85
86impl PortfolioStatistic for OmegaRatio {
87 type Item = f64;
88
89 fn name(&self) -> String {
90 self.to_string()
91 }
92
93 fn calculate_from_returns(&self, raw_returns: &Returns) -> Option<Self::Item> {
94 if !self.check_valid_returns(raw_returns) {
95 return Some(f64::NAN);
96 }
97
98 let returns = self.downsample_to_daily_bins(raw_returns);
99
100 let mut gain = 0.0;
101 let mut loss = 0.0;
102
103 for &ret in returns.values() {
104 let excess = ret - self.threshold;
105 if excess > 0.0 {
106 gain += excess;
107 } else {
108 loss -= excess;
109 }
110 }
111
112 if loss <= 0.0 {
113 return Some(f64::NAN);
114 }
115
116 Some(gain / loss)
117 }
118
119 fn calculate_from_realized_pnls(&self, _realized_pnls: &[f64]) -> Option<Self::Item> {
120 None
121 }
122
123 fn calculate_from_positions(&self, _positions: &[Position]) -> Option<Self::Item> {
124 None
125 }
126}
127
128#[cfg(test)]
129mod tests {
130 use std::collections::BTreeMap;
131
132 use nautilus_core::{UnixNanos, approx_eq};
133 use rstest::rstest;
134
135 use super::*;
136
137 fn create_returns(values: &[f64]) -> BTreeMap<UnixNanos, f64> {
138 let mut new_return = BTreeMap::new();
139 let one_day_in_nanos = 86_400_000_000_000;
140 let start_time = 1_600_000_000_000_000_000;
141
142 for (i, &value) in values.iter().enumerate() {
143 let timestamp = start_time + i as u64 * one_day_in_nanos;
144 new_return.insert(UnixNanos::from(timestamp), value);
145 }
146
147 new_return
148 }
149
150 #[rstest]
151 fn test_name() {
152 let ratio = OmegaRatio::new(None);
153 assert_eq!(ratio.name(), "Omega Ratio (threshold 0)");
154 }
155
156 #[rstest]
157 fn test_empty_returns() {
158 let ratio = OmegaRatio::new(None);
159 let returns = create_returns(&[]);
160 let result = ratio.calculate_from_returns(&returns);
161 assert!(result.is_some());
162 assert!(result.unwrap().is_nan());
163 }
164
165 #[rstest]
166 fn test_no_losses_is_nan() {
167 let ratio = OmegaRatio::new(None);
169 let returns = create_returns(&[0.01, 0.02, 0.015]);
170 let result = ratio.calculate_from_returns(&returns);
171 assert!(result.is_some());
172 assert!(result.unwrap().is_nan());
173 }
174
175 #[rstest]
176 fn test_omega_ratio_calculation() {
177 let ratio = OmegaRatio::new(Some(0.0));
181 let returns = create_returns(&[0.01, -0.02, 0.015, -0.005, 0.025]);
182 let result = ratio.calculate_from_returns(&returns).unwrap();
183 assert!(approx_eq!(f64, result, 2.0, epsilon = 1e-12));
184 }
185
186 #[rstest]
187 #[case(Some(f64::NAN))]
188 #[case(Some(f64::INFINITY))]
189 #[case(Some(f64::NEG_INFINITY))]
190 fn test_new_checked_rejects_non_finite_threshold(#[case] threshold: Option<f64>) {
191 assert!(OmegaRatio::new_checked(threshold).is_err());
192 }
193
194 #[rstest]
195 #[case(None)]
196 #[case(Some(0.0))]
197 #[case(Some(-0.02))]
198 #[case(Some(0.5))]
199 fn test_new_checked_accepts_finite_threshold(#[case] threshold: Option<f64>) {
200 assert!(OmegaRatio::new_checked(threshold).is_ok());
201 }
202}