// Hull Ma // // hull_ma // // Hull Moving Average // // HMA = WMA(2*WMA(n/2) - WMA(n), √n) // // Inputs: 1 // Outputs: 1 // Constants: 1 #include #include #include "ts.h" typedef struct { uint_t k; } ts_hull_ma_params_t; ts_parameter_t const ts_hull_ma_p = { .n_inputs = 1, .n_outputs = 1, .n_constants = 1, .params_size = sizeof(ts_hull_ma_params_t) }; uint_t ts_hull_ma_offset( ts_constant_t const *c ) { ( void )c; return ( c ? ((ts_hull_ma_params_t *)c)->k + (uint_t)sqrt((fp_t)((ts_hull_ma_params_t *)c)->k) - 2 : 0 ); } int ts_hull_ma( 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_hull_ma_p ); if ( !c ) return -1; TS_CHECK_INPUT(x, x_n, n); uint_t k = ((ts_hull_ma_params_t *)c)->k; if (k < 2) return -1; uint_t half_k = k / 2; uint_t sqrt_k = (uint_t)sqrt((fp_t)k); if (sqrt_k < 1) sqrt_k = 1; fp_t *wma_half = calloc( n, sizeof( fp_t ) ); fp_t *wma_full = calloc( n, sizeof( fp_t ) ); if ( !wma_half || !wma_full ) { free( wma_half ); free( wma_full ); return -1; } /* WMA(n/2) */ fp_t wt_half = (fp_t)half_k * ((fp_t)half_k + 1.0) / 2.0; for ( uint_t i = half_k - 1; i < n; ++i ) { fp_t s = 0; for ( uint_t j = 0; j < half_k; ++j ) s += x[0][i - j] * (fp_t)(half_k - j); wma_half[i] = s / wt_half; } /* WMA(n) */ fp_t wt_full = (fp_t)k * ((fp_t)k + 1.0) / 2.0; for ( uint_t i = k - 1; i < n; ++i ) { fp_t s = 0; for ( uint_t j = 0; j < k; ++j ) s += x[0][i - j] * (fp_t)(k - j); wma_full[i] = s / wt_full; } /* HMA = WMA(sqrt(n), 2*WMA(n/2) - WMA(n)) */ fp_t wt_sqrt = (fp_t)sqrt_k * ((fp_t)sqrt_k + 1.0) / 2.0; uint_t offset = k + sqrt_k - 2; for (uint_t j = 0; j < n && j < offset; ++j) y[0][j] = NAN; for ( uint_t i = offset; i < n; ++i ) { fp_t s = 0; for ( uint_t j = 0; j < sqrt_k; ++j ) { fp_t diff = 2.0 * wma_half[i - j] - wma_full[i - j]; s += diff * (fp_t)(sqrt_k - j); } y[0][i] = s / wt_sqrt; } free( wma_half ); free( wma_full ); return 0; }