summaryrefslogtreecommitdiffstats
path: root/lib/atr.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.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.c')
-rw-r--r--lib/atr.c73
1 files changed, 73 insertions, 0 deletions
diff --git a/lib/atr.c b/lib/atr.c
new file mode 100644
index 0000000..7c9f06f
--- /dev/null
+++ b/lib/atr.c
@@ -0,0 +1,73 @@
+// Average True Range
+//
+// atr - ATR
+//
+// Welles Wilder's Average True Range. True Range is the maximum of:
+// (1) High - Low
+// (2) |High - Previous Close|
+// (3) |Low - Previous Close|
+// The first ATR is the SMA of the first k TR values; subsequent values
+// use Wilder's smoothing: ATR = (prev_ATR * (k-1) + TR) / k
+//
+// Inputs: 4 (OHLC)
+// Outputs: 1 (ATR)
+// Constants: 1 (period)
+
+#include <math.h>
+#include "ts.h"
+
+typedef struct {
+ uint_t k;
+} ts_atr_params_t;
+
+ts_parameter_t const ts_atr_p = { .n_inputs = 4, .n_outputs = 1, .n_constants = 1, .params_size = sizeof(ts_atr_params_t) };
+
+
+uint_t ts_atr_offset( ts_constant_t const *c )
+{
+ ( void )c;
+ return ( c ? ((ts_atr_params_t *)c)->k : 0 );
+}
+
+int ts_atr(
+ 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_p );
+ if ( !c ) return -1;
+ TS_CHECK_INPUT(x, x_n, n);
+ uint_t k = ((ts_atr_params_t *)c)->k;
+ if (k == 0) return -1;
+ if (n < 2) return -1;
+
+ fp_t tr_sum = 0;
+
+ /* Cumulative SMA for first k TR values */
+ for( uint_t i = 1; i < k && 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 ) ) ) );
+ tr_sum += tr;
+ y[0][i] = tr_sum / (fp_t)i;
+ }
+
+ /* At bar k, use SMA of first k TR values */
+ if( k < n )
+ {
+ fp_t tr = fmax( ts_h( x, k ) - ts_l( x, k ), fmax( fabs( ts_h( x, k ) - ts_c( x, k - 1 ) ), fabs( ts_l( x, k ) - ts_c( x, k - 1 ) ) ) );
+ tr_sum += tr;
+ y[0][k] = tr_sum / (fp_t)k;
+ }
+
+ /* Wilder's smoothing from bar k+1 */
+ for( uint_t i = k + 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 ) ) ) );
+ y[0][i] = ( y[0][i - 1] * ( k - 1 ) + tr ) / k;
+ }
+ return 0;
+}
+
+
+