Skip to main content

nautilus_analysis/statistics/
information_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
16//! Information ratio statistic (benchmark-relative).
17
18use std::fmt::Display;
19
20use nautilus_model::position::Position;
21
22use crate::{
23    Returns, statistic::PortfolioStatistic, statistics::tracking_error::active_return_stats,
24};
25
26/// Calculates the information ratio of portfolio returns relative to a benchmark.
27///
28/// The information ratio measures active return per unit of active risk (tracking error):
29///
30/// `IR = mean(active) / std(active) * sqrt(period)`
31///
32/// where `active_i = portfolio_i - benchmark_i`, `std` uses Bessel's correction
33/// (`ddof = 1`), and the ratio is annualized by the square root of the specified period
34/// (default: 252 trading days).
35///
36/// # References
37///
38/// - Goodwin, T. H. (1998). "The Information Ratio". *Financial Analysts Journal*, 54(4), 34-43.
39/// - CFA Institute Investment Foundations, 3rd Edition
40#[repr(C)]
41#[derive(Debug, Clone)]
42#[cfg_attr(
43    feature = "python",
44    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.analysis", from_py_object)
45)]
46#[cfg_attr(
47    feature = "python",
48    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.analysis")
49)]
50pub struct InformationRatio {
51    /// The annualization period (default: 252 for daily data).
52    period: usize,
53}
54
55impl InformationRatio {
56    /// Creates a new [`InformationRatio`] instance.
57    #[must_use]
58    pub fn new(period: Option<usize>) -> Self {
59        Self {
60            period: period.unwrap_or(252),
61        }
62    }
63}
64
65impl Display for InformationRatio {
66    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67        write!(f, "Information Ratio ({} days)", self.period)
68    }
69}
70
71impl PortfolioStatistic for InformationRatio {
72    type Item = f64;
73
74    fn name(&self) -> String {
75        self.to_string()
76    }
77
78    fn calculate_from_returns(&self, _returns: &Returns) -> Option<Self::Item> {
79        None
80    }
81
82    fn calculate_from_realized_pnls(&self, _realized_pnls: &[f64]) -> Option<Self::Item> {
83        None
84    }
85
86    fn calculate_from_positions(&self, _positions: &[Position]) -> Option<Self::Item> {
87        None
88    }
89
90    fn calculate_from_returns_with_benchmark(
91        &self,
92        returns: &Returns,
93        benchmark: &Returns,
94    ) -> Option<Self::Item> {
95        let (r, b) = self.align_returns(returns, benchmark);
96        if r.len() < 2 {
97            return Some(f64::NAN);
98        }
99
100        let (mean_active, std_active) = active_return_stats(&r, &b);
101        if std_active < f64::EPSILON {
102            return Some(f64::NAN);
103        }
104
105        let ir_period = mean_active / std_active;
106        Some(ir_period * (self.period as f64).sqrt())
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use std::collections::BTreeMap;
113
114    use nautilus_core::{UnixNanos, approx_eq};
115    use rstest::rstest;
116
117    use super::*;
118
119    fn create_returns(values: &[f64]) -> BTreeMap<UnixNanos, f64> {
120        let mut new_return = BTreeMap::new();
121        let one_day_in_nanos = 86_400_000_000_000;
122        let start_time = 1_600_000_000_000_000_000;
123
124        for (i, &value) in values.iter().enumerate() {
125            let timestamp = start_time + i as u64 * one_day_in_nanos;
126            new_return.insert(UnixNanos::from(timestamp), value);
127        }
128
129        new_return
130    }
131
132    #[rstest]
133    fn test_name() {
134        let stat = InformationRatio::new(None);
135        assert_eq!(stat.name(), "Information Ratio (252 days)");
136    }
137
138    #[rstest]
139    fn test_name_non_default_period() {
140        let stat = InformationRatio::new(Some(63));
141        assert_eq!(stat.name(), "Information Ratio (63 days)");
142    }
143
144    #[rstest]
145    fn test_known_value_nonzero_benchmark() {
146        // Both strategy and benchmark non-zero so the (r - b) subtraction is exercised.
147        //   r       = [0.03, -0.01, 0.02, 0.04]
148        //   b       = [0.01, 0.005, 0.005, 0.01]
149        //   active  = [0.02, -0.015, 0.015, 0.03]
150        //   mean(active)       = 0.0125
151        //   std(active, ddof=1)= 0.019364916731037084
152        //   IR = 0.0125 / 0.019364916731037084 * sqrt(252) = 10.246950765959598
153        // A formula dropping the benchmark (active = r) would yield 14.69693845669907,
154        // so this value discriminates against that bug.
155        let returns = create_returns(&[0.03, -0.01, 0.02, 0.04]);
156        let benchmark = create_returns(&[0.01, 0.005, 0.005, 0.01]);
157        let stat = InformationRatio::new(Some(252));
158        let result = stat
159            .calculate_from_returns_with_benchmark(&returns, &benchmark)
160            .unwrap();
161        assert!(approx_eq!(f64, result, 10.246950765959598, epsilon = 1e-9));
162    }
163
164    #[rstest]
165    fn test_partial_overlap_inner_join() {
166        // Strategy on days 0..5, benchmark on days 2..7 -> overlap on days 2,3,4 only.
167        let one_day = 86_400_000_000_000_u64;
168        let start = 1_600_000_000_000_000_000_u64;
169
170        let mut returns = BTreeMap::new();
171        for (i, v) in [0.05, 0.06, 0.030, -0.010, 0.020].iter().enumerate() {
172            returns.insert(UnixNanos::from(start + i as u64 * one_day), *v);
173        }
174        let mut benchmark = BTreeMap::new();
175        for (i, v) in [0.005, 0.010, 0.015, 0.040, 0.050].iter().enumerate() {
176            benchmark.insert(UnixNanos::from(start + (i as u64 + 2) * one_day), *v);
177        }
178
179        // Overlap days 2,3,4: r = [0.030, -0.010, 0.020], b = [0.005, 0.010, 0.015].
180        //   active = [0.025, -0.020, 0.005]
181        //   IR = mean(active) / std(active, ddof=1) * sqrt(252) = 2.3469547761538725
182        let stat = InformationRatio::new(Some(252));
183        let result = stat
184            .calculate_from_returns_with_benchmark(&returns, &benchmark)
185            .unwrap();
186        assert!(approx_eq!(f64, result, 2.3469547761538725, epsilon = 1e-9));
187    }
188
189    #[rstest]
190    fn test_intraday_compounds_before_join() {
191        // Day 0 carries two intraday strategy returns that must compound into one daily
192        // bin BEFORE the inner-join: (1.02)(1.03) - 1 = 0.0506. Day 1 carries 0.01.
193        // Benchmark is one daily return per day: [0.015, 0.004].
194        //   active = [0.0506 - 0.015, 0.01 - 0.004] = [0.0356, 0.006]
195        //   IR = mean(active) / std(active, ddof=1) * sqrt(252) = 15.775636549641483
196        // Arithmetic-summing the intraday day-0 returns (0.05) would change the result,
197        // so this confirms geometric compounding happens before the join.
198        let one_day = 86_400_000_000_000_u64;
199        let one_hour = 3_600_000_000_000_u64;
200        let start = 1_600_000_000_000_000_000_u64;
201
202        let mut returns = BTreeMap::new();
203        returns.insert(UnixNanos::from(start), 0.02);
204        returns.insert(UnixNanos::from(start + one_hour), 0.03);
205        returns.insert(UnixNanos::from(start + one_day), 0.01);
206
207        let mut benchmark = BTreeMap::new();
208        benchmark.insert(UnixNanos::from(start), 0.015);
209        benchmark.insert(UnixNanos::from(start + one_day), 0.004);
210
211        let active = [(1.02_f64 * 1.03 - 1.0) - 0.015, 0.01 - 0.004];
212        let mean_active = active.iter().sum::<f64>() / active.len() as f64;
213        let var = active
214            .iter()
215            .map(|&x| (x - mean_active).powi(2))
216            .sum::<f64>()
217            / (active.len() as f64 - 1.0);
218        let expected = mean_active / var.sqrt() * 252.0_f64.sqrt();
219
220        let stat = InformationRatio::new(Some(252));
221        let result = stat
222            .calculate_from_returns_with_benchmark(&returns, &benchmark)
223            .unwrap();
224        assert!(approx_eq!(f64, result, expected, epsilon = 1e-9));
225        assert!(approx_eq!(f64, result, 15.775636549641483, epsilon = 1e-9));
226    }
227
228    #[rstest]
229    fn test_known_value() {
230        // active = strategy - benchmark = [0.01, 0.02, 0.03] (a clean arithmetic case).
231        // mean = 0.02, sample std (ddof=1) = 0.01, ir_period = 2.0,
232        // annualized = 2.0 * sqrt(4) = 4.0.
233        let benchmark = create_returns(&[0.00, 0.00, 0.00]);
234        let returns = create_returns(&[0.01, 0.02, 0.03]);
235        let stat = InformationRatio::new(Some(4));
236        let result = stat
237            .calculate_from_returns_with_benchmark(&returns, &benchmark)
238            .unwrap();
239        assert!(approx_eq!(f64, result, 4.0, epsilon = 1e-12));
240    }
241
242    #[rstest]
243    fn test_zero_active_std_is_nan() {
244        // strategy - benchmark constant -> std(active) = 0 -> NaN.
245        let benchmark = create_returns(&[0.01, -0.02, 0.015, -0.005]);
246        let returns = create_returns(&[0.02, -0.01, 0.025, 0.005]);
247        let stat = InformationRatio::new(None);
248        let result = stat
249            .calculate_from_returns_with_benchmark(&returns, &benchmark)
250            .unwrap();
251        assert!(result.is_nan());
252    }
253
254    #[rstest]
255    fn test_empty_returns_is_nan() {
256        let stat = InformationRatio::new(None);
257        let result = stat
258            .calculate_from_returns_with_benchmark(&create_returns(&[]), &create_returns(&[]))
259            .unwrap();
260        assert!(result.is_nan());
261    }
262
263    #[rstest]
264    fn test_single_overlap_is_nan() {
265        let benchmark = create_returns(&[0.01, -0.02, 0.015]);
266        let returns = create_returns(&[0.02]);
267        let stat = InformationRatio::new(None);
268        let result = stat
269            .calculate_from_returns_with_benchmark(&returns, &benchmark)
270            .unwrap();
271        assert!(result.is_nan());
272    }
273}