tulip_rs 0.1.15

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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
use crate::common::{validate_inputs};
pub use crate::indicator_types::TIndicatorState;
use crate::indicators::{
    sma::calc as sma_calc,
    stddev::{
        calc as stddev_calc, multiplier as stddev_multiplier,
        output_length as stddev_output_length, State as StddevState,
    },
};
use crate::types::{
    DisplayGroup, DisplayType, IndicatorError, 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 = 3;

/// 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::vidya_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::vidya_simd::indicator_by_options;

// Sub-module exports with common naming
/// 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.
    pub use crate::indicators::simd_indicators::vidya_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.
    pub use crate::indicators::simd_indicators::vidya_simd::indicator_by_options as indicator;
}

#[derive(Serialize, Deserialize)]
pub struct IndicatorState {
    state: State,
    real: Vec<f64>,
    periods: (usize, usize),
    multipliers: (f64, f64),
    alpha: f64,
}
impl IndicatorState {
    pub fn new(
        real: &[f64],
        state: State,
        periods: (usize, usize),
        multipliers: (f64, f64),
        alpha: f64,
    ) -> Self {
        Self {
            real: real[real.len() - periods.1..].to_vec(),
            state,
            periods,
            multipliers,
            alpha,
        }
    }
}

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 vidya_line,
            mut short_sma_line,
            mut long_sma_line,
            mut short_sd_line,
            mut long_sd_line,
        );
        {
            let capacity = inputs[0].len();
            vidya_line = crate::uninit_vec!(f64, capacity);

            (short_sma_line, long_sma_line, short_sd_line, long_sd_line) = crate::init_optional_outputs_eff!(
                optional_outputs, &[false, false, false, false],
                short_sma_line: capacity,
                long_sma_line: capacity,
                short_sd_line: capacity,
                long_sd_line: capacity
            );
        }
        cycle(
            &self.real,
            self.periods,
            self.multipliers,
            self.alpha,
            &mut self.state,
            &mut vidya_line,
            (
                &mut short_sma_line,
                &mut long_sma_line,
                &mut short_sd_line,
                &mut long_sd_line,
            ),
        );

        self.real.drain(..self.real.len() - self.periods.1);

        Ok(vec![
            vidya_line,
            short_sma_line,
            long_sma_line,
            short_sd_line,
            long_sd_line,
        ])
    }
}
#[derive(Serialize, Deserialize)]
pub struct State {
    pub short_state: StddevState,
    pub long_state: StddevState,
    pub prev_vidya: f64,
}
impl State {
    pub fn new(short_state: (f64, f64), long_state: (f64, f64), prev_vidya: f64) -> Self {
        Self {
            short_state: StddevState::new(short_state.0, short_state.1),
            long_state: StddevState::new(long_state.0, long_state.1),
            prev_vidya,
        }
    }

    pub fn init_state(
        short_period: usize,
        long_period: usize,
        real: &[f64],
        alpha: f64,
        vidya_line: &mut [f64],
        out_vecs: (&mut [f64], &mut [f64], &mut [f64], &mut [f64]),
    ) -> Self {
        let mut sum_short: f64 = 0.0;
        let mut sum_sq_short: f64 = 0.0;
        let mut sum_long: f64 = 0.0;
        let mut sum_sq_long: f64 = 0.0;
        let (short_sma_line, long_sma_line, short_sd_line, long_sd_line) = out_vecs;
        let (short_multiplier, long_multiplier) = multiplier(short_period, long_period);
        for (i, &value) in real.iter().enumerate().take(long_period) {
            sum_long += value;
            sum_sq_long += value * value;
            if i >= short_period {
                let prev_value = real[i - short_period];
                let short_sma = sma_calc(&mut sum_short, &value, &prev_value, &short_multiplier);
                sum_sq_short += (value * value) - (prev_value * prev_value);
                let short_stddev = (sum_sq_short * short_multiplier
                    - short_sma * (sum_short * short_multiplier))
                    .sqrt();
                crate::init_store_optional_outputs!(i, real.len(),
                    short_sma_line => short_sma,
                    short_sd_line => short_stddev
                );
            } else {
                sum_short += value;
                sum_sq_short += value * value;
            }
        }
        let short_sma = sum_short * short_multiplier;
        let short_stddev =
            (sum_sq_short * short_multiplier - short_sma * (sum_short * short_multiplier)).sqrt();
        let long_sma = sum_long * long_multiplier;
        let long_stddev =
            (sum_sq_long * long_multiplier - long_sma * (sum_long * long_multiplier)).sqrt();
        let mut k = if long_stddev.abs() < f64::EPSILON {
            0.0
        } else {
            short_stddev / long_stddev
        };
        if k.is_nan() {
            k = 0.0;
        }
        k *= alpha;
        let vidya = (real[long_period - 1] - real[long_period - 2]) * k + real[long_period - 2];
        vidya_line[0] = vidya;

        crate::init_store_optional_outputs!(long_period-1, real.len(),
            /*short_sma_line => short_sma,
            short_sd_line => short_stddev,*/
            long_sma_line => long_sma,
            long_sd_line => long_stddev
        );
        Self::new((sum_short, sum_sq_short), (sum_long, sum_sq_long), vidya)
    }
    #[inline(always)]
    pub fn calc(
        &mut self,
        value: &f64,
        prev_values: (&f64, &f64),
        alpha: f64,
        multipliers: (f64, f64),
    ) -> (f64, f64, f64, f64, f64) {
        // Compute short-term STDDEV.
        let (multiplier_short, multiplier_long) = multipliers;
        let (prev_short, prev_long) = prev_values;

        let (sd_short, sma_short) = self.short_state.calc(value, &prev_short, multiplier_short);

        // Compute long-term STDDEV.
        let (sd_long, sma_long) = self.long_state.calc(value, &prev_long, multiplier_long);

        let mut k = sd_short / sd_long;
        k *= alpha;

        self.prev_vidya = (value - self.prev_vidya) * k + self.prev_vidya;
        (self.prev_vidya, sma_short, sma_long, sd_short, sd_long)
    }
}
pub const INFO: Info = Info {
    name: "vidya",
    full_name: "Variable Index Dynamic Average",
    indicator_type: IndicatorType::Trend,
    inputs: &["real"],
    // Three options: short_period, long_period, alpha.
    options: &["short_period", "long_period", "alpha"],
    outputs: &["vidya"],
    // Optional outputs: sma_fast and sma_slow are taken from the STDDEV calc.
    optional_outputs: &["short_sma", "long_sma", "short_stddev", "long_stddev"],
    display_groups: &[
        DisplayGroup {
            offset: None,
            id: "vidya",
            label: "VIDYA",
            display_type: DisplayType::Overlay,
            outputs: &["vidya"],
        },
        DisplayGroup {
            offset: None,
            id: "short_sma_long_sma",
            label: "SMAs",
            display_type: DisplayType::Overlay,
            outputs: &["short_sma", "long_sma"],
        },
        DisplayGroup {
            offset: None,
            id: "short_stddev_long_stddev",
            label: "Standard Deviation",
            display_type: DisplayType::Indicator,
            outputs: &["short_stddev", "long_stddev"],
        },
    ],
};
/// Returns the minimum amount of data required for the VIDYA indicator.
///
/// # Arguments
///
/// * `options` - A slice containing the options: `[short_period, long_period, alpha]`.
///
/// # Returns
///
/// The minimum amount of data required (equal to the long period).
pub fn min_data(options: &[f64]) -> usize {
    options[1] as usize
}

/// Calculates the output length based on the data length and options.
///
/// # Arguments
///
/// * `data_len` - The length of the input data.
/// * `options` - A slice containing the options for the VIDYA calculation.
///
/// # Returns
///
/// The output length.
pub fn output_length(data_len: usize, options: &[f64]) -> usize {
    data_len - min_data(options) + 1
}
pub(crate) fn validate_options(options: &[f64; OPTIONS_WIDTH]) -> Result<(), IndicatorError> {
    if options[2] <= 0.0 || options[2] >= 1.0 || options[0] < 1.0 || options[1] <= options[0] {
        return Err(IndicatorError::InvalidOptions);
    }
    Ok(())
}
/// Calculates the Variable Index Dynamic Average (VIDYA) indicator over the full input dataset.
///
/// # Inputs
///
/// * `inputs[0]` — `real` (price series)
///
/// # Options
///
/// * `options[0]` — `short_period`
/// * `options[1]` — `long_period`
/// * `options[2]` — `alpha` (smoothing constant; must be in `(0.0, 1.0)`)
///
/// # Arguments
///
/// * `inputs` - Array of input price slices (see Inputs above).
/// * `options` - Array of indicator options (see Options above).
/// * `optional_outputs` - Pass `Some(&[true, …])` to enable optional outputs
///   `[short_sma, long_sma, short_stddev, long_stddev]`; `None` disables all.
///
/// # Returns
///
/// `Ok((outputs, state))` where `outputs[0]` is `vidya` 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 short_period = options[0] as usize;
    let long_period = options[1] as usize;
    let alpha = options[2];
    let multipliers = multiplier(short_period, long_period);

    validate_inputs(inputs, min_data(options))?;

    let real = inputs[0];

    let (
        mut vidya_line,
        mut short_sma_line,
        mut long_sma_line,
        mut short_sd_line,
        mut long_sd_line,
        mut state,
        outputs,
    );
    {
        let capacity = output_length(real.len(), options);
        let long_capacity = stddev_output_length(real.len(), &[long_period as f64]);
        let short_capacity = stddev_output_length(real.len(), &[short_period as f64]);

        vidya_line = crate::uninit_vec!(f64, capacity);
        (short_sma_line, long_sma_line, short_sd_line, long_sd_line) = crate::init_optional_outputs_eff!(
            optional_outputs, &[false, false, false, false],
            short_sma_line: short_capacity,
            long_sma_line: long_capacity,
            short_sd_line: short_capacity,
            long_sd_line: long_capacity
        );

        // Start processing at the max period for a full window.
        state = State::init_state(
            short_period,
            long_period,
            real,
            alpha,
            &mut vidya_line,
            (
                &mut short_sma_line,
                &mut long_sma_line,
                &mut short_sd_line,
                &mut long_sd_line,
            ),
        );
        let start = crate::slice_outputs_start!(
            capacity - 1,
            short_sma_line,
            long_sma_line,
            short_sd_line,
            long_sd_line
        ); //capacity - 1 because vidya_line recieve 1 output bar in init_state
        outputs = (
            &mut short_sma_line[start.0..],
            &mut long_sma_line[start.1..],
            &mut short_sd_line[start.2..],
            &mut long_sd_line[start.3..],
        )
    }

    cycle(
        real,
        (short_period, long_period),
        multipliers,
        alpha,
        &mut state,
        &mut vidya_line[1..],
        outputs,
    );

    Ok((
        vec![
            vidya_line,
            short_sma_line,
            long_sma_line,
            short_sd_line,
            long_sd_line,
        ],
        IndicatorState::new(real, state, (short_period, long_period), multipliers, alpha),
    ))
}

/// Iterates over the real data slice and computes VIDYA values for each bar.
///
/// # Arguments
///
/// * `real` - The full input data slice.
/// * `periods` - A tuple of `(short_period, long_period)`.
/// * `multipliers` - A tuple of `(short_multiplier, long_multiplier)` from `multiplier()`.
/// * `alpha` - The smoothing constant.
/// * `state` - Mutable reference to the rolling calculation state.
/// * `vidya_line` - Mutable output slice for VIDYA values.
/// * `out_vecs` - Mutable output slices for optional outputs:
///   `(short_sma, long_sma, short_sd, long_sd)`.
fn cycle(
    real: &[f64],
    periods: (usize, usize),
    multipliers: (f64, f64),
    alpha: f64,
    state: &mut State,
    vidya_line: &mut [f64],
    out_vecs: (&mut [f64], &mut [f64], &mut [f64], &mut [f64]),
) {
    let (short_period, long_period) = periods;
    let (short_sma_line, long_sma_line, short_sd_line, long_sd_line) = out_vecs;
    let (has_optional, want_short_sma, want_long_sma, want_short_sd, want_long_sd) =
        crate::calc_want_flags!(short_sma_line, long_sma_line, short_sd_line, long_sd_line);

    for (j, i) in (long_period..real.len()).enumerate() {
        let (value, prev_values) = unsafe {
            (
                real.get_unchecked(i),
                (real.get_unchecked(i - short_period), real.get_unchecked(j)),
            )
        };
        let (vidya, sma_short, sma_long, sd_short, sd_long) =
            calc(state, value, prev_values, alpha, multipliers);
        unsafe { *vidya_line.get_unchecked_mut(j) = vidya };

        if has_optional {
            crate::store_optional_outputs!(j,
                want_long_sma, long_sma_line => sma_long,
                want_long_sd, long_sd_line => sd_long,
                want_short_sma, short_sma_line => sma_short,
                want_short_sd, short_sd_line => sd_short
            );
        }
    }
}

/// Calculates a single bar of VIDYA, updating the rolling state in place.
///
/// # Arguments
///
/// * `state` - Mutable reference to the rolling `State` (short and long stddev states,
///   previous VIDYA value).
/// * `value` - The current input value.
/// * `prev_values` - A tuple of previous values: `(prev_short, prev_long)`.
/// * `alpha` - The smoothing constant.
/// * `multipliers` - A tuple of `(short_multiplier, long_multiplier)` from `multiplier()`.
///
/// # Returns
///
/// A tuple of `(vidya, sma_short, sma_long, sd_short, sd_long)`.
#[inline(always)]
pub fn calc(
    state: &mut State,
    value: &f64,
    prev_values: (&f64, &f64),
    alpha: f64,
    multipliers: (f64, f64),
) -> (f64, f64, f64, f64, f64) {
    // Compute short-term STDDEV.
    let (multiplier_short, multiplier_long) = multipliers;
    let (prev_short, prev_long) = prev_values;

    let (sd_short, sma_short) =
        stddev_calc(&mut state.short_state, value, &prev_short, multiplier_short);

    // Compute long-term STDDEV.
    let (sd_long, sma_long) =
        stddev_calc(&mut state.long_state, value, &prev_long, multiplier_long);

    let mut k = sd_short / sd_long;
    k *= alpha;

    //state.prev_vidya = (value - state.prev_vidya) * k + state.prev_vidya;
    state.prev_vidya = (value - state.prev_vidya).mul_add(k, state.prev_vidya);
    (state.prev_vidya, sma_short, sma_long, sd_short, sd_long)
}
#[inline(always)]
pub fn multiplier(short_period: usize, long_period: usize) -> (f64, f64) {
    (
        stddev_multiplier(short_period),
        stddev_multiplier(long_period),
    )
}