From 07e18043145f3d91c8ea7ec3ad41b3c905585277 Mon Sep 17 00:00:00 2001 From: Ethan Werner Date: Wed, 1 Jul 2026 09:42:39 +0400 Subject: 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 --- lib/cmf.c | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 lib/cmf.c (limited to 'lib/cmf.c') diff --git a/lib/cmf.c b/lib/cmf.c new file mode 100644 index 0000000..7ac0402 --- /dev/null +++ b/lib/cmf.c @@ -0,0 +1,67 @@ +// Chaikin Money Flow +// +// cmf - CMF +// +// SUM(MF * V) / SUM(V) over period, where MF = ((C-L)-(H-C))/(H-L) +// +// Inputs: 5 (OHLCV) +// Outputs: 1 (CMF) +// Constants: 1 (period) + +#include +#include "ts.h" + +typedef struct { + uint_t k; +} ts_cmf_params_t; + +ts_parameter_t const ts_cmf_p = { .n_inputs = 5, .n_outputs = 1, .n_constants = 1, .params_size = sizeof(ts_cmf_params_t) }; + +uint_t ts_cmf_offset( ts_constant_t const *c ) +{ + ( void )c; + return ( c ? ((ts_cmf_params_t *)c)->k - 1 : 0 ); +} + +int ts_cmf( + 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_cmf_p ); + if ( !c ) return -1; + uint_t k = ((ts_cmf_params_t *)c)->k; + if (k == 0 || n < k) return -1; + + fp_t sum_mf = 0; + fp_t sum_vol = 0; + + for ( uint_t i = 0; i < k; ++i ) + { + fp_t hl = ts_h( x, i ) - ts_l( x, i ); + fp_t mf = hl != 0 ? ( ( ts_c( x, i ) - ts_l( x, i ) ) - ( ts_h( x, i ) - ts_c( x, i ) ) ) / hl * ts_v( x, i ) : 0; + sum_mf += mf; + sum_vol += ts_v( x, i ); + } + + y[0][k - 1] = sum_vol != 0 ? sum_mf / sum_vol : 0; + + for ( uint_t i = k; i < n; ++i ) + { + fp_t hl_prev = ts_h( x, i - k ) - ts_l( x, i - k ); + fp_t mf_prev = hl_prev != 0 ? ( ( ts_c( x, i - k ) - ts_l( x, i - k ) ) - ( ts_h( x, i - k ) - ts_c( x, i - k ) ) ) / hl_prev * ts_v( x, i - k ) : 0; + + fp_t hl_cur = ts_h( x, i ) - ts_l( x, i ); + fp_t mf_cur = hl_cur != 0 ? ( ( ts_c( x, i ) - ts_l( x, i ) ) - ( ts_h( x, i ) - ts_c( x, i ) ) ) / hl_cur * ts_v( x, i ) : 0; + + sum_mf = sum_mf - mf_prev + mf_cur; + sum_vol = sum_vol - ts_v( x, i - k ) + ts_v( x, i ); + + y[0][i] = sum_vol != 0 ? sum_mf / sum_vol : 0; + } + return 0; +} + + + -- cgit v1.3.1