use std::fmt::Display;
use nautilus_core::correctness::check_predicate_true;
use nautilus_model::position::Position;
use crate::{Returns, statistic::PortfolioStatistic};
#[repr(C)]
#[derive(Debug, Clone)]
#[cfg_attr(
feature = "python",
pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.analysis", from_py_object)
)]
#[cfg_attr(
feature = "python",
pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.analysis")
)]
pub struct OmegaRatio {
threshold: f64,
}
impl OmegaRatio {
pub fn new_checked(threshold: Option<f64>) -> anyhow::Result<Self> {
let threshold = threshold.unwrap_or(0.0);
check_predicate_true(threshold.is_finite(), "threshold must be finite")?;
Ok(Self { threshold })
}
#[must_use]
pub fn new(threshold: Option<f64>) -> Self {
Self::new_checked(threshold).expect("Invalid `threshold` for `OmegaRatio`")
}
}
impl Display for OmegaRatio {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Omega Ratio (threshold {})", self.threshold)
}
}
impl PortfolioStatistic for OmegaRatio {
type Item = f64;
fn name(&self) -> String {
self.to_string()
}
fn calculate_from_returns(&self, raw_returns: &Returns) -> Option<Self::Item> {
if !self.check_valid_returns(raw_returns) {
return Some(f64::NAN);
}
let returns = self.downsample_to_daily_bins(raw_returns);
let mut gain = 0.0;
let mut loss = 0.0;
for &ret in returns.values() {
let excess = ret - self.threshold;
if excess > 0.0 {
gain += excess;
} else {
loss -= excess;
}
}
if loss <= 0.0 {
return Some(f64::NAN);
}
Some(gain / loss)
}
fn calculate_from_realized_pnls(&self, _realized_pnls: &[f64]) -> Option<Self::Item> {
None
}
fn calculate_from_positions(&self, _positions: &[Position]) -> Option<Self::Item> {
None
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use nautilus_core::{UnixNanos, approx_eq};
use rstest::rstest;
use super::*;
fn create_returns(values: &[f64]) -> BTreeMap<UnixNanos, f64> {
let mut new_return = BTreeMap::new();
let one_day_in_nanos = 86_400_000_000_000;
let start_time = 1_600_000_000_000_000_000;
for (i, &value) in values.iter().enumerate() {
let timestamp = start_time + i as u64 * one_day_in_nanos;
new_return.insert(UnixNanos::from(timestamp), value);
}
new_return
}
#[rstest]
fn test_name() {
let ratio = OmegaRatio::new(None);
assert_eq!(ratio.name(), "Omega Ratio (threshold 0)");
}
#[rstest]
fn test_empty_returns() {
let ratio = OmegaRatio::new(None);
let returns = create_returns(&[]);
let result = ratio.calculate_from_returns(&returns);
assert!(result.is_some());
assert!(result.unwrap().is_nan());
}
#[rstest]
fn test_no_losses_is_nan() {
let ratio = OmegaRatio::new(None);
let returns = create_returns(&[0.01, 0.02, 0.015]);
let result = ratio.calculate_from_returns(&returns);
assert!(result.is_some());
assert!(result.unwrap().is_nan());
}
#[rstest]
fn test_omega_ratio_calculation() {
let ratio = OmegaRatio::new(Some(0.0));
let returns = create_returns(&[0.01, -0.02, 0.015, -0.005, 0.025]);
let result = ratio.calculate_from_returns(&returns).unwrap();
assert!(approx_eq!(f64, result, 2.0, epsilon = 1e-12));
}
#[rstest]
#[case(Some(f64::NAN))]
#[case(Some(f64::INFINITY))]
#[case(Some(f64::NEG_INFINITY))]
fn test_new_checked_rejects_non_finite_threshold(#[case] threshold: Option<f64>) {
assert!(OmegaRatio::new_checked(threshold).is_err());
}
#[rstest]
#[case(None)]
#[case(Some(0.0))]
#[case(Some(-0.02))]
#[case(Some(0.5))]
fn test_new_checked_accepts_finite_threshold(#[case] threshold: Option<f64>) {
assert!(OmegaRatio::new_checked(threshold).is_ok());
}
}