summaryrefslogtreecommitdiffstats
path: root/lib/atr_bands.c
diff options
context:
space:
mode:
authorEthan Werner <mail@ethanwerner.com>2026-07-01 09:42:39 +0400
committerEthan Werner <mail@ethanwerner.com>2026-07-01 09:42:39 +0400
commit07e18043145f3d91c8ea7ec3ad41b3c905585277 (patch)
tree2bdeae46973f4bdfce263679a4008ac768011f28 /lib/atr_bands.c
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
Diffstat (limited to 'lib/atr_bands.c')
-rw-r--r--lib/atr_bands.c87
1 files changed, 87 insertions, 0 deletions
diff --git a/lib/atr_bands.c b/lib/atr_bands.c
new file mode 100644
index 0000000..73b7d44
--- /dev/null
+++ b/lib/atr_bands.c
@@ -0,0 +1,87 @@
+// ATR Bands
+//
+// atr_bands - ATR bands
+//
+// Upper: SMA(Close) + mult * ATR
+// Middle: SMA(Close)
+// Lower: SMA(Close) - mult * ATR
+//
+// Inputs: 4 (OHLC)
+// Outputs: 3 (Upper, Middle, Lower)
+// Constants: 2 (period, multiplier)
+
+#include <math.h>
+#include "ts.h"
+
+
+typedef struct {
+ uint_t k;
+ fp_t mult;
+} ts_atr_bands_params_t;
+
+ts_parameter_t const ts_atr_bands_p = { .n_inputs = 4, .n_outputs = 3, .n_constants = 2, .params_size = sizeof(ts_atr_bands_params_t) };
+
+
+uint_t ts_atr_bands_offset( ts_constant_t const *c )
+{
+ ( void )c;
+ return ( c ? ((ts_atr_bands_params_t *)c)->k : 0 );
+}
+
+int ts_atr_bands(
+ 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_atr_bands_p );
+ if ( !c ) return -1;
+ uint_t k = ((ts_atr_bands_params_t *)c)->k;
+ if (k == 0 || n < k) return -1;
+ if (n < 2) return -1;
+
+ fp_t mult = ((ts_atr_bands_params_t *)c)->mult;
+
+ fp_t tr_sum = 0;
+ fp_t atr = 0;
+
+ // Accumulate ATR from i=1, but only write output from i=k-1 (when SMA window is valid)
+ for( uint_t i = 1; i < n; ++i )
+ {
+ fp_t tr = fmax( ts_h( x, i ) - ts_l( x, i ), fmax( fabs( ts_h( x, i ) - ts_c( x, i - 1 ) ), fabs( ts_l( x, i ) - ts_c( x, i - 1 ) ) ) );
+
+ if( i < k )
+ {
+ tr_sum += tr;
+ atr = tr_sum / (fp_t)i;
+ }
+ else if( i == k )
+ {
+ tr_sum += tr;
+ atr = tr_sum / (fp_t)k;
+ }
+ else
+ {
+ atr = ( atr * ( k - 1 ) + tr ) / k;
+ }
+
+ // Only write output when SMA window is fully within bounds (i >= k-1)
+ if( i >= k - 1 )
+ {
+ fp_t sum = 0;
+ for( uint_t j = 0; j < k; ++j )
+ {
+ sum += ts_c( x, i - k + 1 + j );
+ }
+ fp_t mean = sum / k;
+
+ y[0][i] = mean + mult * atr;
+ y[1][i] = mean;
+ y[2][i] = mean - mult * atr;
+ }
+ }
+ return 0;
+}
+
+
+