fix(ops): unify ddof=0 for ts_covariance, fix corr identity#2
Merged
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
Numerical Impact
ts_covariance output changes by factor of (n-1)/n:
ts_corr and ts_autocorr output: unchanged.
Cross-validated against numpy to machine precision (diff < 1e-15).
Testing
pytest tests/ -v)ruff check elvers/)