From 61dccd54d874aecf98114bbf814a606a2f93ebec Mon Sep 17 00:00:00 2001 From: m5l14i11 Date: Mon, 7 Aug 2023 19:59:56 +0300 Subject: [PATCH] cross --- ta_lib/core/src/helper.rs | 53 +++++++++++++++++++++++++++++++++++++++ ta_lib/core/src/lib.rs | 1 + ta_lib/core/src/series.rs | 2 +- 3 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 ta_lib/core/src/helper.rs diff --git a/ta_lib/core/src/helper.rs b/ta_lib/core/src/helper.rs new file mode 100644 index 00000000..4f69b938 --- /dev/null +++ b/ta_lib/core/src/helper.rs @@ -0,0 +1,53 @@ +use crate::series::Series; + +impl Series { + pub fn cross_over(&self, rhs: &Series) -> Series { + self.gt(rhs) & self.shift(1).lt(&rhs.shift(1)) + } + + pub fn cross_under(&self, rhs: &Series) -> Series { + self.lt(rhs) & self.shift(1).gt(&rhs.shift(1)) + } + + pub fn cross(&self, rhs: &Series) -> Series { + 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 = 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 = 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 = Series::from([f64::NAN, 0.0, 0.0, 1.0, 1.0]).into(); + + let result = a.cross(&b); + + assert_eq!(result, expected); + } +} diff --git a/ta_lib/core/src/lib.rs b/ta_lib/core/src/lib.rs index f65963cb..0d8da7b0 100644 --- a/ta_lib/core/src/lib.rs +++ b/ta_lib/core/src/lib.rs @@ -1,4 +1,5 @@ pub mod bool; +pub mod helper; pub mod math; pub mod ops; pub mod series; diff --git a/ta_lib/core/src/series.rs b/ta_lib/core/src/series.rs index e4c983c8..0a15e183 100644 --- a/ta_lib/core/src/series.rs +++ b/ta_lib/core/src/series.rs @@ -155,7 +155,7 @@ impl Into> for Series { impl Into> for Series { fn into(self) -> Series { - 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) })) } }