finalytics 0.9.0

A rust library for financial data analysis
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::data::ticker::TickerData;
use crate::error::{series_to_vec_f64, FinalyticsError};
use crate::models::ticker::Ticker;
use chrono::{DateTime, NaiveDateTime};
use polars::prelude::*;
use std::error::Error;
use ta::indicators::*;
use ta::{DataItem, Next};

/// Enum of OHLCV DataFrame Columns
pub enum Column {
    Open,
    High,
    Low,
    Close,
    Volume,
    AdjClose,
}

impl Column {
    pub fn as_str(&self) -> &'static str {
        match *self {
            Column::Open => "open",
            Column::High => "high",
            Column::Low => "low",
            Column::Close => "close",
            Column::Volume => "volume",
            Column::AdjClose => "adjclose",
        }
    }

    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Column {
        match s {
            "open" => Column::Open,
            "high" => Column::High,
            "low" => Column::Low,
            "close" => Column::Close,
            "volume" => Column::Volume,
            "adjclose" => Column::AdjClose,
            _ => Column::Close,
        }
    }
}

pub trait TechnicalIndicators {
    fn sma(
        &self,
        period: usize,
        col: Option<Column>,
    ) -> impl std::future::Future<Output = Result<DataFrame, Box<dyn Error>>>;
    fn ema(
        &self,
        period: usize,
        col: Option<Column>,
    ) -> impl std::future::Future<Output = Result<DataFrame, Box<dyn Error>>>;
    fn rsi(
        &self,
        period: usize,
        col: Option<Column>,
    ) -> impl std::future::Future<Output = Result<DataFrame, Box<dyn Error>>>;
    fn macd(
        &self,
        fast_period: usize,
        slow_period: usize,
        signal_period: usize,
        col: Option<Column>,
    ) -> impl std::future::Future<Output = Result<DataFrame, Box<dyn Error>>>;
    fn ppo(
        &self,
        fast_period: usize,
        slow_period: usize,
        signal_period: usize,
        col: Option<Column>,
    ) -> impl std::future::Future<Output = Result<DataFrame, Box<dyn Error>>>;
    fn mfi(
        &self,
        period: usize,
    ) -> impl std::future::Future<Output = Result<DataFrame, Box<dyn Error>>>;
    fn bb(
        &self,
        period: usize,
        std_dev: f64,
        col: Option<Column>,
    ) -> impl std::future::Future<Output = Result<DataFrame, Box<dyn Error>>>;
    fn fs(
        &self,
        period: usize,
        col: Option<Column>,
    ) -> impl std::future::Future<Output = Result<DataFrame, Box<dyn Error>>>;
    fn ss(
        &self,
        stochastic_period: usize,
        ema_period: usize,
        col: Option<Column>,
    ) -> impl std::future::Future<Output = Result<DataFrame, Box<dyn Error>>>;
    fn sd(
        &self,
        period: usize,
        col: Option<Column>,
    ) -> impl std::future::Future<Output = Result<DataFrame, Box<dyn Error>>>;
    fn mad(
        &self,
        period: usize,
        col: Option<Column>,
    ) -> impl std::future::Future<Output = Result<DataFrame, Box<dyn Error>>>;
    fn max(
        &self,
        period: usize,
        col: Option<Column>,
    ) -> impl std::future::Future<Output = Result<DataFrame, Box<dyn Error>>>;
    fn min(
        &self,
        period: usize,
        col: Option<Column>,
    ) -> impl std::future::Future<Output = Result<DataFrame, Box<dyn Error>>>;
    fn atr(
        &self,
        period: usize,
    ) -> impl std::future::Future<Output = Result<DataFrame, Box<dyn Error>>>;
    fn roc(
        &self,
        period: usize,
        col: Option<Column>,
    ) -> impl std::future::Future<Output = Result<DataFrame, Box<dyn Error>>>;
    fn obv(&self) -> impl std::future::Future<Output = Result<DataFrame, Box<dyn Error>>>;
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Extract a `Vec<f64>` from an OHLCV DataFrame column by name, using the
/// safe `series_to_vec_f64` helper so we never panic on dtype/null issues.
fn extract_f64_col(df: &DataFrame, col_name: &str) -> Result<Vec<f64>, Box<dyn Error>> {
    let col = df.column(col_name)?;
    let s = col.as_materialized_series();
    Ok(series_to_vec_f64(s, col_name)?)
}

/// Extract the timestamp column as a `Series` clone suitable for building a
/// new DataFrame. Returns an error instead of panicking.
fn extract_series_col(df: &DataFrame, col_name: &str) -> Result<Series, Box<dyn Error>> {
    let col = df.column(col_name)?;
    Ok(col.as_materialized_series().clone())
}

/// Extract the timestamp column as `Vec<NaiveDateTime>`, safely handling
/// potential null values.
fn extract_timestamps(df: &DataFrame) -> Result<Vec<NaiveDateTime>, Box<dyn Error>> {
    let ts_col = df.column("timestamp")?;
    let ca = ts_col.datetime().map_err(|e| -> Box<dyn Error> {
        Box::new(FinalyticsError::DtypeMismatch {
            column: "timestamp".into(),
            expected: "Datetime".into(),
            actual: format!("{:?} — {e}", ts_col.dtype()),
        })
    })?;
    let mut out = Vec::with_capacity(ca.len());
    for opt in ca.into_iter() {
        let millis = opt.ok_or_else(|| -> Box<dyn Error> {
            Box::new(FinalyticsError::NullValues {
                column: "timestamp".into(),
                null_count: 1,
            })
        })?;
        let dt = DateTime::from_timestamp_millis(millis)
            .ok_or_else(|| -> Box<dyn Error> {
                Box::new(FinalyticsError::DataParse {
                    source: "timestamp".into(),
                    message: format!("Cannot convert millis {millis} to DateTime"),
                })
            })?
            .naive_local();
        out.push(dt);
    }
    Ok(out)
}

/// Create a `ta` indicator, mapping the `Result` from `::new()` into our
/// `Box<dyn Error>`.
macro_rules! new_indicator {
    ($ty:ty, $($arg:expr),+ $(,)?) => {{
        <$ty>::new($($arg),+).map_err(|e| -> Box<dyn Error> {
            Box::new(FinalyticsError::InvalidParameter {
                name: stringify!($ty).into(),
                message: format!("Failed to create indicator: {e}"),
            })
        })
    }};
}

/// Build an OHLCV `DataItem` vec together with sanitised parallel vecs
/// (timestamps, open, high, low, close, volume). Rows where the `DataItem`
/// cannot be built are dropped from **all** vectors so they stay aligned.
fn build_data_items(
    timestamps: &[NaiveDateTime],
    open: &[f64],
    high: &[f64],
    low: &[f64],
    close: &[f64],
    volume: &[f64],
) -> (
    Vec<NaiveDateTime>,
    Vec<f64>,
    Vec<f64>,
    Vec<f64>,
    Vec<f64>,
    Vec<f64>,
    Vec<DataItem>,
) {
    let mut ts_out = Vec::with_capacity(close.len());
    let mut o_out = Vec::with_capacity(close.len());
    let mut h_out = Vec::with_capacity(close.len());
    let mut l_out = Vec::with_capacity(close.len());
    let mut c_out = Vec::with_capacity(close.len());
    let mut v_out = Vec::with_capacity(close.len());
    let mut items = Vec::with_capacity(close.len());

    for i in 0..close.len() {
        match DataItem::builder()
            .high(high[i])
            .low(low[i])
            .close(close[i])
            .open(open[i])
            .volume(volume[i])
            .build()
        {
            Ok(di) => {
                ts_out.push(timestamps[i]);
                o_out.push(open[i]);
                h_out.push(high[i]);
                l_out.push(low[i]);
                c_out.push(close[i]);
                v_out.push(volume[i]);
                items.push(di);
            }
            Err(_) => {
                eprintln!("Skipping row {i}: invalid DataItem");
            }
        }
    }

    (ts_out, o_out, h_out, l_out, c_out, v_out, items)
}

impl TechnicalIndicators for Ticker {
    /// Generates a Dataframe of the ticker price data with the Simple Moving Average Indicator
    ///
    /// # Arguments
    ///
    /// * `period` - Period for the Simple Moving Average Indicator (e.g., 50)
    /// * `col` - Column for the Simple Moving Average Indicator (e.g., Column::Close)
    ///
    /// # Returns
    ///
    /// * `DataFrame` of the ticker price data with the Simple Moving Average Indicator
    async fn sma(&self, period: usize, col: Option<Column>) -> Result<DataFrame, Box<dyn Error>> {
        let ohlcv = self.get_chart().await?;
        let mut sma = new_indicator!(SimpleMovingAverage, period)?;
        let col_str = match col {
            Some(col) => col.as_str(),
            None => Column::Close.as_str(),
        };
        let col_val = extract_f64_col(&ohlcv, col_str)?;
        let col_name = format!("sma-{period}");
        let sma_series = Series::new(
            col_name.as_str().into(),
            col_val.iter().map(|x| sma.next(*x)).collect::<Vec<f64>>(),
        );
        let mut df = df!(
            "timestamp" => extract_series_col(&ohlcv, "timestamp")?,
            col_str => extract_series_col(&ohlcv, col_str)?,
        )?;
        let df = df.with_column(sma_series)?.clone();
        Ok(df)
    }

    /// Generates a Dataframe of the ticker price data with the Exponential Moving Average Indicator
    ///
    /// # Arguments
    ///
    /// * `period` - Period for the Exponential Moving Average Indicator (e.g., 3)
    /// * `col` - Column for the Exponential Moving Average Indicator (default - Column::Close)
    ///
    /// # Returns
    ///
    /// * `DataFrame` of the ticker price data with the Exponential Moving Average Indicator
    async fn ema(&self, period: usize, col: Option<Column>) -> Result<DataFrame, Box<dyn Error>> {
        let ohlcv = self.get_chart().await?;
        let mut ema = new_indicator!(ExponentialMovingAverage, period)?;
        let col_str = match col {
            Some(col) => col.as_str(),
            None => Column::Close.as_str(),
        };
        let col_val = extract_f64_col(&ohlcv, col_str)?;
        let col_name = format!("ema-{period}");
        let ema_series = Series::new(
            col_name.as_str().into(),
            col_val.iter().map(|x| ema.next(*x)).collect::<Vec<f64>>(),
        );
        let mut df = df!(
            "timestamp" => extract_series_col(&ohlcv, "timestamp")?,
            col_str => extract_series_col(&ohlcv, col_str)?,
        )?;
        let df = df.with_column(ema_series)?.clone();
        Ok(df)
    }

    /// Generates a Dataframe of the ticker price data with the Relative Strength Index Indicator
    ///
    /// # Arguments
    ///
    /// * `period` - Period for the Relative Strength Index Indicator (e.g., 14)
    /// * `col` - Column for the Relative Strength Index Indicator (default - Column::Close)
    ///
    /// # Returns
    ///
    /// * `DataFrame` of the ticker price data with the Relative Strength Index Indicator
    async fn rsi(&self, period: usize, col: Option<Column>) -> Result<DataFrame, Box<dyn Error>> {
        let ohlcv = self.get_chart().await?;
        let mut rsi = new_indicator!(RelativeStrengthIndex, period)?;
        let col_str = match col {
            Some(col) => col.as_str(),
            None => Column::Close.as_str(),
        };
        let col_val = extract_f64_col(&ohlcv, col_str)?;
        let col_name = format!("rsi-{period}");
        let rsi_series = Series::new(
            col_name.as_str().into(),
            col_val.iter().map(|x| rsi.next(*x)).collect::<Vec<f64>>(),
        );
        let mut df = df!(
            "timestamp" => extract_series_col(&ohlcv, "timestamp")?,
            col_str => extract_series_col(&ohlcv, col_str)?,
        )?;
        let df = df.with_column(rsi_series)?.clone();
        Ok(df)
    }

    /// Generates a Dataframe of the ticker price data with the Moving Average Convergence Divergence Indicators
    ///
    /// # Arguments
    ///
    /// * `fast_period` - Fast period for the Moving Average Convergence Divergence Indicator (e.g., 12)
    /// * `slow_period` - Slow period for the Moving Average Convergence Divergence Indicator (e.g., 26)
    /// * `signal_period` - Signal period for the Moving Average Convergence Divergence Indicator (e.g., 9)
    /// * `col` - Column for the Moving Average Convergence Divergence Indicator (default - Column::Close)
    ///
    /// # Returns
    ///
    /// * `DataFrame` of the ticker price data with the Moving Average Convergence Divergence Indicators
    async fn macd(
        &self,
        fast_period: usize,
        slow_period: usize,
        signal_period: usize,
        col: Option<Column>,
    ) -> Result<DataFrame, Box<dyn Error>> {
        let ohlcv = self.get_chart().await?;
        let col_str = match col {
            Some(col) => col.as_str(),
            None => Column::Close.as_str(),
        };
        let col_val = extract_f64_col(&ohlcv, col_str)?;
        let mut macd = new_indicator!(
            MovingAverageConvergenceDivergence,
            fast_period,
            slow_period,
            signal_period
        )?;
        let macd_str = format!("macd-({fast_period},{slow_period},{signal_period})");
        let signal_str = format!("macd_signal-({fast_period},{slow_period},{signal_period})");
        let divergence_str =
            format!("macd_divergence-({fast_period},{slow_period},{signal_period})");
        let all_series: Vec<MovingAverageConvergenceDivergenceOutput> =
            col_val.iter().map(|x| macd.next(*x)).collect();
        let df = df!(
            "timestamp" => extract_series_col(&ohlcv, "timestamp")?,
            col_str => extract_series_col(&ohlcv, col_str)?,
            macd_str.as_str() => all_series.iter().map(|x| x.macd).collect::<Vec<f64>>(),
            signal_str.as_str() => all_series.iter().map(|x| x.signal).collect::<Vec<f64>>(),
            divergence_str.as_str() => all_series.iter().map(|x| x.histogram).collect::<Vec<f64>>()
        )?;
        Ok(df)
    }

    /// Generates a Dataframe of the ticker price data with the Percentage Price Oscillator Indicators
    ///
    /// # Arguments
    ///
    /// * `fast_period` - Fast period for the Percentage Price Oscillator Indicator (e.g., 12)
    /// * `slow_period` - Slow period for the Percentage Price Oscillator Indicator (e.g., 26)
    /// * `signal_period` - Signal period for the Percentage Price Oscillator Indicator (e.g., 9)
    /// * `col` - Column for the Percentage Price Oscillator Indicator (default - Column::Close)
    ///
    /// # Returns
    ///
    /// * `DataFrame` of the ticker price data with the Percentage Price Oscillator Indicators
    async fn ppo(
        &self,
        fast_period: usize,
        slow_period: usize,
        signal_period: usize,
        col: Option<Column>,
    ) -> Result<DataFrame, Box<dyn Error>> {
        let ohlcv = self.get_chart().await?;
        let col_str = match col {
            Some(col) => col.as_str(),
            None => Column::Close.as_str(),
        };
        let col_val = extract_f64_col(&ohlcv, col_str)?;
        let mut ppo = new_indicator!(
            PercentagePriceOscillator,
            fast_period,
            slow_period,
            signal_period
        )?;
        let ppo_str = format!("ppo-({fast_period},{slow_period},{signal_period})");
        let signal_str = format!("ppo_signal-({fast_period},{slow_period},{signal_period})");
        let divergence_str =
            format!("ppo_divergence-({fast_period},{slow_period},{signal_period})");
        let all_series: Vec<PercentagePriceOscillatorOutput> =
            col_val.iter().map(|x| ppo.next(*x)).collect();
        let df = df!(
            "timestamp" => extract_series_col(&ohlcv, "timestamp")?,
            col_str => extract_series_col(&ohlcv, col_str)?,
            ppo_str.as_str() => all_series.iter().map(|x| x.ppo).collect::<Vec<f64>>(),
            signal_str.as_str() => all_series.iter().map(|x| x.signal).collect::<Vec<f64>>(),
            divergence_str.as_str() => all_series.iter().map(|x| x.histogram).collect::<Vec<f64>>()
        )?;
        Ok(df)
    }

    /// Generates a Dataframe of the OHLCV data with the Money Flow Index Indicator
    ///
    /// # Arguments
    ///
    /// * `period` - Period for the Money Flow Index Indicator (e.g., 14)
    ///
    /// # Returns
    ///
    /// * `DataFrame` of the OHLCV data with the Money Flow Index Indicator
    async fn mfi(&self, period: usize) -> Result<DataFrame, Box<dyn Error>> {
        let ohlcv = self.get_chart().await?;
        let mut mfi = new_indicator!(MoneyFlowIndex, period)?;
        let timestamp = extract_timestamps(&ohlcv)?;
        let open = extract_f64_col(&ohlcv, "open")?;
        let high = extract_f64_col(&ohlcv, "high")?;
        let low = extract_f64_col(&ohlcv, "low")?;
        let close = extract_f64_col(&ohlcv, "close")?;
        let volume = extract_f64_col(&ohlcv, "volume")?;

        let (ts, o, h, l, c, v, data_items) =
            build_data_items(&timestamp, &open, &high, &low, &close, &volume);

        let col_name = format!("mfi-{period}");
        let df = df!(
            "timestamp" => ts,
            "open" => o,
            "high" => h,
            "low" => l,
            "close" => c,
            "volume" => v,
            col_name.as_str() => data_items.iter().map(|x| mfi.next(x)).collect::<Vec<f64>>()
        )?;
        Ok(df)
    }

    /// Generates a Dataframe of the ticker price data with Bollinger Bands
    ///
    /// # Arguments
    ///
    /// * `period` - Period for the Bollinger Bands (e.g., 20)
    /// * `std_dev` - Standard deviation for the Bollinger Bands (e.g., 2.0)
    /// * `col` - Column for the Bollinger Bands (default - Column::Close)
    ///
    /// # Returns
    ///
    /// * `DataFrame` of the ticker price data with Bollinger Bands
    async fn bb(
        &self,
        period: usize,
        std_dev: f64,
        col: Option<Column>,
    ) -> Result<DataFrame, Box<dyn Error>> {
        let ohlcv = self.get_chart().await?;
        let col_str = match col {
            Some(col) => col.as_str(),
            None => Column::Close.as_str(),
        };
        let col_val = extract_f64_col(&ohlcv, col_str)?;
        let mut bb = new_indicator!(BollingerBands, period, std_dev)?;
        let bb_str = format!("bb-({period},{std_dev})");
        let upper_str = format!("bb_upper-({period},{std_dev})");
        let lower_str = format!("bb_lower-({period},{std_dev})");
        let all_series: Vec<BollingerBandsOutput> = col_val.iter().map(|x| bb.next(*x)).collect();
        let df = df!(
            "timestamp" => extract_series_col(&ohlcv, "timestamp")?,
            col_str => extract_series_col(&ohlcv, col_str)?,
            bb_str.as_str() => all_series.iter().map(|x| x.average).collect::<Vec<f64>>(),
            upper_str.as_str() => all_series.iter().map(|x| x.upper).collect::<Vec<f64>>(),
            lower_str.as_str() => all_series.iter().map(|x| x.lower).collect::<Vec<f64>>()
        )?;
        Ok(df)
    }

    /// Generates a Dataframe of the ticker price data with the Fast Stochastic Oscillator
    ///
    /// # Arguments
    ///
    /// * `period` - Period for the Fast Stochastic Oscillator (e.g., 14)
    /// * `col` - Column for the Fast Stochastic Oscillator (default - Column::Close)
    ///
    /// # Returns
    ///
    /// * `DataFrame` of the ticker price data with the Fast Stochastic Oscillator
    async fn fs(&self, period: usize, col: Option<Column>) -> Result<DataFrame, Box<dyn Error>> {
        let ohlcv = self.get_chart().await?;
        let col_str = match col {
            Some(col) => col.as_str(),
            None => Column::Close.as_str(),
        };
        let col_val = extract_f64_col(&ohlcv, col_str)?;
        let mut fs = new_indicator!(FastStochastic, period)?;
        let col_name = format!("fs-{period}");
        let fs_series = Series::new(
            col_name.as_str().into(),
            col_val.iter().map(|x| fs.next(*x)).collect::<Vec<f64>>(),
        );
        let mut df = df!(
            "timestamp" => extract_series_col(&ohlcv, "timestamp")?,
            col_str => extract_series_col(&ohlcv, col_str)?,
        )?;
        let df = df.with_column(fs_series)?.clone();
        Ok(df)
    }

    /// Generates a Dataframe of the ticker price data with the Slow Stochastic Oscillator
    ///
    /// # Arguments
    ///
    /// * `stochastic_period` - Stochastic period for the Slow Stochastic Oscillator (e.g., 7)
    /// * `ema_period` - Exponential Moving Average period for the Slow Stochastic Oscillator (e.g., 3)
    /// * `col` - Column for the Slow Stochastic Oscillator (default - Column::Close)
    ///
    /// # Returns
    ///
    /// * `DataFrame` of the ticker price data with the Slow Stochastic Oscillator
    async fn ss(
        &self,
        stochastic_period: usize,
        ema_period: usize,
        col: Option<Column>,
    ) -> Result<DataFrame, Box<dyn Error>> {
        let ohlcv = self.get_chart().await?;
        let col_str = match col {
            Some(col) => col.as_str(),
            None => Column::Close.as_str(),
        };
        let col_val = extract_f64_col(&ohlcv, col_str)?;
        let mut ss = new_indicator!(SlowStochastic, stochastic_period, ema_period)?;
        let col_name = format!("ss-({stochastic_period},{ema_period}`)");
        let ss_series = Series::new(
            col_name.as_str().into(),
            col_val.iter().map(|x| ss.next(*x)).collect::<Vec<f64>>(),
        );
        let mut df = df!(
            "timestamp" => extract_series_col(&ohlcv, "timestamp")?,
            col_str => extract_series_col(&ohlcv, col_str)?,
        )?;
        let df = df.with_column(ss_series)?.clone();
        Ok(df)
    }

    /// Generates a Dataframe of the ticker price data with rolling Standard Deviation
    ///
    /// # Arguments
    ///
    /// * `period` - Period for the rolling Standard Deviation (e.g., 20)
    /// * `col` - Column for the rolling Standard Deviation (default - Column::Close)
    ///
    /// # Returns
    ///
    /// * `DataFrame` of the ticker price data with rolling Standard Deviation
    async fn sd(&self, period: usize, col: Option<Column>) -> Result<DataFrame, Box<dyn Error>> {
        let ohlcv = self.get_chart().await?;
        let col_str = match col {
            Some(col) => col.as_str(),
            None => Column::Close.as_str(),
        };
        let col_val = extract_f64_col(&ohlcv, col_str)?;
        let mut sd = new_indicator!(StandardDeviation, period)?;
        let col_name = format!("sd-{period}");
        let sd_series = Series::new(
            col_name.as_str().into(),
            col_val.iter().map(|x| sd.next(*x)).collect::<Vec<f64>>(),
        );
        let mut df = df!(
            "timestamp" => extract_series_col(&ohlcv, "timestamp")?,
            col_str => extract_series_col(&ohlcv, col_str)?,
        )?;
        let df = df.with_column(sd_series)?.clone();
        Ok(df)
    }

    /// Generates a Dataframe of the ticker price data with rolling Mean Absolute Deviation
    ///
    /// # Arguments
    ///
    /// * `period` - Period for the rolling Mean Absolute Deviation (e.g., 20)
    /// * `col` - Column for the rolling Mean Absolute Deviation (default - Column::Close)
    ///
    /// # Returns
    ///
    /// * `DataFrame` of the ticker price data with rolling Mean Absolute Deviation
    async fn mad(&self, period: usize, col: Option<Column>) -> Result<DataFrame, Box<dyn Error>> {
        let ohlcv = self.get_chart().await?;
        let col_str = match col {
            Some(col) => col.as_str(),
            None => Column::Close.as_str(),
        };
        let col_val = extract_f64_col(&ohlcv, col_str)?;
        let mut mad = new_indicator!(MeanAbsoluteDeviation, period)?;
        let col_name = format!("mad-{period}");
        let mad_series = Series::new(
            col_name.as_str().into(),
            col_val.iter().map(|x| mad.next(*x)).collect::<Vec<f64>>(),
        );
        let mut df = df!(
            "timestamp" => extract_series_col(&ohlcv, "timestamp")?,
            col_str => extract_series_col(&ohlcv, col_str)?,
        )?;
        let df = df.with_column(mad_series)?.clone();
        Ok(df)
    }

    /// Generates a Dataframe of the ticker price data with rolling Maximum Values
    ///
    /// # Arguments
    ///
    /// * `period` - Period for the rolling Maximum Values (e.g., 20)
    /// * `col` - Column for the rolling Maximum Values (default - Column::High)
    ///
    /// # Returns
    ///
    /// * `DataFrame` of the ticker price data with rolling Maximum Values
    async fn max(&self, period: usize, col: Option<Column>) -> Result<DataFrame, Box<dyn Error>> {
        let ohlcv = self.get_chart().await?;
        let col_str = match col {
            Some(col) => col.as_str(),
            None => Column::High.as_str(),
        };
        let col_val = extract_f64_col(&ohlcv, col_str)?;
        let mut max = new_indicator!(Maximum, period)?;
        let col_name = format!("max-{period}");
        let max_series = Series::new(
            col_name.as_str().into(),
            col_val.iter().map(|x| max.next(*x)).collect::<Vec<f64>>(),
        );
        let mut df = df!(
            "timestamp" => extract_series_col(&ohlcv, "timestamp")?,
            col_str => extract_series_col(&ohlcv, col_str)?,
        )?;
        let df = df.with_column(max_series)?.clone();
        Ok(df)
    }

    /// Generates a Dataframe of the ticker price data with rolling Minimum Values
    ///
    /// # Arguments
    ///
    /// * `period` - Period for the rolling Minimum Values (e.g., 20)
    /// * `col` - Column for the rolling Minimum Values (default - Column::Low)
    ///
    /// # Returns
    ///
    /// * `DataFrame` of the ticker price date data with rolling Minimum Values
    async fn min(&self, period: usize, col: Option<Column>) -> Result<DataFrame, Box<dyn Error>> {
        let ohlcv = self.get_chart().await?;
        let col_str = match col {
            Some(col) => col.as_str(),
            None => Column::Low.as_str(),
        };
        let col_val = extract_f64_col(&ohlcv, col_str)?;
        let mut min = new_indicator!(Minimum, period)?;
        let col_name = format!("min-{period}");
        let min_series = Series::new(
            col_name.as_str().into(),
            col_val.iter().map(|x| min.next(*x)).collect::<Vec<f64>>(),
        );
        let mut df = df!(
            "timestamp" => extract_series_col(&ohlcv, "timestamp")?,
            col_str => extract_series_col(&ohlcv, col_str)?,
        )?;
        let df = df.with_column(min_series)?.clone();
        Ok(df)
    }

    /// Generates a Dataframe of the OHLCV data with the Average True Range Indicator
    ///
    /// # Arguments
    ///
    /// * `period` - Period for the Average True Range Indicator (e.g., 14)
    ///
    /// # Returns
    ///
    /// * `DataFrame` of the OHLCV data with the Average True Range Indicator
    async fn atr(&self, period: usize) -> Result<DataFrame, Box<dyn Error>> {
        let ohlcv = self.get_chart().await?;
        let mut atr = new_indicator!(AverageTrueRange, period)?;
        let col_name = format!("atr-{period}");
        let timestamp = extract_timestamps(&ohlcv)?;
        let open = extract_f64_col(&ohlcv, "open")?;
        let high = extract_f64_col(&ohlcv, "high")?;
        let low = extract_f64_col(&ohlcv, "low")?;
        let close = extract_f64_col(&ohlcv, "close")?;
        let volume = extract_f64_col(&ohlcv, "volume")?;

        let (ts, o, h, l, c, v, data_items) =
            build_data_items(&timestamp, &open, &high, &low, &close, &volume);

        let df = df!(
            "timestamp" => ts,
            "open" => o,
            "high" => h,
            "low" => l,
            "close" => c,
            "volume" => v,
            col_name.as_str() => data_items.iter().map(|x| atr.next(x)).collect::<Vec<f64>>()
        )?;
        Ok(df)
    }

    /// Generates a Dataframe of the ticker price data with the Rate of Change Indicator
    ///
    /// # Arguments
    ///
    /// * `period` - Period for the Rate of Change Indicator (e.g., 1)
    /// * `col` - Column for the Rate of Change Indicator (default - Column::AdjClose)
    ///
    /// # Returns
    ///
    /// * `DataFrame` of the OHLCV data with the Rate of Change Indicator
    async fn roc(&self, period: usize, col: Option<Column>) -> Result<DataFrame, Box<dyn Error>> {
        let ohlcv = self.get_chart().await?;
        let col_str = match col {
            Some(col) => col.as_str(),
            None => Column::AdjClose.as_str(),
        };
        let col_val = extract_f64_col(&ohlcv, col_str)?;
        let mut roc = new_indicator!(RateOfChange, period)?;
        let col_name = format!("roc-{period}");
        let roc_series = Series::new(
            col_name.as_str().into(),
            col_val.iter().map(|x| roc.next(*x)).collect::<Vec<f64>>(),
        );
        let mut df = df!(
            "timestamp" => extract_series_col(&ohlcv, "timestamp")?,
            col_str => extract_series_col(&ohlcv, col_str)?,
        )?;
        let df = df.with_column(roc_series)?.clone();
        Ok(df)
    }

    /// Generates a Dataframe of the OHLCV data with the On Balance Volume Indicator
    ///
    /// # Returns
    ///
    /// * `DataFrame` of the OHLCV data with the On Balance Volume Indicator
    async fn obv(&self) -> Result<DataFrame, Box<dyn Error>> {
        let ohlcv = self.get_chart().await?;
        let mut obv = OnBalanceVolume::new();
        let timestamp = extract_timestamps(&ohlcv)?;
        let open = extract_f64_col(&ohlcv, "open")?;
        let high = extract_f64_col(&ohlcv, "high")?;
        let low = extract_f64_col(&ohlcv, "low")?;
        let close = extract_f64_col(&ohlcv, "close")?;
        let volume = extract_f64_col(&ohlcv, "volume")?;

        let (ts, o, h, l, c, v, data_items) =
            build_data_items(&timestamp, &open, &high, &low, &close, &volume);

        let df = df!(
            "timestamp" => ts,
            "open" => o,
            "high" => h,
            "low" => l,
            "close" => c,
            "volume" => v,
            "obv" => data_items.iter().map(|x| obv.next(x)).collect::<Vec<f64>>()
        )?;
        Ok(df)
    }
}