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
use crate::common::{validate_inputs, validate_options};
//use crate::indicators::aroon::State;
pub use crate::indicator_types::TIndicatorState;
use crate::indicators::max::{
    calc as calc_max, calc_unchecked as calc_max_uncheked, output_length as max_output_length,
    State as MaxState,
};
use crate::indicators::min::{
    calc as calc_min, calc_unchecked as calc_min_uncheked, State as MinState,
};
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 = 3;
/// 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::willr_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::willr_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::willr_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::willr_simd::indicator_by_options as indicator;
}

#[derive(Serialize, Deserialize)]
pub struct IndicatorState {
    state: State,
    high: Vec<f64>,
    low: Vec<f64>,
    period: usize,
}
impl IndicatorState {
    pub fn new(state: State, high: &[f64], low: &[f64], period: usize) -> Self {
        Self {
            state,
            high: high[high.len() - period..].to_vec(),
            low: low[low.len() - period..].to_vec(),
            period,
        }
    }
}
impl TIndicatorState<3> for IndicatorState {
    fn batch_indicator(
        &mut self,
        inputs: &[&[f64]; INPUTS_WIDTH],
        optional_outputs: Option<&[bool]>,
    ) -> Result<Vec<Vec<f64>>, IndicatorError> {
        validate_inputs(inputs, 1)?;
        // Merge stored tails with new inputs.
        let [high, low, close] = *inputs;
        self.high.extend_from_slice(high);
        self.low.extend_from_slice(low);

        let (mut willr_line, (mut min_line, mut max_line)) = {
            let len = high.len();
            (
                crate::uninit_vec!(f64, len),
                crate::init_optional_outputs_eff!(
                    optional_outputs, &[false, false],
                    min_line: len,
                    max_line: len
                ),
            )
        };
        match self.period {
            1..=13 => {
                cycle_willr::<1>(
                    &self.high,
                    &self.low,
                    close,
                    self.period,
                    &mut self.state,
                    &mut willr_line,
                    (&mut min_line, &mut max_line),
                );
            }
            14..30 => {
                cycle_willr::<4>(
                    &self.high,
                    &self.low,
                    close,
                    self.period,
                    &mut self.state,
                    &mut willr_line,
                    (&mut min_line, &mut max_line),
                );
            }
            _ => {
                cycle_willr::<8>(
                    &self.high,
                    &self.low,
                    close,
                    self.period,
                    &mut self.state,
                    &mut willr_line,
                    (&mut min_line, &mut max_line),
                );
            }
        }

        self.high.drain(..self.high.len() - self.period);
        self.low.drain(..self.low.len() - self.period);

        Ok(vec![willr_line, min_line, max_line])
    }
}
#[derive(Serialize, Deserialize)]
pub struct State {
    pub min_state: MinState,
    pub max_state: MaxState,
}
impl State {
    pub fn new(min_state: (f64, usize), max_state: (f64, usize)) -> Self {
        State {
            min_state: MinState::new(min_state.0, min_state.1),
            max_state: MaxState::new(max_state.0, max_state.1),
        }
    }
    pub fn init_state(
        high: &[f64],
        low: &[f64],
        period: usize,
        min_max: (&mut [f64], &mut [f64]),
    ) -> Self {
        let (min_line, max_line) = min_max;
        let min_state = MinState::init_state(low, period, period - 1, min_line);
        let max_state = MaxState::init_state(high, period, period - 1, max_line);

        Self {
            min_state,
            max_state,
        }
    }
}
pub const INFO: Info = Info {
    name: "willr",
    full_name: "Williams %R",
    indicator_type: IndicatorType::Momentum,
    // Three inputs: high, low, close.
    inputs: &["high", "low", "close"],
    // One option: period.
    options: &["period"],
    outputs: &["willr"],
    optional_outputs: &["min", "max"],
    display_groups: &[
        DisplayGroup {
            offset: None,
            id: "willr",
            label: "WILLR",
            display_type: DisplayType::Indicator,
            outputs: &["willr"],
        },
        DisplayGroup {
            offset: None,
            id: "min_max",
            label: "Min & Max",
            display_type: DisplayType::Overlay,
            outputs: &["min", "max"],
        },
    ],
};
/// Returns the minimum amount of data required for the Williams %R indicator.
///
/// # Arguments
///
/// * `options` - A slice containing the options: `[period]`.
///
/// # Returns
///
/// The minimum amount of data required (period + 1).
pub fn min_data(options: &[f64]) -> usize {
    options[0] as usize + 1
}

/// 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 Williams %R calculation.
///
/// # Returns
///
/// The output length.
pub fn output_length(data_len: usize, options: &[f64]) -> usize {
    data_len - min_data(options) + 1
}

/// Calculates the Williams %R indicator over the full input dataset.
///
/// # Inputs
///
/// * `inputs[0]` — `high`
/// * `inputs[1]` — `low`
/// * `inputs[2]` — `close`
///
/// # Options
///
/// * `options[0]` — `period`
///
/// # Arguments
///
/// * `inputs` - Array of input price slices (see Inputs above).
/// * `options` - Array of indicator options (see Options above).
/// * `_optional_outputs` - Unused; this indicator has no optional outputs.
///
/// # Returns
///
/// `Ok((outputs, state))` where `outputs[0]` is `willr` 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;

    validate_inputs(inputs, min_data(options))?;
    let high = inputs[0];
    let low = inputs[1];
    let close = inputs[2];

    let (mut willr_line, (mut min_line, mut max_line)) = {
        let len = high.len();
        let capacity = output_length(len, options);
        let min_max_capacity = max_output_length(len, options);
        (
            crate::uninit_vec!(f64, capacity),
            crate::init_optional_outputs_eff!(
                optional_outputs, &[false, false],
                min_line: min_max_capacity,
                max_line: min_max_capacity
            ),
        )
    };

    let mut state = State::init_state(high, low, period, (&mut min_line, &mut max_line));
    let optional_outputs = {
        let (min_offset, max_offset) =
            crate::slice_outputs_start!(willr_line.len(), min_line, max_line);
        (&mut min_line[min_offset..], &mut max_line[max_offset..])
    };
    // The first valid calculation is at index period - 1 within the slice.
    match period {
        1..=13 => {
            cycle_willr::<1>(
                high,
                low,
                &close[period..],
                period,
                &mut state,
                &mut willr_line,
                optional_outputs,
            );
        }
        14..25 => {
            cycle_willr::<4>(
                high,
                low,
                &close[period..],
                period,
                &mut state,
                &mut willr_line,
                optional_outputs,
            );
        }
        _ => {
            cycle_willr::<8>(
                high,
                low,
                &close[period..],
                period,
                &mut state,
                &mut willr_line,
                optional_outputs,
            );
        }
    }

    Ok((
        vec![willr_line, min_line, max_line],
        IndicatorState::new(state, high, low, period),
    ))
}

/// Iterates over the high, low, and close slices and computes Williams %R values.
///
/// # Arguments
///
/// * `high` - The full high price input slice.
/// * `low` - The full low price input slice.
/// * `close` - The close price slice to iterate over (already offset by `period`).
/// * `period` - The lookback period.
/// * `state` - Mutable reference to the rolling `State` (min and max states).
/// * `willr_line` - Mutable output slice for Williams %R values.
fn cycle_willr<const N: usize>(
    high: &[f64],
    low: &[f64],
    close: &[f64],
    period: usize,
    state: &mut State,
    willr_line: &mut [f64],
    optional_outputs: (&mut [f64], &mut [f64]),
) {
    let (min_line, max_line) = optional_outputs;
    let (has_optional, want_min, want_max) = crate::calc_want_flags!(min_line, max_line);

    let periods = (period, period - 1);
    let mut i = period;
    for (j, (close, willr)) in close.iter().zip(willr_line.iter_mut()).enumerate() {
        let (min, max);
        unsafe {
            (*willr, min, max) = calc_unchecked::<N>(state, high, low, close, i, periods);
        }

        if has_optional {
            crate::store_optional_outputs!(j,
                want_min, min_line => min,
                want_max, max_line => max
            );
        }

        i += 1;
    }
}

/// Calculates WillR for a single bar using the sliding window state.
/// It mimics stoch’s calc_kfast but uses the WillR formula:
/// willr = -100 * (max - close[i]) / (max - min)
#[inline(always)]
pub fn calc(
    state: &mut State,
    high: &[f64],
    low: &[f64],
    close: &f64,
    i: usize,
    periods: (usize, usize),
) -> (f64, f64, f64) {
    // Update the minimum and maximum for the rolling window.
    let (min, _) = calc_min(&mut state.min_state, low, i, periods);
    let (max, _) = calc_max(&mut state.max_state, high, i, periods);

    if (max - min).abs() < f64::EPSILON {
        return (0.0, min, max);
    }

    (100.0 * (max - close) / (max - min), min, max)
}
/// Calculates Williams %R for a single bar using unchecked min/max access.
///
/// # Arguments
///
/// * `state` - Mutable reference to the rolling `State` (min and max states).
/// * `high` - The full high price input slice.
/// * `low` - The full low price input slice.
/// * `close` - Reference to the current bar's close price.
/// * `i` - The current index into `high` and `low`.
/// * `periods` - A tuple of `(period, period - 1)` used by the min/max states.
///
/// # Returns
///
/// The Williams %R value for this bar.
///
/// # Safety
///
/// `i` and the look-back window must be within bounds of `high` and `low`.
#[inline(always)]
pub unsafe fn calc_unchecked<const N: usize>(
    state: &mut State,
    high: &[f64],
    low: &[f64],
    close: &f64,
    i: usize,
    periods: (usize, usize),
) -> (f64, f64, f64) {
    // Update the minimum and maximum for the rolling window.
    let (min, _) = calc_min_uncheked::<N>(&mut state.min_state, low, i, periods);
    let (max, _) = calc_max_uncheked::<N>(&mut state.max_state, high, i, periods);

    if (max - min).abs() < f64::EPSILON {
        return (0.0, min, max);
    }
    (100.0 * (max - close) / (max - min), min, max)
}