Skip to main content

sma

Function sma 

Source
pub fn sma(closes: &[f64], period: usize) -> FinanceResult<Vec<Option<f64>>>
Expand description

SMA of period closes. Leading period - 1 values are None.

Implemented via SmaState::push_bars so batch and streaming stay bit-identical.

§Errors

Empty input, non-finite values, or period == 0.

§Examples

use finance_solution::stocks::ta::sma;
let c = [1.0, 2.0, 3.0, 4.0, 5.0];
let s = sma(&c, 3).unwrap();
assert_eq!(s[0], None);
assert_eq!(s[1], None);
assert!((s[2].unwrap() - 2.0).abs() < 1e-12); // (1+2+3)/3
assert!((s[4].unwrap() - 4.0).abs() < 1e-12); // (3+4+5)/3

Short series (shorter than period) — all None, still Ok:

use finance_solution::stocks::ta::sma;
let s = sma(&[1.0, 2.0], 5).unwrap();
assert!(s.iter().all(|x| x.is_none()));