finance-query 2.5.1

A Rust library for querying financial data
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
//! Price-based indicator references.
//!
//! This module provides references to OHLCV price data that can be used
//! in trading conditions without requiring indicator computation.

use crate::indicators::Indicator;

use super::IndicatorRef;
use crate::backtesting::strategy::StrategyContext;

/// Reference to the close price.
///
/// # Example
///
/// ```ignore
/// use finance_query::backtesting::refs::*;
///
/// let close_above_sma = close().above_ref(sma(200));
/// ```
#[derive(Debug, Clone, Copy)]
pub struct ClosePrice;

impl IndicatorRef for ClosePrice {
    fn key(&self) -> &str {
        "close"
    }

    fn required_indicators(&self) -> Vec<(String, Indicator)> {
        vec![] // Price doesn't need pre-computation
    }

    fn value(&self, ctx: &StrategyContext) -> Option<f64> {
        Some(ctx.close())
    }

    fn prev_value(&self, ctx: &StrategyContext) -> Option<f64> {
        ctx.previous_candle().map(|c| c.close)
    }
}

/// Reference to the open price.
#[derive(Debug, Clone, Copy)]
pub struct OpenPrice;

impl IndicatorRef for OpenPrice {
    fn key(&self) -> &str {
        "open"
    }

    fn required_indicators(&self) -> Vec<(String, Indicator)> {
        vec![]
    }

    fn value(&self, ctx: &StrategyContext) -> Option<f64> {
        Some(ctx.open())
    }

    fn prev_value(&self, ctx: &StrategyContext) -> Option<f64> {
        ctx.previous_candle().map(|c| c.open)
    }
}

/// Reference to the high price.
#[derive(Debug, Clone, Copy)]
pub struct HighPrice;

impl IndicatorRef for HighPrice {
    fn key(&self) -> &str {
        "high"
    }

    fn required_indicators(&self) -> Vec<(String, Indicator)> {
        vec![]
    }

    fn value(&self, ctx: &StrategyContext) -> Option<f64> {
        Some(ctx.high())
    }

    fn prev_value(&self, ctx: &StrategyContext) -> Option<f64> {
        ctx.previous_candle().map(|c| c.high)
    }
}

/// Reference to the low price.
#[derive(Debug, Clone, Copy)]
pub struct LowPrice;

impl IndicatorRef for LowPrice {
    fn key(&self) -> &str {
        "low"
    }

    fn required_indicators(&self) -> Vec<(String, Indicator)> {
        vec![]
    }

    fn value(&self, ctx: &StrategyContext) -> Option<f64> {
        Some(ctx.low())
    }

    fn prev_value(&self, ctx: &StrategyContext) -> Option<f64> {
        ctx.previous_candle().map(|c| c.low)
    }
}

/// Reference to the volume.
#[derive(Debug, Clone, Copy)]
pub struct VolumeRef;

impl IndicatorRef for VolumeRef {
    fn key(&self) -> &str {
        "volume"
    }

    fn required_indicators(&self) -> Vec<(String, Indicator)> {
        vec![]
    }

    fn value(&self, ctx: &StrategyContext) -> Option<f64> {
        Some(ctx.volume() as f64)
    }

    fn prev_value(&self, ctx: &StrategyContext) -> Option<f64> {
        ctx.previous_candle().map(|c| c.volume as f64)
    }
}

/// Reference to the typical price: (high + low + close) / 3
#[derive(Debug, Clone, Copy)]
pub struct TypicalPrice;

impl IndicatorRef for TypicalPrice {
    fn key(&self) -> &str {
        "typical_price"
    }

    fn required_indicators(&self) -> Vec<(String, Indicator)> {
        vec![]
    }

    fn value(&self, ctx: &StrategyContext) -> Option<f64> {
        let candle = ctx.current_candle();
        Some((candle.high + candle.low + candle.close) / 3.0)
    }

    fn prev_value(&self, ctx: &StrategyContext) -> Option<f64> {
        ctx.previous_candle()
            .map(|c| (c.high + c.low + c.close) / 3.0)
    }
}

/// Reference to the median price: (high + low) / 2
#[derive(Debug, Clone, Copy)]
pub struct MedianPrice;

impl IndicatorRef for MedianPrice {
    fn key(&self) -> &str {
        "median_price"
    }

    fn required_indicators(&self) -> Vec<(String, Indicator)> {
        vec![]
    }

    fn value(&self, ctx: &StrategyContext) -> Option<f64> {
        let candle = ctx.current_candle();
        Some((candle.high + candle.low) / 2.0)
    }

    fn prev_value(&self, ctx: &StrategyContext) -> Option<f64> {
        ctx.previous_candle().map(|c| (c.high + c.low) / 2.0)
    }
}

// ============================================================================
// DERIVED PRICE REFERENCES
// ============================================================================

/// Reference to the price change percentage from previous close.
///
/// Returns the percentage change: ((current_close - prev_close) / prev_close) * 100
///
/// # Example
///
/// ```ignore
/// use finance_query::backtesting::refs::*;
///
/// // Enter on big moves (>2% change)
/// let big_move = price_change_pct().above(2.0);
/// // Exit on reversal
/// let reversal = price_change_pct().below(-1.5);
/// ```
#[derive(Debug, Clone, Copy)]
pub struct PriceChangePct;

impl IndicatorRef for PriceChangePct {
    fn key(&self) -> &str {
        "price_change_pct"
    }

    fn required_indicators(&self) -> Vec<(String, Indicator)> {
        vec![]
    }

    fn value(&self, ctx: &StrategyContext) -> Option<f64> {
        let current = ctx.close();
        ctx.previous_candle().map(|prev| {
            if prev.close != 0.0 {
                ((current - prev.close) / prev.close) * 100.0
            } else {
                0.0
            }
        })
    }

    fn prev_value(&self, ctx: &StrategyContext) -> Option<f64> {
        // Need candle at idx-1 and idx-2
        let candles = &ctx.candles;
        let idx = ctx.index;
        if idx >= 2 {
            let prev = &candles[idx - 1];
            let prev_prev = &candles[idx - 2];
            if prev_prev.close != 0.0 {
                Some(((prev.close - prev_prev.close) / prev_prev.close) * 100.0)
            } else {
                Some(0.0)
            }
        } else {
            None
        }
    }
}

/// Reference to the gap percentage (open vs previous close).
///
/// Returns: ((current_open - prev_close) / prev_close) * 100
///
/// # Example
///
/// ```ignore
/// use finance_query::backtesting::refs::*;
///
/// // Gap up strategy
/// let gap_up = gap_pct().above(1.0);
/// // Gap down reversal
/// let gap_down = gap_pct().below(-2.0);
/// ```
#[derive(Debug, Clone, Copy)]
pub struct GapPct;

impl IndicatorRef for GapPct {
    fn key(&self) -> &str {
        "gap_pct"
    }

    fn required_indicators(&self) -> Vec<(String, Indicator)> {
        vec![]
    }

    fn value(&self, ctx: &StrategyContext) -> Option<f64> {
        let current_open = ctx.open();
        ctx.previous_candle().map(|prev| {
            if prev.close != 0.0 {
                ((current_open - prev.close) / prev.close) * 100.0
            } else {
                0.0
            }
        })
    }

    fn prev_value(&self, ctx: &StrategyContext) -> Option<f64> {
        let candles = &ctx.candles;
        let idx = ctx.index;
        if idx >= 2 {
            let prev = &candles[idx - 1];
            let prev_prev = &candles[idx - 2];
            if prev_prev.close != 0.0 {
                Some(((prev.open - prev_prev.close) / prev_prev.close) * 100.0)
            } else {
                Some(0.0)
            }
        } else {
            None
        }
    }
}

/// Reference to the candle range (high - low).
///
/// # Example
///
/// ```ignore
/// use finance_query::backtesting::refs::*;
///
/// // Filter for high volatility candles
/// let wide_range = candle_range().above(5.0);
/// ```
#[derive(Debug, Clone, Copy)]
pub struct CandleRange;

impl IndicatorRef for CandleRange {
    fn key(&self) -> &str {
        "candle_range"
    }

    fn required_indicators(&self) -> Vec<(String, Indicator)> {
        vec![]
    }

    fn value(&self, ctx: &StrategyContext) -> Option<f64> {
        let candle = ctx.current_candle();
        Some(candle.high - candle.low)
    }

    fn prev_value(&self, ctx: &StrategyContext) -> Option<f64> {
        ctx.previous_candle().map(|c| c.high - c.low)
    }
}

/// Reference to the candle body size (absolute difference between open and close).
///
/// # Example
///
/// ```ignore
/// use finance_query::backtesting::refs::*;
///
/// // Strong candle filter
/// let strong_body = candle_body().above(2.0);
/// ```
#[derive(Debug, Clone, Copy)]
pub struct CandleBody;

impl IndicatorRef for CandleBody {
    fn key(&self) -> &str {
        "candle_body"
    }

    fn required_indicators(&self) -> Vec<(String, Indicator)> {
        vec![]
    }

    fn value(&self, ctx: &StrategyContext) -> Option<f64> {
        let candle = ctx.current_candle();
        Some((candle.close - candle.open).abs())
    }

    fn prev_value(&self, ctx: &StrategyContext) -> Option<f64> {
        ctx.previous_candle().map(|c| (c.close - c.open).abs())
    }
}

/// Reference to whether the current candle is bullish (close > open).
///
/// Returns 1.0 if bullish, 0.0 if bearish or doji.
///
/// # Example
///
/// ```ignore
/// use finance_query::backtesting::refs::*;
///
/// // Only enter on bullish candles
/// let bullish = is_bullish().above(0.5);
/// ```
#[derive(Debug, Clone, Copy)]
pub struct IsBullish;

impl IndicatorRef for IsBullish {
    fn key(&self) -> &str {
        "is_bullish"
    }

    fn required_indicators(&self) -> Vec<(String, Indicator)> {
        vec![]
    }

    fn value(&self, ctx: &StrategyContext) -> Option<f64> {
        let candle = ctx.current_candle();
        Some(if candle.close > candle.open { 1.0 } else { 0.0 })
    }

    fn prev_value(&self, ctx: &StrategyContext) -> Option<f64> {
        ctx.previous_candle()
            .map(|c| if c.close > c.open { 1.0 } else { 0.0 })
    }
}

/// Reference to whether the current candle is bearish (close < open).
///
/// Returns 1.0 if bearish, 0.0 if bullish or doji.
#[derive(Debug, Clone, Copy)]
pub struct IsBearish;

impl IndicatorRef for IsBearish {
    fn key(&self) -> &str {
        "is_bearish"
    }

    fn required_indicators(&self) -> Vec<(String, Indicator)> {
        vec![]
    }

    fn value(&self, ctx: &StrategyContext) -> Option<f64> {
        let candle = ctx.current_candle();
        Some(if candle.close < candle.open { 1.0 } else { 0.0 })
    }

    fn prev_value(&self, ctx: &StrategyContext) -> Option<f64> {
        ctx.previous_candle()
            .map(|c| if c.close < c.open { 1.0 } else { 0.0 })
    }
}

// === Convenience Functions ===

/// Get a reference to the close price.
///
/// # Example
///
/// ```ignore
/// use finance_query::backtesting::refs::*;
///
/// let above_sma = price().above_ref(sma(200));
/// let crosses_ema = close().crosses_above_ref(ema(50));
/// ```
#[inline]
pub fn price() -> ClosePrice {
    ClosePrice
}

/// Get a reference to the close price.
///
/// Alias for [`price()`].
#[inline]
pub fn close() -> ClosePrice {
    ClosePrice
}

/// Get a reference to the open price.
#[inline]
pub fn open() -> OpenPrice {
    OpenPrice
}

/// Get a reference to the high price.
#[inline]
pub fn high() -> HighPrice {
    HighPrice
}

/// Get a reference to the low price.
#[inline]
pub fn low() -> LowPrice {
    LowPrice
}

/// Get a reference to the volume.
#[inline]
pub fn volume() -> VolumeRef {
    VolumeRef
}

/// Get a reference to the typical price: (high + low + close) / 3.
#[inline]
pub fn typical_price() -> TypicalPrice {
    TypicalPrice
}

/// Get a reference to the median price: (high + low) / 2.
#[inline]
pub fn median_price() -> MedianPrice {
    MedianPrice
}

/// Get a reference to the price change percentage from previous close.
///
/// # Example
///
/// ```ignore
/// use finance_query::backtesting::refs::*;
///
/// // Big move filter (>2% change)
/// let big_move = price_change_pct().above(2.0);
/// ```
#[inline]
pub fn price_change_pct() -> PriceChangePct {
    PriceChangePct
}

/// Get a reference to the gap percentage (open vs previous close).
///
/// # Example
///
/// ```ignore
/// use finance_query::backtesting::refs::*;
///
/// // Gap up entry
/// let gap_up = gap_pct().above(1.0);
/// ```
#[inline]
pub fn gap_pct() -> GapPct {
    GapPct
}

/// Get a reference to the candle range (high - low).
#[inline]
pub fn candle_range() -> CandleRange {
    CandleRange
}

/// Get a reference to the candle body size.
#[inline]
pub fn candle_body() -> CandleBody {
    CandleBody
}

/// Returns 1.0 if the candle is bullish (close > open), 0.0 otherwise.
///
/// Use with `.above(0.5)` to check for bullish candle.
#[inline]
pub fn is_bullish() -> IsBullish {
    IsBullish
}

/// Returns 1.0 if the candle is bearish (close < open), 0.0 otherwise.
///
/// Use with `.above(0.5)` to check for bearish candle.
#[inline]
pub fn is_bearish() -> IsBearish {
    IsBearish
}

/// Reference to relative volume (current volume / average volume over N periods).
///
/// Returns ratio: 1.0 = average, 2.0 = double average, etc.
///
/// # Example
///
/// ```ignore
/// use finance_query::backtesting::refs::*;
///
/// // High volume breakout (volume > 1.5x average)
/// let high_volume = relative_volume(20).above(1.5);
/// ```
#[derive(Debug, Clone)]
pub struct RelativeVolume {
    /// Number of periods for volume average
    pub period: usize,
    key: String,
}

impl IndicatorRef for RelativeVolume {
    fn key(&self) -> &str {
        &self.key
    }

    fn required_indicators(&self) -> Vec<(String, Indicator)> {
        vec![] // We compute from candle history directly
    }

    fn value(&self, ctx: &StrategyContext) -> Option<f64> {
        let candles = &ctx.candles;
        let idx = ctx.index;

        // Need at least `period` candles to compute average
        if idx < self.period {
            return None;
        }

        // Calculate average volume over the last N periods (not including current)
        let avg_volume: f64 = candles[idx.saturating_sub(self.period)..idx]
            .iter()
            .map(|c| c.volume as f64)
            .sum::<f64>()
            / self.period as f64;

        if avg_volume > 0.0 {
            let current_volume = ctx.volume() as f64;
            Some(current_volume / avg_volume)
        } else {
            None
        }
    }

    fn prev_value(&self, ctx: &StrategyContext) -> Option<f64> {
        let candles = &ctx.candles;
        let idx = ctx.index;

        if idx < self.period + 1 {
            return None;
        }

        let prev_idx = idx - 1;
        let avg_volume: f64 = candles[prev_idx.saturating_sub(self.period)..prev_idx]
            .iter()
            .map(|c| c.volume as f64)
            .sum::<f64>()
            / self.period as f64;

        if avg_volume > 0.0 {
            Some(candles[prev_idx].volume as f64 / avg_volume)
        } else {
            None
        }
    }
}

/// Get a reference to relative volume (current volume / N-period average volume).
///
/// # Arguments
///
/// * `period` - Number of periods for the volume average
///
/// # Example
///
/// ```ignore
/// use finance_query::backtesting::refs::*;
///
/// // Volume spike filter
/// let volume_spike = relative_volume(20).above(2.0);
/// ```
#[inline]
pub fn relative_volume(period: usize) -> RelativeVolume {
    RelativeVolume {
        period,
        key: format!("relative_volume_{period}"),
    }
}

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

    #[test]
    fn test_price_keys() {
        assert_eq!(price().key(), "close");
        assert_eq!(close().key(), "close");
        assert_eq!(open().key(), "open");
        assert_eq!(high().key(), "high");
        assert_eq!(low().key(), "low");
        assert_eq!(volume().key(), "volume");
        assert_eq!(typical_price().key(), "typical_price");
        assert_eq!(median_price().key(), "median_price");
    }

    #[test]
    fn test_price_no_indicators_required() {
        assert!(price().required_indicators().is_empty());
        assert!(open().required_indicators().is_empty());
        assert!(high().required_indicators().is_empty());
        assert!(low().required_indicators().is_empty());
        assert!(volume().required_indicators().is_empty());
    }

    #[test]
    fn test_derived_price_keys() {
        assert_eq!(price_change_pct().key(), "price_change_pct");
        assert_eq!(gap_pct().key(), "gap_pct");
        assert_eq!(candle_range().key(), "candle_range");
        assert_eq!(candle_body().key(), "candle_body");
        assert_eq!(is_bullish().key(), "is_bullish");
        assert_eq!(is_bearish().key(), "is_bearish");
    }

    #[test]
    fn test_derived_price_no_indicators_required() {
        assert!(price_change_pct().required_indicators().is_empty());
        assert!(gap_pct().required_indicators().is_empty());
        assert!(candle_range().required_indicators().is_empty());
        assert!(candle_body().required_indicators().is_empty());
        assert!(is_bullish().required_indicators().is_empty());
        assert!(is_bearish().required_indicators().is_empty());
    }

    #[test]
    fn test_relative_volume_key() {
        assert_eq!(relative_volume(20).key(), "relative_volume_20");
        assert_eq!(relative_volume(10).key(), "relative_volume_10");
    }
}