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/mass_index.c | 91 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 lib/mass_index.c (limited to 'lib/mass_index.c') diff --git a/lib/mass_index.c b/lib/mass_index.c new file mode 100644 index 0000000..1985fab --- /dev/null +++ b/lib/mass_index.c @@ -0,0 +1,91 @@ +// Mass Index +// +// mass_index +// +// Mass Index +// +// SMA of EMA(H/L) ratio, reversal when > threshold +// +// Inputs: 5 +// Outputs: 1 +// Constants: 0 + + +#include +#include "ts.h" + + +ts_parameter_t const ts_mass_index_p = { .n_inputs = 4, .n_outputs = 1, .n_constants = 0, .params_size = 0 }; + +uint_t ts_mass_index_offset( ts_constant_t const *c ) +{ + ( void )c; + return ( 26 ); +} + +int ts_mass_index( + 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_mass_index_p ); + (void)c; + uint_t ema_period = 9; + uint_t sum_period = 26; + + if (n < sum_period) return -1; + + fp_t *hl = calloc( n, sizeof( fp_t ) ); + fp_t *ema1 = calloc( n, sizeof( fp_t ) ); + fp_t *ema2 = calloc( n, sizeof( fp_t ) ); + fp_t *ratio = calloc( n, sizeof( fp_t ) ); + if ( !hl || !ema1 || !ema2 || !ratio ) + { + free( hl ); free( ema1 ); free( ema2 ); free( ratio ); + return -1; + } + + fp_t a1 = 2.0 / ( ( fp_t )ema_period + 1.0 ); + + for ( uint_t i = 0; i < n; ++i ) + { + hl[i] = ts_h( x, i ) - ts_l( x, i ); + } + + ema1[0] = hl[0]; + for ( uint_t i = 1; i < n; ++i ) + { + ema1[i] = ema1[i - 1] + a1 * ( hl[i] - ema1[i - 1] ); + } + + ema2[0] = ema1[0]; + for ( uint_t i = 1; i < n; ++i ) + { + ema2[i] = ema2[i - 1] + a1 * ( ema1[i] - ema2[i - 1] ); + } + + for ( uint_t i = 0; i < n; ++i ) + { + ratio[i] = ema2[i] != 0 ? ema1[i] / ema2[i] : 0; + } + + fp_t sum = 0; + for ( uint_t i = 0; i < sum_period; ++i ) + { + sum += ratio[i]; + } + + for ( uint_t j = 0; j < sum_period - 1; ++j ) y[0][j] = 0; + y[0][sum_period - 1] = sum; + + for ( uint_t i = sum_period; i < n; ++i ) + { + sum = sum - ratio[i - sum_period] + ratio[i]; + y[0][i] = sum; + } + + free( hl ); free( ema1 ); free( ema2 ); free( ratio ); + return 0; +} + -- cgit v1.3.1