summaryrefslogtreecommitdiffstats
path: root/lib/historical_volatility.c
blob: 5848d1ce9598f1c27f4bfdd6202baccdfd23ee67 (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
// Historical Volatility
//
// historical_volatility
//
// Historical volatility of log returns
//
// stddev(log(C[t]/C[t-1])) over period
//
// Inputs:    1
// Outputs:   1
// Constants: 1


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

typedef struct {
    uint_t k;
} ts_historical_volatility_params_t;

ts_parameter_t const ts_historical_volatility_p = { .n_inputs = 1, .n_outputs = 1, .n_constants = 1, .params_size = sizeof(ts_historical_volatility_params_t) };

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

int ts_historical_volatility(
	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_historical_volatility_p );
	if ( !c ) return -1;
    uint_t k = ((ts_historical_volatility_params_t const *)c)->k;
    if (k == 0 || n < k + 1) return -1;

    for ( uint_t d = k - 1; d < n - 1; ++d )
    {
        fp_t sum = 0;
        fp_t sum2 = 0;
        for ( uint_t j = d - k + 1; j <= d; ++j )
        {
            fp_t lr = 0;
            if ( x[0][j] > 0 && x[0][j + 1] > 0 )
                lr = log( x[0][j + 1] / x[0][j] );
            sum += lr;
            sum2 += lr * lr;
        }
        fp_t mean = sum / ( fp_t )k;
        fp_t variance = sum2 / ( fp_t )k - mean * mean;
        y[0][d] = variance > 0 ? sqrt( variance ) * sqrt( 252.0 ) : 0;
    }

    y[0][n - 1] = 0;
	return 0;
}