Skip to main content

nautilus_analysis/statistics/
sharpe_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::position::Position;
19
20use crate::{Returns, statistic::PortfolioStatistic};
21
22/// Calculates the Sharpe ratio for portfolio returns.
23///
24/// The Sharpe ratio measures risk-adjusted return and is calculated as:
25/// `(Mean Return - Risk-free Rate) / Standard Deviation of Returns * sqrt(period)`
26///
27/// This implementation assumes a risk-free rate of 0 and annualizes the ratio
28/// using the square root of the specified period (default: 252 trading days).
29///
30/// # References
31///
32/// - Sharpe, W. F. (1966). "Mutual Fund Performance". *Journal of Business*, 39(1), 119-138.
33/// - Sharpe, W. F. (1994). "The Sharpe Ratio". *Journal of Portfolio Management*, 21(1), 49-58.
34/// - CFA Institute Investment Foundations, 3rd Edition
35#[repr(C)]
36#[derive(Debug, Clone)]
37#[cfg_attr(
38    feature = "python",
39    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.analysis", from_py_object)
40)]
41#[cfg_attr(
42    feature = "python",
43    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.analysis")
44)]
45pub struct SharpeRatio {
46    /// The annualization period (default: 252 for daily data).
47    period: usize,
48}
49
50impl SharpeRatio {
51    /// Creates a new [`SharpeRatio`] instance.
52    #[must_use]
53    pub fn new(period: Option<usize>) -> Self {
54        Self {
55            period: period.unwrap_or(252),
56        }
57    }
58}
59
60impl Display for SharpeRatio {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        write!(f, "Sharpe Ratio ({} days)", self.period)
63    }
64}
65
66impl PortfolioStatistic for SharpeRatio {
67    type Item = f64;
68
69    fn name(&self) -> String {
70        self.to_string()
71    }
72
73    fn calculate_from_returns(&self, raw_returns: &Returns) -> Option<Self::Item> {
74        if !self.check_valid_returns(raw_returns) {
75            return Some(f64::NAN);
76        }
77
78        let returns = self.downsample_to_daily_bins(raw_returns);
79        let mean = returns.values().sum::<f64>() / returns.len() as f64;
80        let std = self.calculate_std(&returns);
81
82        if std < f64::EPSILON {
83            return Some(f64::NAN);
84        }
85
86        let annualized_ratio = (mean / std) * (self.period as f64).sqrt();
87
88        Some(annualized_ratio)
89    }
90    fn calculate_from_realized_pnls(&self, _realized_pnls: &[f64]) -> Option<Self::Item> {
91        None
92    }
93
94    fn calculate_from_positions(&self, _positions: &[Position]) -> Option<Self::Item> {
95        None
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use std::collections::BTreeMap;
102
103    use nautilus_core::{UnixNanos, approx_eq};
104    use rstest::rstest;
105
106    use super::*;
107
108    fn create_returns(values: &[f64]) -> BTreeMap<UnixNanos, f64> {
109        let mut new_return = BTreeMap::new();
110        let one_day_in_nanos = 86_400_000_000_000;
111        let start_time = 1_600_000_000_000_000_000;
112
113        for (i, &value) in values.iter().enumerate() {
114            let timestamp = start_time + i as u64 * one_day_in_nanos;
115            new_return.insert(UnixNanos::from(timestamp), value);
116        }
117
118        new_return
119    }
120
121    #[rstest]
122    fn test_empty_returns() {
123        let ratio = SharpeRatio::new(None);
124        let returns = create_returns(&[]);
125        let result = ratio.calculate_from_returns(&returns);
126        assert!(result.is_some());
127        assert!(result.unwrap().is_nan());
128    }
129
130    #[rstest]
131    fn test_zero_std_dev() {
132        let ratio = SharpeRatio::new(None);
133        let returns = create_returns(&[0.01; 10]);
134        let result = ratio.calculate_from_returns(&returns);
135        assert!(result.is_some());
136        assert!(result.unwrap().is_nan());
137    }
138
139    #[rstest]
140    fn test_valid_sharpe_ratio() {
141        let ratio = SharpeRatio::new(Some(252));
142        let returns = create_returns(&[0.01, -0.02, 0.015, -0.005, 0.025]);
143        let result = ratio.calculate_from_returns(&returns);
144        assert!(result.is_some());
145        assert!(approx_eq!(
146            f64,
147            result.unwrap(),
148            4.48998886412873,
149            epsilon = 1e-9
150        ));
151    }
152
153    #[rstest]
154    fn test_name() {
155        let ratio = SharpeRatio::new(None);
156        assert_eq!(ratio.name(), "Sharpe Ratio (252 days)");
157    }
158}