rsta 0.1.0

Technical analysis indicators, streaming signals, and a single-asset backtesting engine for Rust
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
use crate::indicators::utils::validate_data_length;
use crate::indicators::{Candle, Indicator, IndicatorError};

/// On Balance Volume (OBV) indicator
///
/// OBV is a momentum indicator that uses volume flow to predict changes in stock price.
/// It accumulates volume on up days and subtracts volume on down days.
///
/// # Example
///
/// ```
/// use rsta::indicators::volume::Obv;
/// use rsta::indicators::Indicator;
/// use rsta::indicators::Candle;
///
/// // Create an OBV indicator
/// let mut obv = Obv::new();
///
/// // Create price data with close and volume values
/// let candles = vec![
///     Candle { timestamp: 0, open: 10.0, high: 12.0, low: 9.0, close: 11.0, volume: 1000.0 },
///     Candle { timestamp: 1, open: 11.0, high: 13.0, low: 10.0, close: 12.0, volume: 1500.0 },
///     Candle { timestamp: 2, open: 12.0, high: 15.0, low: 11.0, close: 11.5, volume: 2000.0 },
///     // ... more candles ...
/// ];
///
/// // Calculate OBV values
/// let obv_values = obv.calculate(&candles).unwrap();
/// ```
#[derive(Debug)]
pub struct Obv {
    prev_close: Option<f64>,
    current_obv: f64,
}

impl Obv {
    /// Create a new Obv indicator
    pub fn new() -> Self {
        Self {
            prev_close: None,
            current_obv: 0.0,
        }
    }
}

impl Default for Obv {
    fn default() -> Self {
        Self::new()
    }
}

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

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

        // Reset state
        self.reset();

        // Set first OBV value
        self.current_obv = 0.0;
        result.push(self.current_obv);
        self.prev_close = Some(data[0].close);

        // Calculate OBV for each subsequent candle
        for candle in data.iter().take(n).skip(1) {
            let close = candle.close;
            let prev_close = self.prev_close.unwrap();
            let volume = candle.volume;

            if close > prev_close {
                // Up day
                self.current_obv += volume;
            } else if close < prev_close {
                // Down day
                self.current_obv -= volume;
            }
            // Equal days do not change OBV

            result.push(self.current_obv);
            self.prev_close = Some(close);
        }

        Ok(result)
    }

    fn next(&mut self, value: Candle) -> Result<Option<f64>, IndicatorError> {
        if let Some(prev_close) = self.prev_close {
            let close = value.close;
            let volume = value.volume;

            if close > prev_close {
                // Up day
                self.current_obv += volume;
            } else if close < prev_close {
                // Down day
                self.current_obv -= volume;
            }
            // Equal days do not change OBV

            self.prev_close = Some(close);
            Ok(Some(self.current_obv))
        } else {
            // First value just establishes the baseline
            self.prev_close = Some(value.close);
            self.current_obv = 0.0;
            Ok(Some(self.current_obv))
        }
    }

    fn reset(&mut self) {
        self.prev_close = None;
        self.current_obv = 0.0;
    }
}

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

    // Obv Tests
    #[test]
    fn test_obv_new() {
        // Obv has no parameters to validate
        let obv = Obv::new();
        assert!(obv.current_obv == 0.0);
    }

    #[test]
    fn test_obv_calculation() {
        let mut obv = Obv::new();

        // Create test candles with predictable pattern
        let candles = vec![
            Candle {
                timestamp: 1,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.5,
                volume: 1000.0,
            }, // Initial price
            Candle {
                timestamp: 2,
                open: 10.5,
                high: 12.0,
                low: 10.0,
                close: 11.0,
                volume: 1200.0,
            }, // Price up
            Candle {
                timestamp: 3,
                open: 11.0,
                high: 11.5,
                low: 10.0,
                close: 10.2,
                volume: 800.0,
            }, // Price down
            Candle {
                timestamp: 4,
                open: 10.2,
                high: 11.0,
                low: 10.0,
                close: 10.8,
                volume: 900.0,
            }, // Price up
            Candle {
                timestamp: 5,
                open: 10.8,
                high: 11.0,
                low: 10.0,
                close: 10.8,
                volume: 700.0,
            }, // Price unchanged
        ];

        let result = obv.calculate(&candles).unwrap();

        // We get one OBV value for each candle
        assert_eq!(result.len(), 5);

        // First value is set to 0 by the OBV implementation
        assert_eq!(result[0], 0.0);

        // Second value: previous OBV + second volume (price up)
        assert_eq!(result[1], 1200.0);

        // Third value: previous OBV - volume (price down)
        assert_eq!(result[2], 400.0);

        // Fourth value: previous OBV + volume (price up)
        assert_eq!(result[3], 1300.0);

        // Fifth value: unchanged OBV (price unchanged)
        assert_eq!(result[4], 1300.0);
    }

    #[test]
    fn test_obv_next() {
        let mut obv = Obv::new();

        // First candle - sets initial OBV
        // First candle - sets initial OBV to 0
        let candle1 = Candle {
            timestamp: 1,
            open: 10.0,
            high: 11.0,
            low: 9.0,
            close: 10.5,
            volume: 1000.0,
        };
        assert_eq!(obv.next(candle1).unwrap(), Some(0.0));

        // Next candle - price up, add volume
        let candle2 = Candle {
            timestamp: 2,
            open: 10.5,
            high: 12.0,
            low: 10.0,
            close: 11.0,
            volume: 1200.0,
        };
        assert_eq!(obv.next(candle2).unwrap(), Some(1200.0));

        // Next candle - price down, subtract volume
        let candle3 = Candle {
            timestamp: 3,
            open: 11.0,
            high: 11.5,
            low: 10.0,
            close: 10.2,
            volume: 800.0,
        };
        assert_eq!(obv.next(candle3).unwrap(), Some(400.0));
    }

    #[test]
    fn test_obv_reset() {
        let mut obv = Obv::new();

        // Add some values
        let candle1 = Candle {
            timestamp: 1,
            open: 10.0,
            high: 11.0,
            low: 9.0,
            close: 10.5,
            volume: 1000.0,
        };
        obv.next(candle1).unwrap();

        // Reset
        obv.reset();

        // OBV should be reset to 0
        assert_eq!(obv.current_obv, 0.0);
        assert_eq!(obv.prev_close, None);

        // After reset, next candle should be treated as first
        // After reset, next candle should be treated as first (OBV starts at 0)
        let candle2 = Candle {
            timestamp: 2,
            open: 10.5,
            high: 12.0,
            low: 10.0,
            close: 11.0,
            volume: 1200.0,
        };
        assert_eq!(obv.next(candle2).unwrap(), Some(0.0));
    }

    #[test]
    fn test_obv_zero_volume() {
        let mut obv = Obv::new();

        // Create test candles with zero volume
        let candles = vec![
            Candle {
                timestamp: 1,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.5,
                volume: 1000.0,
            }, // Initial candle with volume
            Candle {
                timestamp: 2,
                open: 10.5,
                high: 12.0,
                low: 10.0,
                close: 11.0,
                volume: 0.0,
            }, // Price up but zero volume
            Candle {
                timestamp: 3,
                open: 11.0,
                high: 11.5,
                low: 10.0,
                close: 10.0,
                volume: 0.0,
            }, // Price down but zero volume
        ];

        let result = obv.calculate(&candles).unwrap();

        // First value is 0 by OBV definition
        assert_eq!(result[0], 0.0);

        // Second value should be unchanged from first because volume is 0
        assert_eq!(result[1], 0.0);

        // Third value should be unchanged from second because volume is 0
        assert_eq!(result[2], 0.0);

        // Test with streaming calculation too
        obv.reset();
        assert_eq!(obv.next(candles[0]).unwrap(), Some(0.0));
        assert_eq!(obv.next(candles[1]).unwrap(), Some(0.0)); // Zero volume should not change OBV
        assert_eq!(obv.next(candles[2]).unwrap(), Some(0.0)); // Zero volume should not change OBV
    }

    #[test]
    fn test_obv_extreme_volume_values() {
        let mut obv = Obv::new();

        // Create test candles with extreme volume values
        let candles = vec![
            Candle {
                timestamp: 1,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.5,
                volume: 1000.0,
            }, // Initial price
            Candle {
                timestamp: 2,
                open: 10.5,
                high: 12.0,
                low: 10.0,
                close: 11.0,
                volume: 1_000_000_000.0, // Extremely large volume
            }, // Price up
            Candle {
                timestamp: 3,
                open: 11.0,
                high: 11.5,
                low: 10.0,
                close: 10.0,
                volume: 500_000_000.0, // Another large volume
            }, // Price down
        ];

        let result = obv.calculate(&candles).unwrap();

        // First value is 0 by OBV definition
        assert_eq!(result[0], 0.0);

        // Second value: add the large volume (price up)
        assert_eq!(result[1], 1_000_000_000.0);

        // Third value: subtract the large volume (price down)
        assert_eq!(result[2], 1_000_000_000.0 - 500_000_000.0);
    }

    #[test]
    fn test_obv_identical_closing_prices() {
        let mut obv = Obv::new();

        // Create test candles with identical closing prices
        let candles = vec![
            Candle {
                timestamp: 1,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.5,
                volume: 1000.0,
            }, // Initial price
            Candle {
                timestamp: 2,
                open: 10.5,
                high: 12.0,
                low: 10.0,
                close: 10.5, // Same close as previous
                volume: 1200.0,
            },
            Candle {
                timestamp: 3,
                open: 10.5,
                high: 11.5,
                low: 10.0,
                close: 10.5, // Same close again
                volume: 800.0,
            },
            Candle {
                timestamp: 4,
                open: 10.5,
                high: 11.0,
                low: 10.0,
                close: 10.5, // Same close again
                volume: 900.0,
            },
        ];

        let result = obv.calculate(&candles).unwrap();

        // First value is 0 by OBV definition
        assert_eq!(result[0], 0.0);

        // All subsequent values should remain at 0 since prices are unchanged
        // and OBV should not change when close prices are identical
        assert_eq!(result[1], 0.0);
        assert_eq!(result[2], 0.0);
        assert_eq!(result[3], 0.0);
    }

    #[test]
    fn test_obv_consecutive_up_down_sequences() {
        let mut obv = Obv::new();

        // Create test candles with alternating up/down patterns
        let candles = vec![
            Candle {
                timestamp: 1,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1000.0,
            }, // Initial price
            Candle {
                timestamp: 2,
                open: 10.0,
                high: 12.0,
                low: 10.0,
                close: 11.0, // Up
                volume: 500.0,
            },
            Candle {
                timestamp: 3,
                open: 11.0,
                high: 11.5,
                low: 9.5,
                close: 10.0, // Down
                volume: 300.0,
            },
            Candle {
                timestamp: 4,
                open: 10.0,
                high: 10.5,
                low: 9.0,
                close: 10.5, // Up
                volume: 700.0,
            },
            Candle {
                timestamp: 5,
                open: 10.5,
                high: 11.0,
                low: 9.5,
                close: 9.5, // Down
                volume: 400.0,
            },
            Candle {
                timestamp: 6,
                open: 9.5,
                high: 10.5,
                low: 9.0,
                close: 10.0, // Up
                volume: 600.0,
            },
        ];

        let result = obv.calculate(&candles).unwrap();

        // First value is 0 by OBV definition
        assert_eq!(result[0], 0.0);

        // Check the pattern matches our expectation:
        // Initial: 0
        // Up: +500 => 500
        // Down: -300 => 200
        // Up: +700 => 900
        // Down: -400 => 500
        // Up: +600 => 1100
        assert_eq!(result[1], 500.0); // +500
        assert_eq!(result[2], 200.0); // +500-300
        assert_eq!(result[3], 900.0); // +500-300+700
        assert_eq!(result[4], 500.0); // +500-300+700-400
        assert_eq!(result[5], 1100.0); // +500-300+700-400+600

        // Test streaming calculation matches batch calculation
        let mut streaming_obv = Obv::new();
        for (i, candle) in candles.iter().enumerate() {
            let obv_value = streaming_obv.next(*candle).unwrap().unwrap();
            assert_eq!(
                obv_value, result[i],
                "Streaming calculation mismatch at index {}",
                i
            );
        }
    }

    #[test]
    fn test_obv_insufficient_data() {
        let mut obv = Obv::new();

        // Test with empty data
        let empty: Vec<Candle> = vec![];
        let result = obv.calculate(&empty);

        // Should error due to insufficient data (require at least 1 data point)
        assert!(result.is_err());
        if let Err(IndicatorError::InsufficientData(_)) = result {
            // Expected error
        } else {
            panic!("Expected InsufficientData error");
        }
    }

    #[test]
    fn test_obv_batch_vs_streaming_consistency() {
        let mut batch_obv = Obv::new();
        let mut streaming_obv = Obv::new();

        // Create test data with different patterns
        let candles = vec![
            Candle {
                timestamp: 1,
                open: 10.0,
                high: 11.0,
                low: 9.0,
                close: 10.0,
                volume: 1000.0,
            },
            Candle {
                timestamp: 2,
                open: 10.0,
                high: 12.0,
                low: 10.0,
                close: 11.0,
                volume: 1500.0,
            },
            Candle {
                timestamp: 3,
                open: 11.0,
                high: 11.5,
                low: 9.5,
                close: 10.0,
                volume: 800.0,
            },
            Candle {
                timestamp: 4,
                open: 10.0,
                high: 10.5,
                low: 9.0,
                close: 10.0,
                volume: 1200.0,
            },
            Candle {
                timestamp: 5,
                open: 10.0,
                high: 11.0,
                low: 9.5,
                close: 10.5,
                volume: 2000.0,
            },
        ];

        // Calculate batch result
        let batch_result = batch_obv.calculate(&candles).unwrap();

        // Calculate streaming result
        let mut streaming_result = Vec::with_capacity(candles.len());
        for candle in &candles {
            let value = streaming_obv.next(*candle).unwrap().unwrap();
            streaming_result.push(value);
        }

        // Compare results - they should be identical
        assert_eq!(batch_result.len(), streaming_result.len());

        for i in 0..batch_result.len() {
            assert_eq!(
                batch_result[i], streaming_result[i],
                "Batch and streaming results differ at index {}",
                i
            );
        }
    }
}