finance-query 2.5.0

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
//! Compile and runtime tests for docs/library/indicators.md
//!
//! Requires the `indicators` feature flag:
//!   cargo test --test doc_indicators --features indicators
//!   cargo test --test doc_indicators --features indicators -- --ignored  (network)
//!   cargo test --test doc_indicators --features "indicators,dataframe" -- --ignored

#![cfg(feature = "indicators")]

// ---------------------------------------------------------------------------
// Compile-time — CandlePattern and PatternSentiment variants
// ---------------------------------------------------------------------------

#[test]
fn test_candle_pattern_variants_compile() {
    use finance_query::indicators::CandlePattern;

    let _ = CandlePattern::MorningStar;
    let _ = CandlePattern::EveningStar;
    let _ = CandlePattern::ThreeWhiteSoldiers;
    let _ = CandlePattern::ThreeBlackCrows;
    let _ = CandlePattern::BullishEngulfing;
    let _ = CandlePattern::BearishEngulfing;
    let _ = CandlePattern::BullishHarami;
    let _ = CandlePattern::BearishHarami;
    let _ = CandlePattern::PiercingLine;
    let _ = CandlePattern::DarkCloudCover;
    let _ = CandlePattern::TweezerBottom;
    let _ = CandlePattern::TweezerTop;
    let _ = CandlePattern::Hammer;
    let _ = CandlePattern::InvertedHammer;
    let _ = CandlePattern::HangingMan;
    let _ = CandlePattern::ShootingStar;
    let _ = CandlePattern::BullishMarubozu;
    let _ = CandlePattern::BearishMarubozu;
    let _ = CandlePattern::Doji;
    let _ = CandlePattern::SpinningTop;
}

#[test]
fn test_pattern_sentiment_variants_compile() {
    use finance_query::indicators::PatternSentiment;

    let _ = PatternSentiment::Bullish;
    let _ = PatternSentiment::Bearish;
}

// ---------------------------------------------------------------------------
// Compile-time — IndicatorsSummary compound data type field access
// ---------------------------------------------------------------------------

#[allow(dead_code)]
fn _verify_indicators_summary_fields(s: finance_query::IndicatorsSummary) {
    // Moving Averages
    let _: Option<f64> = s.sma_10;
    let _: Option<f64> = s.sma_20;
    let _: Option<f64> = s.sma_50;
    let _: Option<f64> = s.sma_100;
    let _: Option<f64> = s.sma_200;
    let _: Option<f64> = s.ema_10;
    let _: Option<f64> = s.ema_20;
    let _: Option<f64> = s.ema_50;
    let _: Option<f64> = s.ema_100;
    let _: Option<f64> = s.ema_200;
    let _: Option<f64> = s.dema_20;
    let _: Option<f64> = s.tema_20;
    let _: Option<f64> = s.hma_20;
    let _: Option<f64> = s.vwma_20;
    let _: Option<f64> = s.alma_9;
    let _: Option<f64> = s.mcginley_dynamic_20;
    // Momentum
    let _: Option<f64> = s.rsi_14;
    let _: Option<f64> = s.cci_20;
    let _: Option<f64> = s.williams_r_14;
    let _: Option<f64> = s.roc_12;
    let _: Option<f64> = s.momentum_10;
    let _: Option<f64> = s.cmo_14;
    let _: Option<f64> = s.awesome_oscillator;
    let _: Option<f64> = s.coppock_curve;
    let _: Option<f64> = s.adx_14;
    let _: Option<f64> = s.parabolic_sar;
    // Volatility
    let _: Option<f64> = s.atr_14;
    let _: Option<f64> = s.true_range;
    let _: Option<f64> = s.choppiness_index_14;
    // Volume
    let _: Option<f64> = s.obv;
    let _: Option<f64> = s.mfi_14;
    let _: Option<f64> = s.cmf_20;
    let _: Option<f64> = s.chaikin_oscillator;
    let _: Option<f64> = s.accumulation_distribution;
    let _: Option<f64> = s.vwap;
    let _: Option<f64> = s.balance_of_power;
}

// ---------------------------------------------------------------------------
// Network tests — Getting Started / Summary API from indicators.md
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires network access"]
async fn test_indicators_getting_started() {
    use finance_query::{Interval, Ticker, TimeRange};

    // From indicators.md "Getting Started" section
    let ticker = Ticker::new("AAPL").await.unwrap();
    let indicators = ticker
        .indicators(Interval::OneDay, TimeRange::ThreeMonths)
        .await
        .unwrap();

    println!("RSI(14): {:?}", indicators.rsi_14);
    println!("SMA(200): {:?}", indicators.sma_200);
    println!("MACD: {:?}", indicators.macd);
}

// ---------------------------------------------------------------------------
// Network tests — Chart Extension Methods from indicators.md
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires network access"]
async fn test_chart_extension_methods() {
    use finance_query::{Interval, Ticker, TimeRange};

    // From indicators.md "Chart Extension Methods" section
    let ticker = Ticker::new("AAPL").await.unwrap();
    let chart = ticker
        .chart(Interval::OneDay, TimeRange::ThreeMonths)
        .await
        .unwrap();

    // Calculate indicators with custom periods
    let sma_15 = chart.sma(15); // Custom period: 15
    let rsi_21 = chart.rsi(21).unwrap(); // Custom period: 21
    let macd = chart.macd(12, 26, 9).unwrap(); // Custom MACD parameters

    // Access the last value
    if let Some(&last_sma) = sma_15.last().and_then(|v| v.as_ref()) {
        println!("Latest SMA(15): {:.2}", last_sma);
    }

    // Candlestick patterns (same chart, no extra request)
    let signals = chart.patterns();

    let _ = rsi_21;
    let _ = macd;
    let _ = signals;
}

// ---------------------------------------------------------------------------
// Network tests — Direct Indicator Functions from indicators.md
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires network access"]
async fn test_direct_indicator_functions() {
    use finance_query::indicators::{macd, rsi, sma};
    use finance_query::{Interval, Ticker, TimeRange};

    // From indicators.md "Direct Indicator Functions" section
    let ticker = Ticker::new("AAPL").await.unwrap();
    let chart = ticker
        .chart(Interval::OneDay, TimeRange::ThreeMonths)
        .await
        .unwrap();

    // Extract price data (convenience methods on Chart)
    let closes: Vec<f64> = chart.close_prices();
    let _highs: Vec<f64> = chart.high_prices();
    let _lows: Vec<f64> = chart.low_prices();

    // Calculate indicators directly
    let sma_25 = sma(&closes, 25); // Returns Vec<Option<f64>>
    let rsi_10 = rsi(&closes, 10).unwrap(); // Returns Result<Vec<Option<f64>>>
    let macd_result = macd(&closes, 12, 26, 9).unwrap(); // Returns Result<MacdResult>

    // Access results
    if let Some(&last_rsi) = rsi_10.last().and_then(|v| v.as_ref()) {
        println!("RSI(10): {:.2}", last_rsi);
    }

    // MACD returns a struct with three series
    if let Some(&last_macd) = macd_result.macd_line.last().and_then(|v| v.as_ref()) {
        println!("MACD Line: {:.4}", last_macd);
    }

    let _ = sma_25;
}

// ---------------------------------------------------------------------------
// Network tests — Compound Indicators from indicators.md
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires network access"]
async fn test_compound_indicators() {
    use finance_query::indicators::{bollinger_bands, macd, stochastic};
    use finance_query::{Interval, Ticker, TimeRange};

    // From indicators.md "Working with Compound Indicators" section
    let ticker = Ticker::new("AAPL").await.unwrap();
    let chart = ticker
        .chart(Interval::OneDay, TimeRange::ThreeMonths)
        .await
        .unwrap();

    let closes = chart.close_prices();
    let highs = chart.high_prices();
    let lows = chart.low_prices();

    // Bollinger Bands - returns BollingerBands struct
    let bb = bollinger_bands(&closes, 20, 2.0).unwrap();
    if let Some(&upper) = bb.upper.last().and_then(|v| v.as_ref())
        && let Some(&middle) = bb.middle.last().and_then(|v| v.as_ref())
        && let Some(&lower) = bb.lower.last().and_then(|v| v.as_ref())
    {
        println!(
            "BB: Upper={:.2}, Middle={:.2}, Lower={:.2}",
            upper, middle, lower
        );
    }

    // Stochastic Oscillator - returns StochasticResult struct
    let stoch = stochastic(&highs, &lows, &closes, 14, 1, 3).unwrap();
    if let Some(&k) = stoch.k.last().and_then(|v| v.as_ref())
        && let Some(&d) = stoch.d.last().and_then(|v| v.as_ref())
    {
        println!("Stochastic: %K={:.2}, %D={:.2}", k, d);
    }

    // MACD - returns MacdResult struct
    let macd_data = macd(&closes, 12, 26, 9).unwrap();
    if let Some(&line) = macd_data.macd_line.last().and_then(|v| v.as_ref())
        && let Some(&signal) = macd_data.signal_line.last().and_then(|v| v.as_ref())
        && let Some(&hist) = macd_data.histogram.last().and_then(|v| v.as_ref())
    {
        println!(
            "MACD: Line={:.4}, Signal={:.4}, Histogram={:.4}",
            line, signal, hist
        );
    }
}

// ---------------------------------------------------------------------------
// Network tests — Candlestick Patterns from indicators.md
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires network access"]
async fn test_candlestick_patterns_via_chart() {
    use finance_query::indicators::{CandlePattern, PatternSentiment, patterns};
    use finance_query::{Interval, Ticker, TimeRange};

    // From indicators.md "Candlestick Patterns" section
    let ticker = Ticker::new("AAPL").await.unwrap();
    let chart = ticker
        .chart(Interval::OneDay, TimeRange::ThreeMonths)
        .await
        .unwrap();

    // Via Chart extension method — same length as chart.candles
    let signals = chart.patterns();

    // Or call the function directly with a candle slice
    let _signals2 = patterns(&chart.candles);

    // Each slot is Some(pattern) or None; iterate with candles for context
    for (candle, pattern) in chart.candles.iter().zip(signals.iter()) {
        if let Some(p) = pattern {
            println!(
                "timestamp={}: {:?} ({:?})",
                candle.timestamp,
                p,
                p.sentiment()
            );
        }
    }

    let _ = CandlePattern::Doji; // confirm variant access
    let _ = PatternSentiment::Bullish; // confirm variant access
}

// ---------------------------------------------------------------------------
// Network tests — PatternSentiment from indicators.md
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires network access"]
async fn test_pattern_sentiment_filtering() {
    use finance_query::indicators::PatternSentiment;
    use finance_query::{Interval, Ticker, TimeRange};

    // From indicators.md "Using PatternSentiment" section
    let ticker = Ticker::new("AAPL").await.unwrap();
    let chart = ticker
        .chart(Interval::OneDay, TimeRange::ThreeMonths)
        .await
        .unwrap();
    let signals = chart.patterns();

    let bullish = signals
        .iter()
        .filter(|s| {
            s.map(|p| p.sentiment() == PatternSentiment::Bullish)
                .unwrap_or(false)
        })
        .count();

    let bearish = signals
        .iter()
        .filter(|s| {
            s.map(|p| p.sentiment() == PatternSentiment::Bearish)
                .unwrap_or(false)
        })
        .count();

    println!("Bull/Bear ratio: {}/{}", bullish, bearish);
}

// ---------------------------------------------------------------------------
// Network tests — Combining Patterns with Indicators from indicators.md
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires network access"]
async fn test_patterns_combined_with_indicators() {
    use finance_query::indicators::PatternSentiment;
    use finance_query::{Interval, Ticker, TimeRange};

    // From indicators.md "Combining Patterns with Indicators" section
    let ticker = Ticker::new("AAPL").await.unwrap();
    let chart = ticker
        .chart(Interval::OneDay, TimeRange::ThreeMonths)
        .await
        .unwrap();
    let rsi = chart.rsi(14).unwrap();
    let signals = chart.patterns();

    // Find bars where RSI is oversold AND a bullish pattern just completed
    for (i, (pattern, rsi_val)) in signals.iter().zip(rsi.iter()).enumerate() {
        let is_bullish_pattern = pattern
            .map(|p| p.sentiment() == PatternSentiment::Bullish)
            .unwrap_or(false);
        let is_oversold = rsi_val.map(|r| r < 30.0).unwrap_or(false);

        if is_bullish_pattern && is_oversold {
            println!(
                "Strong buy signal at bar {}: {:?} with RSI={:.1}",
                i,
                pattern.unwrap(),
                rsi_val.unwrap()
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Network tests — Working with Indicator Results from indicators.md
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires network access"]
async fn test_indicator_results_compound_types() {
    use finance_query::{Interval, Ticker, TimeRange};

    // From indicators.md "Working with Indicator Results" section
    let ticker = Ticker::new("AAPL").await.unwrap();
    let indicators = ticker
        .indicators(Interval::OneDay, TimeRange::ThreeMonths)
        .await
        .unwrap();

    // Simple indicators (Option<f64>)
    if let Some(rsi) = indicators.rsi_14 {
        println!("RSI(14): {:.2}", rsi);
        if rsi < 30.0 {
            println!("  Oversold");
        } else if rsi > 70.0 {
            println!("  Overbought");
        }
    }

    // Moving averages
    if let Some(sma200) = indicators.sma_200 {
        println!("SMA(200): {:.2}", sma200);
    }

    // MACD (compound - MacdData struct)
    if let Some(macd) = indicators.macd {
        if let Some(line) = macd.macd {
            println!("MACD Line: {:.4}", line);
        }
        if let Some(signal) = macd.signal {
            println!("Signal: {:.4}", signal);
        }
        if let Some(histogram) = macd.histogram {
            println!("Histogram: {:.4}", histogram);
        }
    }

    // Stochastic (StochasticData struct)
    if let Some(stoch) = indicators.stochastic {
        if let Some(k) = stoch.k {
            println!("%K: {:.2}", k);
        }
        if let Some(d) = stoch.d {
            println!("%D: {:.2}", d);
        }
    }

    // Bollinger Bands (BollingerBandsData struct)
    if let Some(bb) = indicators.bollinger_bands {
        if let Some(upper) = bb.upper {
            println!("Upper: {:.2}", upper);
        }
        if let Some(middle) = bb.middle {
            println!("Middle: {:.2}", middle);
        }
        if let Some(lower) = bb.lower {
            println!("Lower: {:.2}", lower);
        }
    }

    // Aroon (AroonData struct)
    if let Some(aroon) = indicators.aroon {
        if let Some(up) = aroon.aroon_up {
            println!("Aroon Up: {:.2}", up);
        }
        if let Some(down) = aroon.aroon_down {
            println!("Aroon Down: {:.2}", down);
        }
    }

    // Ichimoku (IchimokuData struct)
    if let Some(ichimoku) = indicators.ichimoku {
        if let Some(conversion) = ichimoku.conversion_line {
            println!("Conversion Line: {:.2}", conversion);
        }
        if let Some(base) = ichimoku.base_line {
            println!("Base Line: {:.2}", base);
        }
    }
}

// ---------------------------------------------------------------------------
// Network tests — DataFrame conversion from indicators.md (dataframe feature)
// ---------------------------------------------------------------------------

#[cfg(feature = "dataframe")]
#[tokio::test]
#[ignore = "requires network access"]
async fn test_indicators_to_dataframe() {
    use finance_query::{Interval, Ticker, TimeRange};

    // From indicators.md "Converting to DataFrame" section
    let ticker = Ticker::new("AAPL").await.unwrap();
    let indicators = ticker
        .indicators(Interval::OneDay, TimeRange::ThreeMonths)
        .await
        .unwrap();

    let df = indicators.to_dataframe().unwrap();
    println!("{}", df);
    assert!(df.height() > 0 || df.width() > 0);
}

// ---------------------------------------------------------------------------
// Network tests — Caching Behavior from indicators.md
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires network access"]
async fn test_indicators_caching() {
    use finance_query::{Interval, Ticker, TimeRange};

    // From indicators.md "Caching Behavior" section
    let ticker = Ticker::new("AAPL").await.unwrap();

    // First call fetches and caches
    let ind1 = ticker
        .indicators(Interval::OneDay, TimeRange::OneMonth)
        .await
        .unwrap();

    // Second call returns cached result
    let ind2 = ticker
        .indicators(Interval::OneDay, TimeRange::OneMonth)
        .await
        .unwrap();

    // Different range: fetches new data
    let ind3 = ticker
        .indicators(Interval::OneDay, TimeRange::ThreeMonths)
        .await
        .unwrap();

    let _ = ind1;
    let _ = ind2;
    let _ = ind3;
}

// ---------------------------------------------------------------------------
// Network tests — Common Patterns from indicators.md
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires network access"]
async fn test_trend_confirmation_with_multiple_mas() {
    use finance_query::{Interval, Ticker, TimeRange};

    // From indicators.md "Trend Confirmation with Multiple MAs" section
    let ticker = Ticker::new("AAPL").await.unwrap();
    let indicators = ticker
        .indicators(Interval::OneDay, TimeRange::OneYear)
        .await
        .unwrap();

    let sma_200 = indicators.sma_200.unwrap_or(0.0);
    let ema_50 = indicators.ema_50.unwrap_or(0.0);
    let ema_20 = indicators.ema_20.unwrap_or(0.0);

    if ema_20 > ema_50 && ema_50 > sma_200 {
        println!("Uptrend confirmed");
    }

    println!(
        "SMA(200): {:.2}, EMA(50): {:.2}, EMA(20): {:.2}",
        sma_200, ema_50, ema_20
    );
}

#[tokio::test]
#[ignore = "requires network access"]
async fn test_rsi_extremes() {
    use finance_query::{Interval, Ticker, TimeRange};

    // From indicators.md "RSI Extremes" section
    let ticker = Ticker::new("AAPL").await.unwrap();
    let indicators = ticker
        .indicators(Interval::OneDay, TimeRange::ThreeMonths)
        .await
        .unwrap();

    if let Some(rsi) = indicators.rsi_14 {
        if rsi < 30.0 {
            println!("Oversold");
        } else if rsi > 70.0 {
            println!("Overbought");
        }
        println!("RSI: {:.2}", rsi);
    }
}

#[tokio::test]
#[ignore = "requires network access"]
async fn test_macd_crossover() {
    use finance_query::{Interval, Ticker, TimeRange};

    // From indicators.md "MACD Crossover" section
    let ticker = Ticker::new("AAPL").await.unwrap();
    let indicators = ticker
        .indicators(Interval::OneDay, TimeRange::ThreeMonths)
        .await
        .unwrap();

    if let Some(macd) = indicators.macd
        && let (Some(line), Some(signal)) = (macd.macd, macd.signal)
    {
        if line > signal {
            println!("Bullish MACD crossover");
        } else {
            println!("Bearish MACD crossover");
        }
    }
}

// ---------------------------------------------------------------------------
// Network tests — Best Practices pattern from indicators.md
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "requires network access"]
async fn test_indicators_best_practices_pattern() {
    use finance_query::{Interval, Ticker, TimeRange};

    // From indicators.md "Best Practices" section — store result once
    let ticker = Ticker::new("AAPL").await.unwrap();
    let indicators = ticker
        .indicators(Interval::OneDay, TimeRange::ThreeMonths)
        .await
        .unwrap();

    if let Some(rsi) = indicators.rsi_14
        && rsi < 30.0
    {
        // Oversold - check other indicators from same result
        if let Some(ref macd) = indicators.macd
            && let (Some(line), Some(signal)) = (macd.macd, macd.signal)
            && line > signal
        {
            println!("Potential buy: RSI oversold + MACD bullish");
        }
    }
}