use crate::stocks::ta::ring::RingF64;
use crate::util::error::{require_finite, FinanceError, FinanceResult};
use crate::util::primitives::PeriodLength;
#[derive(Clone, Debug)]
pub struct SmaState {
period: usize,
ring: RingF64,
}
impl SmaState {
pub fn new(period: usize) -> FinanceResult<Self> {
let period = PeriodLength::new(period)?.get();
Ok(Self {
period,
ring: RingF64::with_capacity(period),
})
}
pub fn from_history(period: usize, closes: &[f64]) -> FinanceResult<Self> {
let mut s = Self::new(period)?;
s.push_bars(closes)?;
Ok(s)
}
pub fn period(&self) -> usize {
self.period
}
pub fn reset(&mut self) {
self.ring.clear();
}
pub fn push(&mut self, close: f64) -> FinanceResult<Option<f64>> {
require_finite("close", close)?;
self.ring.push(close);
if self.ring.is_full() {
Ok(Some(self.ring.sum() / self.period as f64))
} else {
Ok(None)
}
}
pub fn push_bars(&mut self, closes: &[f64]) -> FinanceResult<Vec<Option<f64>>> {
let mut out = Vec::with_capacity(closes.len());
for &c in closes {
out.push(self.push(c)?);
}
Ok(out)
}
pub fn last(&self) -> Option<f64> {
if self.ring.is_full() {
Some(self.ring.sum() / self.period as f64)
} else {
None
}
}
}
#[derive(Clone, Debug)]
pub struct EmaState {
period: usize,
alpha: f64,
seed: RingF64,
value: Option<f64>,
}
impl EmaState {
pub fn new(period: usize) -> FinanceResult<Self> {
let period = PeriodLength::new(period)?.get();
Ok(Self {
period,
alpha: 2.0 / (period as f64 + 1.0),
seed: RingF64::with_capacity(period),
value: None,
})
}
pub fn from_history(period: usize, closes: &[f64]) -> FinanceResult<Self> {
let mut s = Self::new(period)?;
s.push_bars(closes)?;
Ok(s)
}
pub fn period(&self) -> usize {
self.period
}
pub fn reset(&mut self) {
self.seed.clear();
self.value = None;
}
pub fn push(&mut self, close: f64) -> FinanceResult<Option<f64>> {
require_finite("close", close)?;
if let Some(prev) = self.value {
let next = self.alpha * close + (1.0 - self.alpha) * prev;
self.value = Some(next);
return Ok(Some(next));
}
self.seed.push(close);
if self.seed.is_full() {
let seed = self.seed.sum() / self.period as f64;
self.value = Some(seed);
Ok(Some(seed))
} else {
Ok(None)
}
}
pub fn push_bars(&mut self, closes: &[f64]) -> FinanceResult<Vec<Option<f64>>> {
let mut out = Vec::with_capacity(closes.len());
for &c in closes {
out.push(self.push(c)?);
}
Ok(out)
}
pub fn last(&self) -> Option<f64> {
self.value
}
}
pub fn sma(closes: &[f64], period: usize) -> FinanceResult<Vec<Option<f64>>> {
validate_closes(closes)?;
let mut st = SmaState::new(period)?;
st.push_bars(closes)
}
pub fn ema(closes: &[f64], period: usize) -> FinanceResult<Vec<Option<f64>>> {
validate_closes(closes)?;
let mut st = EmaState::new(period)?;
st.push_bars(closes)
}
#[inline]
pub fn sma_last(closes: &[f64], period: usize) -> FinanceResult<Option<f64>> {
validate_closes(closes)?;
let mut st = SmaState::new(period)?;
for &c in closes {
st.push(c)?;
}
Ok(st.last())
}
#[inline]
pub fn ema_last(closes: &[f64], period: usize) -> FinanceResult<Option<f64>> {
validate_closes(closes)?;
let mut st = EmaState::new(period)?;
for &c in closes {
st.push(c)?;
}
Ok(st.last())
}
fn validate_closes(closes: &[f64]) -> FinanceResult<()> {
if closes.is_empty() {
return Err(FinanceError::EmptyInput { what: "closes" });
}
for &c in closes {
require_finite("close", c)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sma_constant() {
let c = [10.0; 5];
let s = sma(&c, 3).unwrap();
assert_eq!(s[2], Some(10.0));
assert_eq!(s[4], Some(10.0));
}
#[test]
fn ema_runs() {
let c: Vec<_> = (1..=30).map(|x| x as f64).collect();
let e = ema(&c, 10).unwrap();
assert!(e[8].is_none());
assert!(e[9].is_some());
}
#[test]
fn rejects_zero_period() {
assert!(sma(&[1.0, 2.0], 0).is_err());
}
#[test]
fn last_matches_series_tail() {
let c: Vec<_> = (1..=25).map(|x| x as f64 * 0.5).collect();
let s = sma(&c, 7).unwrap();
assert_eq!(sma_last(&c, 7).unwrap(), s[24]);
let e = ema(&c, 7).unwrap();
assert_eq!(ema_last(&c, 7).unwrap(), e[24]);
}
}