kestrel_chartkit/indicator/rci.rs
1use std::collections::VecDeque;
2
3use crate::model::Bar;
4use crate::stats::correlation;
5
6use super::{Indicator, IndicatorOutput};
7
8/// Rank Correlation Index: how closely the order of the last `len` prices follows the order of
9/// time.
10///
11/// Prices in the window are ranked, time is ranked by position, and the two rank series are
12/// correlated; the result is scaled by 100. A window whose prices rise monotonically gives +100,
13/// one that falls monotonically -100, and a shuffled one something in between.
14///
15/// **Ties get the average of the ranks they share.** Two equal prices are not one before the
16/// other, and pretending otherwise would invent an ordering the market did not produce. The
17/// correlation is then computed over the rank series directly rather than through the
18/// `1 - 6*sum(d^2)/(n^3-n)` shortcut, which is only valid when no rank is shared.
19///
20/// Unit: an index in `-100..=100`, not a percentage of anything.
21///
22/// A window without price variance — every price equal — has no ordering at all. There is no
23/// correlation to compute, and the documented convention is `0`: no direction, rather than a
24/// trend strength conjured from nothing.
25///
26/// First output: with the `len`-th bar. `len` must be at least 2, since a single price has no
27/// order. A window that holds a non-finite price produces no output at all — there is no ordering
28/// to compute. [`Indicator::reset`] clears the window.
29#[derive(Debug, Clone)]
30pub struct RciEngine {
31 len: usize,
32 window: VecDeque<f64>,
33}
34
35impl RciEngine {
36 pub fn new(len: usize) -> Self {
37 Self {
38 len: len.max(2),
39 window: VecDeque::with_capacity(len.max(2)),
40 }
41 }
42
43 pub fn with_defaults() -> Self {
44 Self::new(9)
45 }
46}
47
48/// Average ranks of `values`, ascending: the smallest value gets rank 1, and values that are
49/// equal share the mean of the ranks they occupy.
50fn average_ranks(values: &[f64]) -> Vec<f64> {
51 let mut order: Vec<usize> = (0..values.len()).collect();
52 // `total_cmp` rather than `partial_cmp`: a total order cannot fail on any input, and the
53 // caller has already refused windows with non-finite prices.
54 order.sort_by(|a, b| values[*a].total_cmp(&values[*b]));
55
56 let mut ranks = vec![0.0; values.len()];
57 let mut start = 0;
58 while start < order.len() {
59 let mut end = start + 1;
60 while end < order.len() && values[order[end]] == values[order[start]] {
61 end += 1;
62 }
63 // Ranks are one-based; the shared rank is the mean of the positions this group occupies.
64 let shared = ((start + 1) + end) as f64 / 2.0;
65 for slot in &order[start..end] {
66 ranks[*slot] = shared;
67 }
68 start = end;
69 }
70 ranks
71}
72
73impl Indicator for RciEngine {
74 fn name(&self) -> &str {
75 "rci"
76 }
77
78 fn warmup_period(&self) -> usize {
79 self.len
80 }
81
82 fn on_bar(&mut self, bar: &Bar) -> Option<IndicatorOutput> {
83 self.window.push_back(bar.close);
84 if self.window.len() > self.len {
85 self.window.pop_front();
86 }
87 if self.window.len() < self.len {
88 return None;
89 }
90
91 let prices: Vec<f64> = self.window.iter().copied().collect();
92 if prices.iter().any(|price| !price.is_finite()) {
93 // A window holding a non-finite price has no order to speak of. No output beats a
94 // rank correlation over a value that is not a price.
95 return None;
96 }
97 let price_ranks = average_ranks(&prices);
98 let time_ranks: Vec<f64> = (1..=self.len).map(|i| i as f64).collect();
99
100 // `None` means one side has no variance, which for the time ranks cannot happen — so it
101 // is the price side, i.e. a window of identical prices.
102 let value = correlation(&price_ranks, &time_ranks).unwrap_or(0.0) * 100.0;
103 Some(IndicatorOutput::new(value))
104 }
105
106 fn reset(&mut self) {
107 self.window.clear();
108 }
109}