From 0eceec29d521da916c7c3016d487c825d3f5f2e2 Mon Sep 17 00:00:00 2001 From: Soojal1807 <2004soojal@gmail.com> Date: Sun, 14 Jun 2026 12:34:03 +0530 Subject: [PATCH] fix: resolve NaN value return in stats --- quantstats/stats.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/quantstats/stats.py b/quantstats/stats.py index 266f9513..0a3006d5 100644 --- a/quantstats/stats.py +++ b/quantstats/stats.py @@ -823,9 +823,19 @@ def autocorr_penalty( # returns.to_csv('/Users/ran/Desktop/test.csv') num = len(returns) + # Fix: corrcoef on fewer than 2 points is undefined and returns NaN + # with a RuntimeWarning, so bail out early with the neutral penalty + if num < 2: + return 1.0 + # Calculate autocorrelation coefficient between consecutive returns coef = _np.abs(_np.corrcoef(returns[:-1], returns[1:])[0, 1]) + # Fix: zero-variance (constant) returns also make corrcoef return NaN, + # which would otherwise silently propagate through the sum below + if _np.isnan(coef): + return 1.0 + # Vectorized calculation instead of list comprehension x = _np.arange(1, num) # Calculate weighted correlation effects over time