tulip_rs 0.1.13

High-performance technical analysis library — 100+ indicators and 60+ candlestick patterns with SIMD acceleration
Documentation
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use crate::common::{min_process, validate_inputs, validate_options};
pub use crate::indicator_types::TIndicatorState;
use crate::indicators::ef::calc as calc_ef;
use crate::indicators::ema::multiplier as ema_multiplier;
use crate::types::{
    DisplayGroup, DisplayType, IndicatorError, IndicatorInfoOrInteger, IndicatorType, Info,
};
use serde::{Deserialize, Serialize};

/// Number of input price series required by this indicator.
pub const INPUTS_WIDTH: usize = 1;

/// Number of option parameters required by this indicator.
pub const OPTIONS_WIDTH: usize = 1;

/// SIMD-parallel variant that processes `N` assets with identical options simultaneously.
/// Requires the `simd_assets` Cargo feature. See [`by_assets`] for the module form.
#[cfg(feature = "simd_assets")]
pub use crate::indicators::simd_indicators::kama_simd::indicator_by_assets;

/// SIMD-parallel variant that processes a single asset with `N` different option
/// sets simultaneously. Requires the `simd_options` Cargo feature. See [`by_options`].
#[cfg(feature = "simd_options")]
pub use crate::indicators::simd_indicators::kama_simd::indicator_by_options;

/// Convenience module that re-exports [`indicator_by_assets`] as `indicator`,
/// allowing SIMD multi-asset computation to be used as a drop-in replacement
/// for the standard single-asset [`indicator`] function.
/// Requires the `simd_assets` Cargo feature.
#[cfg(feature = "simd_assets")]
pub mod by_assets {
    /// Processes `N` assets in parallel with shared options.
    /// See the parent module's [`super::indicator_by_assets`] for full documentation.
    pub use crate::indicators::simd_indicators::kama_simd::indicator_by_assets as indicator;
}

/// Convenience module that re-exports [`indicator_by_options`] as `indicator`,
/// allowing SIMD multi-option computation to be used as a drop-in replacement
/// for the standard single-asset [`indicator`] function.
/// Requires the `simd_options` Cargo feature.
#[cfg(feature = "simd_options")]
pub mod by_options {
    /// Processes a single asset with `N` different option sets in parallel.
    /// See the parent module's [`super::indicator_by_options`] for full documentation.
    pub use crate::indicators::simd_indicators::kama_simd::indicator_by_options as indicator;
}
/// Returns information about the Kaufman's Adaptive Moving Average (KAMA) indicator.
///
/// # Returns
///
/// An `Info` struct containing metadata about the KAMA indicator.
pub const INFO: Info = Info {
    name: "kama",
    indicator_type: IndicatorType::Trend,
    full_name: "Kaufman's Adaptive Moving Average",
    inputs: &["real"],
    options: &["period"],
    outputs: &["kama"],
    optional_outputs: &["ef"],
    display_groups: &[
        DisplayGroup {
            id: "kama",
            label: "KAMA",
            display_type: DisplayType::Overlay,
            outputs: &["kama"],
        },
        DisplayGroup {
            id: "ef",
            label: "Efficiency Ratio",
            display_type: DisplayType::Indicator,
            outputs: &["ef"],
        },
    ],
};
#[derive(Serialize, Deserialize)]
pub struct IndicatorState {
    real: Vec<f64>,
    period: usize,
    multipliers: (f64, f64),
    state: State,
}
impl IndicatorState {
    pub fn new(real: &[f64], period: usize, multipliers: (f64, f64), state: State) -> Self {
        Self {
            period,
            multipliers,
            state,
            real: real[real.len() - period - 1..].to_vec(),
        }
    }
}
impl TIndicatorState<1> for IndicatorState {
    fn batch_indicator(
        &mut self,
        inputs: &[&[f64]; INPUTS_WIDTH],
        optional_outputs: Option<&[bool]>,
    ) -> Result<Vec<Vec<f64>>, IndicatorError> {
        validate_inputs(inputs, 1)?;
        self.real.extend_from_slice(inputs[0]);

        let (mut kama_line, mut ef_line) = {
            let capacity = inputs[0].len();
            (
                crate::uninit_vec!(f64, capacity),
                crate::init_optional_outputs!(
                    optional_outputs, &[false],
                    ef_line: capacity
                ),
            )
        };

        cycle_kama(
            &self.real,
            &mut self.state,
            self.period,
            self.multipliers,
            &mut kama_line,
            &mut ef_line,
        );
        self.real.drain(..self.real.len() - self.period - 1);

        Ok(vec![kama_line, ef_line])
    }
}

#[derive(Serialize, Deserialize)]
pub struct State {
    pub kama: f64,
    pub sum: f64,
}
impl State {
    pub fn new(kama: f64, sum: f64) -> Self {
        Self { kama, sum }
    }
    pub fn init_state(
        real: &[f64],
        period: usize,
        kama_line: &mut [f64],
        ef_line: &mut [f64],
    ) -> Self {
        let mut state = Self::new(
            real[period - 1],
            (1..period).map(|i| (real[i] - real[i - 1]).abs()).sum(),
        );
        let multipliers = multiplier();
        let values = unsafe {
            (
                real.get_unchecked(period),
                real.get_unchecked(period - 1),
                real.get_unchecked(0),
                &0.0,
            )
        };
        let (kama, efficiency_ratio) = state.calc(values, multipliers, period, period);
        kama_line[0] = kama;
        let (_, want_ef) = crate::calc_want_flags!(ef_line);
        crate::store_optional_outputs!(0,
            want_ef, ef_line => efficiency_ratio
        );

        state
    }
    /// Kaufman's Efficiency Ratio (ER) is defined as:
    ///
    /// ```text
    /// ER = |price[t] - price[t-n]| / sum(|Δprice[i]|)
    /// ```
    ///
    /// If the denominator (the sum of absolute price changes) is zero, the ER is
    /// defined as **0.0**.  This condition occurs when price has not moved at all
    /// over the lookback window, or when every up‑move is exactly cancelled by a
    /// down‑move.  In either case, the market exhibits **maximum noise and zero
    /// trend efficiency**, so ER = 0.0 is the correct interpretation.
    ///
    /// ER must **not** be forced to 1.0 in this case.  Doing so would imply a
    /// perfectly efficient trend despite *no net movement*, which in turn would
    /// cause KAMA to switch into its fastest smoothing regime—opposite of the
    /// intended behaviour. (yet another bug in c tulip! and many other indicator libraries)
    ///
    /// In this implementation, an ER of 0.0 is completely safe: the KAMA smoothing
    /// constant is computed as:
    ///
    /// ```text
    /// SC = (ER * (fast - slow) + slow).powi(2)
    /// ```
    ///
    /// Because `slow` is always greater than zero, the smoothing constant can never
    /// collapse to 0.0.  When ER = 0.0, KAMA simply falls back to its slowest
    /// possible smoothing, exactly as Kaufman designed.
    #[inline(always)]
    pub fn calc(
        &mut self,
        values: (&f64, &f64, &f64, &f64),
        multipliers: (f64, f64),
        period: usize,
        i: usize,
    ) -> (f64, f64) {
        let (fast_ema, slow_ema) = multipliers;
        let efficiency_ratio = calc_ef(&mut self.sum, values, period, i);
        let (value, _, _, _) = values;
        //let smoothing_constant = (efficiency_ratio * (fast_ema - slow_ema) + slow_ema).powi(2);
        let smoothing_constant = (fast_ema - slow_ema)
            .mul_add(efficiency_ratio, slow_ema)
            .powi(2);

        // Optimized calculation using C-style EMA pattern
        let per1 = 1.0 - smoothing_constant;
        //self.kama = self.kama * per1 + value * smoothing_constant;
        self.kama = self.kama.mul_add(per1, value * smoothing_constant);
        (self.kama, efficiency_ratio)
    }
}
/// Returns the minimum number of input bars required to produce results
/// accurate to `decimals` decimal places.
///
/// For indicators with exponential smoothing the seed value's influence
/// must decay below the requested precision, so this value grows with
/// `decimals`. Internally uses `min_process` with the smoothing
/// multiplier to calculate the required lookback.
///
/// # Arguments
///
/// * `options` - A slice containing the indicator options (e.g. period).
/// * `decimals` - The number of decimal places of accuracy required.
///
/// # Returns
///
/// The minimum number of input bars needed for the requested accuracy.
pub fn min_data_accuracy(options: &[f64], decimals: usize) -> usize {
    if options[0] > 12.0 {
        let (short_multiplier, long_multiplier) = multiplier();
        let alpha = short_multiplier - long_multiplier;
        return min_process(
            options,
            Some((decimals, 0)),
            &[ema_multiplier(options[0] as usize).0, alpha],
            IndicatorInfoOrInteger::Info(INFO),
            min_data,
        );
    }
    min_process(
        options,
        Some((decimals, 0)),
        &[ema_multiplier(options[0] as usize).0],
        IndicatorInfoOrInteger::Info(INFO),
        min_data,
    )
}
/// Returns the minimum amount of data required for the KAMA indicator.
///
/// # Arguments
///
/// * `options` - A slice containing the options for the KAMA calculation.
///
/// # Returns
///
/// The minimum amount of data required.
pub fn min_data(options: &[f64]) -> usize {
    options[0] as usize + 1
}

/// Returns the number of output values produced by the KAMA indicator given input data length and options.
///
/// # Arguments
///
/// * `data_len` - The length of the input data.
/// * `options` - A slice containing the options for the KAMA calculation.
///
/// # Returns
///
/// The number of output values.
pub fn output_length(data_len: usize, options: &[f64]) -> usize {
    data_len - min_data(options) + 1
}

/// Calculates the Kaufman's Adaptive Moving Average (KAMA) indicator for an entire dataset.
///
/// # Inputs
///
/// * `inputs[0]` — real (close) prices
///
/// # Options
///
/// * `options[0]` — period
///
/// # Outputs
///
/// * `outputs[0]` — `kama` line
///
/// # Arguments
///
/// * `inputs` - Array of input price slices (see Inputs above).
/// * `options` - Array of indicator options (see Options above).
/// * `_optional_outputs` - Unused; KAMA has no optional outputs.
///
/// # Returns
///
/// `Ok((outputs, state))` where `outputs[0]` is the `kama` line and
/// `state` can be passed to `IndicatorState::batch_indicator` for streaming.
/// Returns `Err(IndicatorError)` if inputs are too short or options are invalid.
pub fn indicator(
    inputs: &[&[f64]; INPUTS_WIDTH],
    options: &[f64; OPTIONS_WIDTH],
    optional_outputs: Option<&[bool]>,
) -> Result<(Vec<Vec<f64>>, IndicatorState), IndicatorError> {
    validate_options(options)?;
    let period = options[0] as usize;
    let multipliers = multiplier();

    validate_inputs(inputs, min_data(options))?;
    let real = inputs[0];

    let (mut kama_line, mut ef_line) = {
        let capacity = output_length(real.len(), options);
        (
            crate::uninit_vec!(f64, capacity),
            crate::init_optional_outputs!(
                optional_outputs, &[false],
                ef_line: capacity
            ),
        )
    };
    let mut state = State::init_state(real, period, &mut kama_line, &mut ef_line);
    let ef = {
        let (_, want_ef) = crate::calc_want_flags!(ef_line);

        if want_ef {
            &mut ef_line[1..]
        } else {
            &mut ef_line
        }
    };
    // Perform the main KAMA calculation
    cycle_kama(
        real,
        &mut state,
        period,
        multipliers,
        &mut kama_line[1..],
        ef,
    );

    Ok((
        vec![kama_line, ef_line],
        IndicatorState::new(real, period, multipliers, state),
    ))
}

/// Performs the main calculation loop for the KAMA indicator.
///
/// # Arguments
///
/// * `real` - A slice of input data.
/// * `state` - A mutable reference to the indicator state.
/// * `period` - The period for the KAMA calculation.
/// * `multipliers` - A tuple of `(fast_ema, slow_ema)` smoothing constants.
/// * `kama_line` - A mutable slice for storing the KAMA output values.
fn cycle_kama(
    real: &[f64],
    state: &mut State,
    period: usize,
    multipliers: (f64, f64),
    kama_line: &mut [f64],
    ef_line: &mut [f64],
) {
    let (_, want_ef) = crate::calc_want_flags!(ef_line);
    for (j, i) in (period + 1..real.len()).enumerate() {
        let values = unsafe {
            (
                real.get_unchecked(i),
                real.get_unchecked(i - 1),
                real.get_unchecked(j + 1),
                real.get_unchecked(j),
            )
        };
        let (kama, efficiency_ratio) = state.calc(values, multipliers, period, i);

        unsafe { *kama_line.get_unchecked_mut(j) = kama };

        crate::store_optional_outputs!(j,
            want_ef, ef_line => efficiency_ratio
        );
    }
}

/// Calculates the KAMA value for a single bar.
///
/// # Arguments
///
/// * `state` - A mutable reference to the indicator state.
/// * `values` - A tuple of price references: `(value, prev_value, last_value, old_value)`.
/// * `multipliers` - A tuple of `(fast_ema, slow_ema)` smoothing constants.
/// * `period` - The period for the KAMA calculation.
/// * `i` - The current index in the full data slice (used to gate the rolling-sum subtraction).
///
/// # Returns
///
/// The calculated KAMA value.
#[inline(always)]
pub fn calc(
    state: &mut State,
    values: (&f64, &f64, &f64, &f64),
    multipliers: (f64, f64),
    period: usize,
    i: usize,
) -> (f64, f64) {
    state.calc(values, multipliers, period, i)
}

#[inline(always)]
pub fn multiplier() -> (f64, f64) {
    (ema_multiplier(2).0, ema_multiplier(30).0)
}