amv-dev / yata

Yet Another Technical Analysis library [for Rust]
Apache License 2.0
334 stars 52 forks source link

How to get the avg from SMA method? #26

Closed frozenranger closed 2 years ago

frozenranger commented 2 years ago

Hello Yata!

Great repo, I was trying to learn how to use this repo by starting with the SMA indicator. I'm not sure what I am doing wrong but I can't seem to get the avg / value from the SMA.

Here is my code:

let mut sma = SMA::new(30, &f64::NAN).unwrap();

for i in 0..sma.get_window().len() {
    sma.next(&(i as f64));
}

println!("{:?}", sma.peek());

However this returns NaN? I was wondering how to get the moving average from the window? Do I have to manually calculate it or does yata do this for me?

Thank you :)

amv-dev commented 2 years ago

Hello. I think you misunderstood conceptions of this library.

First of all you should never provide NaN values for calculations. In this context NaN means invalid value. As long as you provide a single NaN and 29 valid values, it is still undefined what result is. Just ask yourself: what is average value of [NaN, 1]? It is still NaN.

You can initialize methods and indicators using the very first value of your time series. In this particular example it's just 0.0. So it should looks like this:

let first_value = 0;
let mut sma = SMA::new(30, &(first_value as f64)).unwrap();

for i in first_value..sma.get_window().len() {
    sma.next(&(i as f64));
}

println!("{:?}", sma.peek());
frozenranger commented 2 years ago

I see! Thanks for the fast reply! Much appreciated. Looking forward to learning more about yata