Skip to content

Commit

Permalink
cross
Browse files Browse the repository at this point in the history
  • Loading branch information
m5l14i11 committed Aug 7, 2023
1 parent 0644237 commit 61dccd5
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
53 changes: 53 additions & 0 deletions ta_lib/core/src/helper.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use crate::series::Series;

impl Series<f64> {
pub fn cross_over(&self, rhs: &Series<f64>) -> Series<bool> {
self.gt(rhs) & self.shift(1).lt(&rhs.shift(1))
}

pub fn cross_under(&self, rhs: &Series<f64>) -> Series<bool> {
self.lt(rhs) & self.shift(1).gt(&rhs.shift(1))
}

pub fn cross(&self, rhs: &Series<f64>) -> Series<bool> {
self.cross_over(rhs) | self.cross_under(rhs)
}
}

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

#[test]
fn test_cross_over() {
let a = Series::from([5.5, 5.0, 4.5, 3.0, 2.5]);
let b = Series::from([4.5, 2.0, 3.0, 3.5, 2.0]);
let expected: Series<bool> = Series::from([f64::NAN, 0.0, 0.0, 0.0, 1.0]).into();

let result = a.cross_over(&b);

assert_eq!(result, expected);
}

#[test]
fn test_cross_under() {
let a = Series::from([5.5, 5.0, 4.5, 3.0, 2.5]);
let b = Series::from([4.5, 2.0, 3.0, 3.5, 2.0]);
let expected: Series<bool> = Series::from([f64::NAN, 0.0, 0.0, 1.0, 0.0]).into();

let result = a.cross_under(&b);

assert_eq!(result, expected);
}

#[test]
fn test_cross() {
let a = Series::from([5.5, 5.0, 4.5, 3.0, 2.5]);
let b = Series::from([4.5, 2.0, 3.0, 3.5, 2.0]);
let expected: Series<bool> = Series::from([f64::NAN, 0.0, 0.0, 1.0, 1.0]).into();

let result = a.cross(&b);

assert_eq!(result, expected);
}
}
1 change: 1 addition & 0 deletions ta_lib/core/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod bool;
pub mod helper;
pub mod math;
pub mod ops;
pub mod series;
2 changes: 1 addition & 1 deletion ta_lib/core/src/series.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ impl Into<Vec<bool>> for Series<bool> {

impl Into<Series<bool>> for Series<f64> {
fn into(self) -> Series<bool> {
self.fmap(|opt| opt.map(|&f| f != 0.0))
self.fmap(|opt| opt.and_then(|&f| if f.is_nan() { None } else { Some(f != 0.0) }))
}
}

Expand Down

0 comments on commit 61dccd5

Please sign in to comment.