summaryrefslogtreecommitdiffstats
path: root/lib/cci.c
blob: 5345ac89ae7df49ccb184936e6ba82f0f2a225c3 (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
// Commodity Channel Index
//
// cci - CCI
//
// (TP - SMA(TP)) / (0.015 * MAD(TP)), where TP = (H+L+C)/3
//
// Inputs:    4 (OHLC)
// Outputs:   1 (CCI)
// Constants: 0

#include <math.h>
#include "ts.h"

typedef struct {
    uint_t k;
} ts_cci_params_t;

ts_parameter_t const ts_cci_p = { .n_inputs = 4, .n_outputs = 1, .n_constants = 1, .params_size = sizeof(ts_cci_params_t) };

uint_t ts_cci_offset( ts_constant_t const *c )
{
	( void )c;
	return ( c ? ((ts_cci_params_t const *)c)->k - 1 : 0 );
}

int ts_cci(
	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_cci_p );
	if ( !c ) return -1;
	TS_CHECK_INPUT(x, x_n, n);
	uint_t k = ((ts_cci_params_t const *)c)->k;
	if (k == 0 || n < k) return -1;

	// Compute initial typical prices
	fp_t tp_sum = 0;
	for( uint_t j = 0; j < k; ++j )
	{
		tp_sum += ( ts_h( x, j ) + ts_l( x, j ) + ts_c( x, j ) ) / 3.0;
	}
	fp_t tp_sma = tp_sum / (fp_t)k;

	// Compute initial MAD
	fp_t mad_sum = 0;
	for( uint_t j = 0; j < k; ++j )
	{
		fp_t tp = ( ts_h( x, j ) + ts_l( x, j ) + ts_c( x, j ) ) / 3.0;
		mad_sum += fabs( tp - tp_sma );
	}
	fp_t mad = mad_sum / (fp_t)k;

	{
		fp_t tp = ( ts_h( x, k - 1 ) + ts_l( x, k - 1 ) + ts_c( x, k - 1 ) ) / 3.0;
		if( mad == 0 )
			y[0][k - 1] = 0;
		else
			y[0][k - 1] = ( tp - tp_sma ) / ( 0.015 * mad );
	}

	// Sliding window: incremental tp_sum, but MAD needs recompute when tp_sma changes
	// MAD depends on tp_sma which changes each step, so we can't fully incremental MAD
	// However, we can still use incremental tp_sum
	for( uint_t i = k; i < n; ++i )
	{
		fp_t tp_new = ( ts_h( x, i ) + ts_l( x, i ) + ts_c( x, i ) ) / 3.0;
		fp_t tp_old = ( ts_h( x, i - k ) + ts_l( x, i - k ) + ts_c( x, i - k ) ) / 3.0;
		tp_sum = tp_sum + tp_new - tp_old;
		tp_sma = tp_sum / (fp_t)k;

		mad_sum = 0;
		for( uint_t j = 0; j < k; ++j )
		{
			fp_t tp = ( ts_h( x, i - k + 1 + j ) + ts_l( x, i - k + 1 + j ) + ts_c( x, i - k + 1 + j ) ) / 3.0;
			mad_sum += fabs( tp - tp_sma );
		}
		mad = mad_sum / (fp_t)k;

		if( mad == 0 )
			y[0][i] = 0;
		else
			y[0][i] = ( tp_new - tp_sma ) / ( 0.015 * mad );
	}

	return 0;
}