summaryrefslogtreecommitdiffstats
path: root/lib/hull_ma.c
blob: e412a6fe8ab3581f7cb562198e1b9338f8479b61 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Hull Ma
//
// hull_ma
//
// Hull Moving Average
//
// HMA = WMA(2*WMA(n/2) - WMA(n), √n)
//
// Inputs:    1
// Outputs:   1
// Constants: 1


#include <math.h>
#include <stdlib.h>
#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;
}