Skip to content

Commit

Permalink
Merge branch 'master' into feature-opti_min_max_sd
Browse files Browse the repository at this point in the history
  • Loading branch information
greyblake committed Sep 21, 2020
2 parents c382f95 + a5b3798 commit 2b2d644
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 14 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -7,6 +7,7 @@
* More efficient StandardDeviation
* More efficient Minimum
* More efficient Maximum
* More efficient SimpleMovingAverage

#### v0.2.0 - 2020-08-31

Expand Down
3 changes: 1 addition & 2 deletions README.md
Expand Up @@ -18,8 +18,7 @@ Technical analysis library for Rust.
Add to you `Cargo.toml`:
```
[dependencies]
ta = "0.1.5"
ta = "0.2.0"
```

Example:
Expand Down
32 changes: 20 additions & 12 deletions src/indicators/simple_moving_average.rs
Expand Up @@ -12,12 +12,12 @@ use crate::{Close, Next, Reset};
/// Where:
///
/// * _SMA<sub>t</sub>_ - value of simple moving average at a point of time _t_
/// * _n_ - number of periods (length)
/// * _length_ - number of periods (length)
/// * _p<sub>t</sub>_ - input value at a point of time _t_
///
/// # Parameters
///
/// * _n_ - number of periods (integer greater than 0)
/// * _length_ - number of periods (integer greater than 0)
///
/// # Example
///
Expand All @@ -38,41 +38,49 @@ use crate::{Close, Next, Reset};
///
#[derive(Debug, Clone)]
pub struct SimpleMovingAverage {
n: u32,
length: u32,
index: usize,
count: u32,
sum: f64,
vec: Vec<f64>,
}

impl SimpleMovingAverage {
pub fn new(n: u32) -> Result<Self> {
match n {
pub fn new(length: u32) -> Result<Self> {
match length {
0 => Err(Error::from_kind(ErrorKind::InvalidParameter)),
_ => {
let indicator = Self {
n,
length,
index: 0,
count: 0,
sum: 0.0,
vec: vec![0.0; n as usize],
vec: vec![0.0; length as usize],
};
Ok(indicator)
}
}
}

pub fn length(&self) -> u32 {
self.length
}
}

impl Next<f64> for SimpleMovingAverage {
type Output = f64;

fn next(&mut self, input: f64) -> Self::Output {
self.index = (self.index + 1) % (self.n as usize);

let old_val = self.vec[self.index];
self.vec[self.index] = input;

if self.count < self.n {
self.index = if self.index + 1 < self.length as usize {
self.index + 1
} else {
0
};

if self.count < self.length {
self.count += 1;
}

Expand All @@ -94,7 +102,7 @@ impl Reset for SimpleMovingAverage {
self.index = 0;
self.count = 0;
self.sum = 0.0;
for i in 0..(self.n as usize) {
for i in 0..(self.length as usize) {
self.vec[i] = 0.0;
}
}
Expand All @@ -108,7 +116,7 @@ impl Default for SimpleMovingAverage {

impl fmt::Display for SimpleMovingAverage {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "SMA({})", self.n)
write!(f, "SMA({})", self.length)
}
}

Expand Down

0 comments on commit 2b2d644

Please sign in to comment.