rsta 0.0.3

Rust Statistical Technical Analysis (RSTA) - A library for financial technical analysis indicators
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
use crate::indicators::utils::{validate_data_length, validate_period};
use crate::indicators::{Candle, Indicator, IndicatorError};
use std::collections::VecDeque;

/// Relative Strength Index (RSI) indicator
///
/// RSI measures the magnitude of recent price changes to evaluate
/// overbought or oversold conditions. The RSI ranges from 0 to 100.
/// Traditionally, RSI values of 70 or above indicate overbought conditions,
/// while values of 30 or below indicate oversold conditions.
///
/// # Example
///
/// ```
/// use rsta::indicators::momentum::Rsi;
/// use rsta::indicators::Indicator;
///
/// // Create a 14-period RSI
/// let mut rsi = Rsi::new(14).unwrap();
///
/// // Price data
/// let prices = vec![44.34, 44.09, 44.15, 43.61, 44.33, 44.83, 45.10, 45.42,
///                   45.84, 46.08, 45.89, 46.03, 45.61, 46.28, 46.28, 46.00,
///                   46.03, 46.41, 46.22, 45.64, 46.21, 46.25, 45.71, 46.45];
///
/// // Calculate RSI values
/// let rsi_values = rsi.calculate(&prices).unwrap();
/// ```
#[derive(Debug)]
pub struct Rsi {
    period: usize,
    prev_price: Option<f64>,
    gains: VecDeque<f64>,
    losses: VecDeque<f64>,
    avg_gain: Option<f64>,
    avg_loss: Option<f64>,
}

impl Rsi {
    /// Create a new RSI indicator
    ///
    /// # Arguments
    /// * `period` - The period for RSI calculation (must be at least 1)
    ///
    /// # Returns
    /// * `Result<Self, IndicatorError>` - A new RSI or an error
    pub fn new(period: usize) -> Result<Self, IndicatorError> {
        validate_period(period, 1)?;
        Ok(Self {
            period,
            prev_price: None,
            gains: VecDeque::with_capacity(period),
            losses: VecDeque::with_capacity(period),
            avg_gain: None,
            avg_loss: None,
        })
    }

    /// Calculate a single RSI value from average gain and loss
    ///
    /// # Arguments
    /// * `avg_gain` - The average gain over the period
    /// * `avg_loss` - The average loss over the period
    ///
    /// # Returns
    /// * `f64` - The RSI value
    fn calculate_rsi(avg_gain: f64, avg_loss: f64) -> f64 {
        // Edge case: If both gain and loss are 0, market is neutral (RSI = 50)
        if avg_gain == 0.0 && avg_loss == 0.0 {
            return 50.0;
        }

        // Edge case: If loss is 0 but gain is not, market is 100% up (RSI = 100)
        if avg_loss == 0.0 {
            return 100.0;
        }

        let rs = avg_gain / avg_loss;
        100.0 - (100.0 / (1.0 + rs))
    }

    /// Reset the internal state of the RSI indicator
    pub fn reset_state(&mut self) {
        self.prev_price = None;
        self.gains.clear();
        self.losses.clear();
        self.avg_gain = None;
        self.avg_loss = None;
    }
}

impl Indicator<f64, f64> for Rsi {
    fn calculate(&mut self, data: &[f64]) -> Result<Vec<f64>, IndicatorError> {
        validate_data_length(data, self.period + 1)?;

        let n = data.len();
        let mut result = Vec::with_capacity(n - self.period);

        // Reset state
        self.reset_state();

        // First, calculate price changes
        let mut price_changes = Vec::with_capacity(n - 1);
        for i in 1..n {
            price_changes.push(data[i] - data[i - 1]);
        }

        // Calculate initial gains and losses
        let mut gains = Vec::with_capacity(self.period);
        let mut losses = Vec::with_capacity(self.period);

        for &change in price_changes.iter().take(self.period) {
            if change > 0.0 {
                gains.push(change);
                losses.push(0.0);
            } else {
                gains.push(0.0);
                losses.push(-change);
            }
        }

        // Calculate first average gain and loss
        let mut avg_gain = gains.iter().sum::<f64>() / self.period as f64;
        let mut avg_loss = losses.iter().sum::<f64>() / self.period as f64;

        // Calculate first RSI
        result.push(Self::calculate_rsi(avg_gain, avg_loss));

        // Calculate the rest using the smoothed method
        for change in price_changes.iter().skip(self.period).copied() {
            let gain = if change > 0.0 { change } else { 0.0 };
            let loss = if change < 0.0 { -change } else { 0.0 };

            // Use Wilder's smoothing method
            avg_gain = (avg_gain * (self.period - 1) as f64 + gain) / self.period as f64;
            avg_loss = (avg_loss * (self.period - 1) as f64 + loss) / self.period as f64;

            result.push(Self::calculate_rsi(avg_gain, avg_loss));
        }

        Ok(result)
    }

    fn next(&mut self, value: f64) -> Result<Option<f64>, IndicatorError> {
        if let Some(prev) = self.prev_price {
            let change = value - prev;
            let gain = if change > 0.0 { change } else { 0.0 };
            let loss = if change < 0.0 { -change } else { 0.0 };

            self.gains.push_back(gain);
            self.losses.push_back(loss);

            if self.gains.len() > self.period {
                self.gains.pop_front();
                self.losses.pop_front();
            }

            if self.gains.len() < self.period {
                self.avg_gain = None;
                self.avg_loss = None;
                self.prev_price = Some(value);
                return Ok(None);
            }

            // Calculate/update average gain and loss
            if let (Some(avg_gain), Some(avg_loss)) = (self.avg_gain, self.avg_loss) {
                // Use Wilder's smoothing method for ongoing calculations
                self.avg_gain =
                    Some((avg_gain * (self.period - 1) as f64 + gain) / self.period as f64);
                self.avg_loss =
                    Some((avg_loss * (self.period - 1) as f64 + loss) / self.period as f64);
            } else {
                // Initial average calculation
                self.avg_gain = Some(self.gains.iter().sum::<f64>() / self.period as f64);
                self.avg_loss = Some(self.losses.iter().sum::<f64>() / self.period as f64);
            }

            let rsi = Self::calculate_rsi(self.avg_gain.unwrap(), self.avg_loss.unwrap());

            self.prev_price = Some(value);
            Ok(Some(rsi))
        } else {
            self.prev_price = Some(value);
            Ok(None)
        }
    }

    fn reset(&mut self) {
        self.reset_state();
    }
}

impl Indicator<Candle, f64> for Rsi {
    fn calculate(&mut self, data: &[Candle]) -> Result<Vec<f64>, IndicatorError> {
        validate_data_length(data, self.period + 1)?;

        let n = data.len();
        let mut result = Vec::with_capacity(n - self.period);

        // Reset state
        self.reset_state();

        // Extract close prices
        let close_prices: Vec<f64> = data.iter().map(|candle| candle.close).collect();

        // First, calculate price changes
        let mut price_changes = Vec::with_capacity(n - 1);
        for i in 1..n {
            price_changes.push(close_prices[i] - close_prices[i - 1]);
        }

        // Calculate initial gains and losses
        let mut gains = Vec::with_capacity(self.period);
        let mut losses = Vec::with_capacity(self.period);

        for &change in price_changes.iter().take(self.period) {
            if change > 0.0 {
                gains.push(change);
                losses.push(0.0);
            } else {
                gains.push(0.0);
                losses.push(-change);
            }
        }

        // Calculate first average gain and loss
        let mut avg_gain = gains.iter().sum::<f64>() / self.period as f64;
        let mut avg_loss = losses.iter().sum::<f64>() / self.period as f64;

        // Calculate first RSI
        result.push(Self::calculate_rsi(avg_gain, avg_loss));

        // Calculate the rest using the smoothed method
        for change in price_changes.iter().skip(self.period).copied() {
            let gain = if change > 0.0 { change } else { 0.0 };
            let loss = if change < 0.0 { -change } else { 0.0 };

            // Use Wilder's smoothing method
            avg_gain = (avg_gain * (self.period - 1) as f64 + gain) / self.period as f64;
            avg_loss = (avg_loss * (self.period - 1) as f64 + loss) / self.period as f64;

            result.push(Self::calculate_rsi(avg_gain, avg_loss));
        }

        Ok(result)
    }

    fn next(&mut self, candle: Candle) -> Result<Option<f64>, IndicatorError> {
        let close_price = candle.close;

        if let Some(prev) = self.prev_price {
            let change = close_price - prev;
            let gain = if change > 0.0 { change } else { 0.0 };
            let loss = if change < 0.0 { -change } else { 0.0 };

            self.gains.push_back(gain);
            self.losses.push_back(loss);

            if self.gains.len() > self.period {
                self.gains.pop_front();
                self.losses.pop_front();
            }

            if self.gains.len() < self.period {
                self.avg_gain = None;
                self.avg_loss = None;
                self.prev_price = Some(close_price);
                return Ok(None);
            }

            // Calculate/update average gain and loss
            if let (Some(avg_gain), Some(avg_loss)) = (self.avg_gain, self.avg_loss) {
                // Use Wilder's smoothing method for ongoing calculations
                self.avg_gain =
                    Some((avg_gain * (self.period - 1) as f64 + gain) / self.period as f64);
                self.avg_loss =
                    Some((avg_loss * (self.period - 1) as f64 + loss) / self.period as f64);
            } else {
                // Initial average calculation
                self.avg_gain = Some(self.gains.iter().sum::<f64>() / self.period as f64);
                self.avg_loss = Some(self.losses.iter().sum::<f64>() / self.period as f64);
            }

            let rsi = Self::calculate_rsi(self.avg_gain.unwrap(), self.avg_loss.unwrap());

            self.prev_price = Some(close_price);
            Ok(Some(rsi))
        } else {
            self.prev_price = Some(close_price);
            Ok(None)
        }
    }

    fn reset(&mut self) {
        self.reset_state();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // RSI Tests
    #[test]
    fn test_rsi_new() {
        // Valid period should work
        assert!(Rsi::new(14).is_ok());

        // Invalid period should fail
        assert!(Rsi::new(0).is_err());
    }

    #[test]
    fn test_rsi_calculation() {
        let mut rsi = Rsi::new(3).unwrap();

        // Sample price data
        let prices = vec![10.0, 11.0, 10.5, 11.5, 12.0, 11.0, 11.5];

        let result = rsi.calculate(&prices).unwrap();
        assert_eq!(result.len(), 4); // 7 prices - 3 period = 4 results

        // First RSI: price changes = [1.0, -0.5, 1.0]
        // Average gain = (1.0 + 0.0 + 1.0) / 3 = 0.6667
        // Average loss = (0.0 + 0.5 + 0.0) / 3 = 0.1667
        // RS = 0.6667 / 0.1667 = 4.0
        // RSI = 100 - (100 / (1 + 4.0)) = 100 - 20 = 80.0
        assert!((result[0] - 80.0).abs() < 0.01);

        // Check final value is correct
        // Last price change is 0.5, a gain
        // Using Wilder's smoothing method
        let last_value = result.last().unwrap();
        assert!(*last_value >= 0.0 && *last_value <= 100.0);
    }

    #[test]
    fn test_rsi_next() {
        let mut rsi = Rsi::new(3).unwrap();

        // Initial values - not enough data yet
        assert_eq!(rsi.next(10.0).unwrap(), None);
        assert_eq!(rsi.next(11.0).unwrap(), None);
        assert_eq!(rsi.next(10.5).unwrap(), None);

        // Fourth value - now we have RSI
        let first_rsi = rsi.next(11.5).unwrap();
        assert!(first_rsi.is_some());
        let first_rsi_value = first_rsi.unwrap();
        assert!((0.0..=100.0).contains(&first_rsi_value));

        // More values - should keep producing results
        assert!(rsi.next(12.0).unwrap().is_some());
        assert!(rsi.next(11.0).unwrap().is_some());
    }

    #[test]
    fn test_rsi_reset() {
        let mut rsi = Rsi::new(3).unwrap();

        // Add some values
        rsi.next(10.0).unwrap();
        rsi.next(11.0).unwrap();
        rsi.next(10.5).unwrap();
        rsi.next(11.5).unwrap(); // This should produce a result

        // Reset
        rsi.reset_state();

        // Should be back to initial state
        assert_eq!(rsi.next(12.0).unwrap(), None);
    }

    // Tests for RSI with Candle data
    #[test]
    fn test_rsi_calculation_with_candles() {
        let mut rsi = Rsi::new(3).unwrap();

        // Sample candle data with same close prices as the f64 test
        let candles = vec![
            Candle {
                timestamp: 1,
                open: 9.0,
                high: 10.5,
                low: 8.5,
                close: 10.0,
                volume: 1000.0,
            },
            Candle {
                timestamp: 2,
                open: 10.5,
                high: 11.5,
                low: 10.0,
                close: 11.0,
                volume: 1200.0,
            },
            Candle {
                timestamp: 3,
                open: 11.0,
                high: 11.5,
                low: 10.0,
                close: 10.5,
                volume: 1100.0,
            },
            Candle {
                timestamp: 4,
                open: 10.0,
                high: 12.0,
                low: 10.0,
                close: 11.5,
                volume: 1300.0,
            },
            Candle {
                timestamp: 5,
                open: 11.5,
                high: 12.5,
                low: 11.0,
                close: 12.0,
                volume: 1400.0,
            },
            Candle {
                timestamp: 6,
                open: 12.0,
                high: 12.0,
                low: 10.5,
                close: 11.0,
                volume: 1500.0,
            },
            Candle {
                timestamp: 7,
                open: 11.0,
                high: 12.0,
                low: 11.0,
                close: 11.5,
                volume: 1600.0,
            },
        ];

        let result = rsi.calculate(&candles).unwrap();
        assert_eq!(result.len(), 4); // 7 candles - 3 period = 4 results

        // First RSI: price changes = [1.0, -0.5, 1.0]
        // Average gain = (1.0 + 0.0 + 1.0) / 3 = 0.6667
        // Average loss = (0.0 + 0.5 + 0.0) / 3 = 0.1667
        // RS = 0.6667 / 0.1667 = 4.0
        // RSI = 100 - (100 / (1 + 4.0)) = 100 - 20 = 80.0
        assert!((result[0] - 80.0).abs() < 0.01);

        // The result should match the result of the same calculation with raw prices
        let close_prices: Vec<f64> = candles.iter().map(|c| c.close).collect();
        let mut price_rsi = Rsi::new(3).unwrap();
        let price_result = price_rsi.calculate(&close_prices).unwrap();

        // Compare each value to ensure candle and f64 implementations produce identical results
        for (candle_rsi, price_rsi) in result.iter().zip(price_result.iter()) {
            assert!((candle_rsi - price_rsi).abs() < 0.000001);
        }
    }

    #[test]
    fn test_rsi_next_with_candles() {
        let mut rsi = Rsi::new(3).unwrap();

        // Create candles with same close prices as the f64 test
        let candles = [
            Candle {
                timestamp: 1,
                open: 9.0,
                high: 10.5,
                low: 8.5,
                close: 10.0,
                volume: 1000.0,
            },
            Candle {
                timestamp: 2,
                open: 10.5,
                high: 11.5,
                low: 10.0,
                close: 11.0,
                volume: 1200.0,
            },
            Candle {
                timestamp: 3,
                open: 11.0,
                high: 11.5,
                low: 10.0,
                close: 10.5,
                volume: 1100.0,
            },
            Candle {
                timestamp: 4,
                open: 10.0,
                high: 12.0,
                low: 10.0,
                close: 11.5,
                volume: 1300.0,
            },
        ];

        // Initial values - not enough data yet
        assert_eq!(rsi.next(candles[0]).unwrap(), None);
        assert_eq!(rsi.next(candles[1]).unwrap(), None);
        assert_eq!(rsi.next(candles[2]).unwrap(), None);

        // Fourth value - now we have RSI
        let first_rsi = rsi.next(candles[3]).unwrap();
        assert!(first_rsi.is_some());
        let first_rsi_value = first_rsi.unwrap();
        assert!((0.0..=100.0).contains(&first_rsi_value));

        // Create a test with raw prices to verify identical results
        let mut price_rsi = Rsi::new(3).unwrap();
        price_rsi.next(candles[0].close).unwrap();
        price_rsi.next(candles[1].close).unwrap();
        price_rsi.next(candles[2].close).unwrap();
        let price_first_rsi = price_rsi.next(candles[3].close).unwrap().unwrap();

        // RSI values should match between Candle and f64 implementations
        assert!((first_rsi_value - price_first_rsi).abs() < 0.000001);
    }

    #[test]
    fn test_rsi_with_candles_ignores_other_price_data() {
        let mut rsi = Rsi::new(3).unwrap();

        // Create candles with varying open/high/low but identical close prices
        let candles = vec![
            Candle {
                timestamp: 1,
                open: 15.0,
                high: 20.0,
                low: 5.0,
                close: 10.0,
                volume: 5000.0,
            },
            Candle {
                timestamp: 2,
                open: 25.0,
                high: 30.0,
                low: 8.0,
                close: 11.0,
                volume: 6000.0,
            },
            Candle {
                timestamp: 3,
                open: 5.0,
                high: 15.0,
                low: 2.0,
                close: 10.5,
                volume: 7000.0,
            },
            Candle {
                timestamp: 4,
                open: 20.0,
                high: 25.0,
                low: 9.0,
                close: 11.5,
                volume: 8000.0,
            },
        ];

        // Create candles with same close prices but different open/high/low
        let candles2 = vec![
            Candle {
                timestamp: 1,
                open: 9.0,
                high: 10.5,
                low: 8.5,
                close: 10.0,
                volume: 1000.0,
            },
            Candle {
                timestamp: 2,
                open: 10.5,
                high: 11.5,
                low: 10.0,
                close: 11.0,
                volume: 1200.0,
            },
            Candle {
                timestamp: 3,
                open: 11.0,
                high: 11.5,
                low: 10.0,
                close: 10.5,
                volume: 1100.0,
            },
            Candle {
                timestamp: 4,
                open: 10.0,
                high: 12.0,
                low: 10.0,
                close: 11.5,
                volume: 1300.0,
            },
        ];

        // Calculate RSI for both sets
        let result1 = rsi.calculate(&candles).unwrap();

        // Reset and calculate for second set
        rsi.reset_state();
        let result2 = rsi.calculate(&candles2).unwrap();

        // Results should be identical since only close prices matter
        assert_eq!(result1.len(), result2.len());
        for (val1, val2) in result1.iter().zip(result2.iter()) {
            assert!((val1 - val2).abs() < 0.000001);
        }
    }

    #[test]
    fn test_rsi_with_candles_reset() {
        let mut rsi = Rsi::new(3).unwrap();

        // Add some values
        rsi.next(Candle {
            timestamp: 1,
            open: 9.0,
            high: 10.5,
            low: 8.5,
            close: 10.0,
            volume: 1000.0,
        })
        .unwrap();
        rsi.next(Candle {
            timestamp: 2,
            open: 10.5,
            high: 11.5,
            low: 10.0,
            close: 11.0,
            volume: 1200.0,
        })
        .unwrap();
        rsi.next(Candle {
            timestamp: 3,
            open: 11.0,
            high: 11.5,
            low: 10.0,
            close: 10.5,
            volume: 1100.0,
        })
        .unwrap();
        rsi.next(Candle {
            timestamp: 4,
            open: 10.0,
            high: 12.0,
            low: 10.0,
            close: 11.5,
            volume: 1300.0,
        })
        .unwrap(); // This should produce a result

        // Reset
        rsi.reset_state();

        // Should be back to initial state
        assert_eq!(
            rsi.next(Candle {
                timestamp: 5,
                open: 11.5,
                high: 12.5,
                low: 11.0,
                close: 12.0,
                volume: 1400.0
            })
            .unwrap(),
            None
        );
    }

    #[test]
    fn test_rsi_with_candles_edge_cases() {
        let mut rsi = Rsi::new(3).unwrap();

        // Test with identical close prices (no change)
        let flat_candles = vec![
            Candle {
                timestamp: 1,
                open: 9.0,
                high: 10.5,
                low: 8.5,
                close: 10.0,
                volume: 1000.0,
            },
            Candle {
                timestamp: 2,
                open: 10.5,
                high: 11.5,
                low: 10.0,
                close: 10.0,
                volume: 1200.0,
            },
            Candle {
                timestamp: 3,
                open: 11.0,
                high: 11.5,
                low: 10.0,
                close: 10.0,
                volume: 1100.0,
            },
            Candle {
                timestamp: 4,
                open: 10.0,
                high: 12.0,
                low: 10.0,
                close: 10.0,
                volume: 1300.0,
            },
        ];

        let result = rsi.calculate(&flat_candles).unwrap();
        assert_eq!(result[0], 50.0); // With no changes, RSI should be 50

        // Test with only up movements (all gains, no losses)
        let mut rsi = Rsi::new(3).unwrap();
        let up_candles = vec![
            Candle {
                timestamp: 1,
                open: 9.0,
                high: 10.5,
                low: 8.5,
                close: 10.0,
                volume: 1000.0,
            },
            Candle {
                timestamp: 2,
                open: 10.5,
                high: 11.5,
                low: 10.0,
                close: 11.0,
                volume: 1200.0,
            },
            Candle {
                timestamp: 3,
                open: 11.0,
                high: 11.5,
                low: 10.0,
                close: 12.0,
                volume: 1100.0,
            },
            Candle {
                timestamp: 4,
                open: 12.0,
                high: 13.0,
                low: 11.0,
                close: 13.0,
                volume: 1300.0,
            },
        ];

        let result = rsi.calculate(&up_candles).unwrap();
        assert_eq!(result[0], 100.0); // With only gains, RSI should be 100

        // Test with only down movements (all losses, no gains)
        let mut rsi = Rsi::new(3).unwrap();
        let down_candles = vec![
            Candle {
                timestamp: 1,
                open: 14.0,
                high: 15.0,
                low: 13.5,
                close: 14.0,
                volume: 1000.0,
            },
            Candle {
                timestamp: 2,
                open: 13.5,
                high: 14.0,
                low: 13.0,
                close: 13.0,
                volume: 1200.0,
            },
            Candle {
                timestamp: 3,
                open: 13.0,
                high: 13.0,
                low: 12.0,
                close: 12.0,
                volume: 1100.0,
            },
            Candle {
                timestamp: 4,
                open: 12.0,
                high: 12.0,
                low: 11.0,
                close: 11.0,
                volume: 1300.0,
            },
        ];

        let result = rsi.calculate(&down_candles).unwrap();
        assert_eq!(result[0], 0.0); // With only losses, RSI should be 0
    }
}