diff options
| author | Ethan Werner <mail@ethanwerner.com> | 2026-07-01 09:42:39 +0400 |
|---|---|---|
| committer | Ethan Werner <mail@ethanwerner.com> | 2026-07-01 09:42:39 +0400 |
| commit | 07e18043145f3d91c8ea7ec3ad41b3c905585277 (patch) | |
| tree | 2bdeae46973f4bdfce263679a4008ac768011f28 /lib/correlation_coefficient.c | |
initial commit: ts time series analysis library v0.1.0
- 354 financial and mathematical time-series indicators
- Uniform C11 API with consistent function signatures
- 349 passing tests with -Werror
- Static and shared library builds
- pkg-config integration
- Python bindings
- Fuzzing and sanitizer support
- Security hardening flags
Diffstat (limited to 'lib/correlation_coefficient.c')
| -rw-r--r-- | lib/correlation_coefficient.c | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/lib/correlation_coefficient.c b/lib/correlation_coefficient.c new file mode 100644 index 0000000..d20d1ea --- /dev/null +++ b/lib/correlation_coefficient.c @@ -0,0 +1,75 @@ +// Correlation Coefficient +// +// correlation_coefficient - corr +// +// Pearson r = (n*Σxy - Σx*Σy) / √((n*Σx²-Σx²)(n*Σy²-Σy²)) +// +// Inputs: 2 +// Outputs: 1 (r) +// Constants: 1 (period) + +#include <math.h> +#include "ts.h" + +typedef struct { + uint_t k; +} ts_correlation_coefficient_params_t; + +ts_parameter_t const ts_correlation_coefficient_p = { .n_inputs = 2, .n_outputs = 1, .n_constants = 1, .params_size = sizeof(ts_correlation_coefficient_params_t) }; + +uint_t ts_correlation_coefficient_offset( ts_constant_t const *c ) +{ + ( void )c; + return ( c ? ((ts_correlation_coefficient_params_t *)c)->k - 1 : 0 ); +} + +int ts_correlation_coefficient( + fp_t * const *y, uint_t y_n, + fp_t const * const *x, uint_t x_n, + uint_t n, ts_constant_t const *c +) +{ + TS_PROLOGUE( ts_correlation_coefficient_p ); + if ( !c ) return -1; + uint_t k = ((ts_correlation_coefficient_params_t *)c)->k; + if (k == 0 || n < k) return -1; + + fp_t sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0, sum_y2 = 0; + + for ( uint_t i = 0; i < k; ++i ) + { + fp_t xi = x[0][i]; + fp_t yi = x[1][i]; + sum_x += xi; + sum_y += yi; + sum_xy += xi * yi; + sum_x2 += xi * xi; + sum_y2 += yi * yi; + } + + fp_t denom = ( k * sum_x2 - sum_x * sum_x ) * ( k * sum_y2 - sum_y * sum_y ); + fp_t numer = k * sum_xy - sum_x * sum_y; + y[0][k - 1] = denom > 0 ? numer / sqrt( denom ) : 0; + + for ( uint_t i = k; i < n; ++i ) + { + fp_t xi_old = x[0][i - k]; + fp_t yi_old = x[1][i - k]; + fp_t xi_new = x[0][i]; + fp_t yi_new = x[1][i]; + + sum_x = sum_x - xi_old + xi_new; + sum_y = sum_y - yi_old + yi_new; + sum_xy = sum_xy - xi_old * yi_old + xi_new * yi_new; + sum_x2 = sum_x2 - xi_old * xi_old + xi_new * xi_new; + sum_y2 = sum_y2 - yi_old * yi_old + yi_new * yi_new; + + denom = ( k * sum_x2 - sum_x * sum_x ) * ( k * sum_y2 - sum_y * sum_y ); + numer = k * sum_xy - sum_x * sum_y; + y[0][i] = denom > 0 ? numer / sqrt( denom ) : 0; + } + return 0; +} + + + |