Skip to content

fix(ops): unify ddof=0 for ts_covariance, fix corr identity#2

Merged
quantbai merged 1 commit intodevfrom
fix/ddof-unify
Mar 24, 2026
Merged

fix(ops): unify ddof=0 for ts_covariance, fix corr identity#2
quantbai merged 1 commit intodevfrom
fix/ddof-unify

Conversation

@quantbai
Copy link
Copy Markdown
Owner

Summary

Unify ddof=0 (population) for ts_covariance. Fixes the broken identity:
ts_covariance(x,y,w) / (ts_std_dev(x,w) * ts_std_dev(y,w)) == ts_corr(x,y,w).
Previously the mixed ddof (cov=1, std=0) caused ~5-20% error depending on window size.

Change Type

  • Bug fix (corrects incorrect behavior)
  • Numerical change (alters factor computation results) [BREAKING]

Numerical Impact

ts_covariance output changes by factor of (n-1)/n:

  • window=5: -20%
  • window=20: -5%
  • window=252: -0.4%

ts_corr and ts_autocorr output: unchanged.
Cross-validated against numpy to machine precision (diff < 1e-15).

Testing

  • Added or updated tests
  • All tests pass (pytest tests/ -v)
  • Lint passes (ruff check elvers/)

ts_covariance changed from ddof=1 (sample) to ddof=0 (population)
to match the library-wide convention. This fixes the broken identity:

  ts_covariance(x,y,w) / (ts_std_dev(x,w) * ts_std_dev(y,w)) == ts_corr(x,y,w)

Previously the mixed ddof (cov=1, std=0) caused the left side to
exceed the true correlation by a factor of n/(n-1).

ts_corr and ts_autocorr retain ddof=1 in Polars rolling_corr because
Polars applies ddof only to the numerator (cov), producing incorrect
results with ddof=0. Correlation output is ddof-invariant so the
values are unaffected.

Cross-validated against numpy to machine precision (diff < 1e-15).

[NUMERICAL] ts_covariance output changes: values are now multiplied
by (n-1)/n relative to previous output. For window=20, this is a 5%
reduction. ts_corr and ts_autocorr output is unchanged.
@quantbai quantbai merged commit 3855125 into dev Mar 24, 2026
4 checks passed
@quantbai quantbai deleted the fix/ddof-unify branch March 24, 2026 09:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant