Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
m5l14i11 committed Aug 3, 2023
1 parent 8ea794c commit 8ec6afe
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 18 deletions.
24 changes: 24 additions & 0 deletions ta_lib/core/src/math.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,30 @@ impl Series<f64> {
self.ew(period, |period| 1.0 / (period as f64))
}

pub fn wma(&self, period: usize) -> Self {
let len = self.len();
let mut wma = Series::empty(len);

let weight_sum = (period * (period + 1)) as f64 / 2.0;

let mut sum = 0.0;

for i in 0..period {
let weight = (i + 1) as f64;
sum += self[i].unwrap_or(0.0) * weight;
}

wma[period - 1] = Some(sum / weight_sum);

for i in period..len {
sum += (self[i].unwrap_or(0.0) - self[i - period].unwrap_or(0.0)) * period as f64
- (weight_sum - period as f64);
wma[i] = Some(sum / weight_sum);
}

wma
}

pub fn var(&self, period: usize) -> Self {
let ma: Vec<f64> = self.ma(period).into();

Expand Down
21 changes: 3 additions & 18 deletions ta_lib/trend/src/wma.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,11 @@
use core::series::Series;

pub fn wma(source: &[f64], period: usize) -> Vec<f64> {
let len = source.len();
let mut wma = Series::empty(len);
let source = Series::from(&source);

let weight_sum = (period * (period + 1)) as f64 / 2.0;
let wma = source.wma(period);

let mut sum = 0.0;

for i in 0..period {
let weight = (i + 1) as f64;
sum += source[i] * weight;
}

wma[period - 1] = Some(sum / weight_sum);

for i in period..len {
sum += (source[i] - source[i - period]) * period as f64 - (weight_sum - period as f64);
wma[i] = Some(sum / weight_sum);
}

wma.nz(Some(0.0)).into()
wma.into()
}

#[cfg(test)]
Expand Down

0 comments on commit 8ec6afe

Please sign in to comment.