finance_solution/stocks/ta/
moving_average.rs1use crate::stocks::ta::ring::RingF64;
72use crate::util::error::{require_finite, FinanceError, FinanceResult};
73use crate::util::primitives::PeriodLength;
74
75#[derive(Clone, Debug)]
93pub struct SmaState {
94 period: usize,
95 ring: RingF64,
96}
97
98impl SmaState {
99 pub fn new(period: usize) -> FinanceResult<Self> {
101 let period = PeriodLength::new(period)?.get();
102 Ok(Self {
103 period,
104 ring: RingF64::with_capacity(period),
105 })
106 }
107
108 pub fn from_history(period: usize, closes: &[f64]) -> FinanceResult<Self> {
109 let mut s = Self::new(period)?;
110 s.push_bars(closes)?;
111 Ok(s)
112 }
113
114 pub fn period(&self) -> usize {
115 self.period
116 }
117
118 pub fn reset(&mut self) {
119 self.ring.clear();
120 }
121
122 pub fn push(&mut self, close: f64) -> FinanceResult<Option<f64>> {
124 require_finite("close", close)?;
125 self.ring.push(close);
126 if self.ring.is_full() {
127 Ok(Some(self.ring.sum() / self.period as f64))
128 } else {
129 Ok(None)
130 }
131 }
132
133 pub fn push_bars(&mut self, closes: &[f64]) -> FinanceResult<Vec<Option<f64>>> {
135 let mut out = Vec::with_capacity(closes.len());
136 for &c in closes {
137 out.push(self.push(c)?);
138 }
139 Ok(out)
140 }
141
142 pub fn last(&self) -> Option<f64> {
143 if self.ring.is_full() {
144 Some(self.ring.sum() / self.period as f64)
145 } else {
146 None
147 }
148 }
149}
150
151#[derive(Clone, Debug)]
168pub struct EmaState {
169 period: usize,
170 alpha: f64,
171 seed: RingF64,
172 value: Option<f64>,
173}
174
175impl EmaState {
176 pub fn new(period: usize) -> FinanceResult<Self> {
177 let period = PeriodLength::new(period)?.get();
178 Ok(Self {
179 period,
180 alpha: 2.0 / (period as f64 + 1.0),
181 seed: RingF64::with_capacity(period),
182 value: None,
183 })
184 }
185
186 pub fn from_history(period: usize, closes: &[f64]) -> FinanceResult<Self> {
187 let mut s = Self::new(period)?;
188 s.push_bars(closes)?;
189 Ok(s)
190 }
191
192 pub fn period(&self) -> usize {
193 self.period
194 }
195
196 pub fn reset(&mut self) {
197 self.seed.clear();
198 self.value = None;
199 }
200
201 pub fn push(&mut self, close: f64) -> FinanceResult<Option<f64>> {
202 require_finite("close", close)?;
203 if let Some(prev) = self.value {
204 let next = self.alpha * close + (1.0 - self.alpha) * prev;
205 self.value = Some(next);
206 return Ok(Some(next));
207 }
208 self.seed.push(close);
209 if self.seed.is_full() {
210 let seed = self.seed.sum() / self.period as f64;
211 self.value = Some(seed);
212 Ok(Some(seed))
213 } else {
214 Ok(None)
215 }
216 }
217
218 pub fn push_bars(&mut self, closes: &[f64]) -> FinanceResult<Vec<Option<f64>>> {
219 let mut out = Vec::with_capacity(closes.len());
220 for &c in closes {
221 out.push(self.push(c)?);
222 }
223 Ok(out)
224 }
225
226 pub fn last(&self) -> Option<f64> {
227 self.value
228 }
229}
230
231pub fn sma(closes: &[f64], period: usize) -> FinanceResult<Vec<Option<f64>>> {
256 validate_closes(closes)?;
257 let mut st = SmaState::new(period)?;
258 st.push_bars(closes)
259}
260
261pub fn ema(closes: &[f64], period: usize) -> FinanceResult<Vec<Option<f64>>> {
278 validate_closes(closes)?;
279 let mut st = EmaState::new(period)?;
280 st.push_bars(closes)
281}
282
283#[inline]
295pub fn sma_last(closes: &[f64], period: usize) -> FinanceResult<Option<f64>> {
296 validate_closes(closes)?;
297 let mut st = SmaState::new(period)?;
298 for &c in closes {
299 st.push(c)?;
300 }
301 Ok(st.last())
302}
303
304#[inline]
315pub fn ema_last(closes: &[f64], period: usize) -> FinanceResult<Option<f64>> {
316 validate_closes(closes)?;
317 let mut st = EmaState::new(period)?;
318 for &c in closes {
319 st.push(c)?;
320 }
321 Ok(st.last())
322}
323
324#[derive(Clone, Debug)]
334pub struct WmaState {
335 period: usize,
336 ring: RingF64,
337 weight_sum: f64,
338 ordered: Vec<f64>,
339}
340
341impl WmaState {
342 pub fn new(period: usize) -> FinanceResult<Self> {
343 let period = PeriodLength::new(period)?.get();
344 let weight_sum = (period * (period + 1)) as f64 / 2.0;
345 Ok(Self {
346 period,
347 ring: RingF64::with_capacity(period),
348 weight_sum,
349 ordered: Vec::with_capacity(period),
350 })
351 }
352
353 pub fn from_history(period: usize, closes: &[f64]) -> FinanceResult<Self> {
354 let mut s = Self::new(period)?;
355 s.push_bars(closes)?;
356 Ok(s)
357 }
358
359 pub fn period(&self) -> usize {
360 self.period
361 }
362
363 pub fn reset(&mut self) {
364 self.ring.clear();
365 self.ordered.clear();
366 }
367
368 pub fn push(&mut self, close: f64) -> FinanceResult<Option<f64>> {
369 require_finite("close", close)?;
370 self.ring.push(close);
371 if !self.ring.is_full() {
372 return Ok(None);
373 }
374 self.ring.copy_ordered(&mut self.ordered);
375 let mut num = 0.0;
376 for (i, &p) in self.ordered.iter().enumerate() {
377 num += (i + 1) as f64 * p;
378 }
379 Ok(Some(num / self.weight_sum))
380 }
381
382 pub fn push_bars(&mut self, closes: &[f64]) -> FinanceResult<Vec<Option<f64>>> {
383 let mut out = Vec::with_capacity(closes.len());
384 for &c in closes {
385 out.push(self.push(c)?);
386 }
387 Ok(out)
388 }
389
390 pub fn last(&self) -> Option<f64> {
391 if !self.ring.is_full() {
392 return None;
393 }
394 let mut ordered = Vec::with_capacity(self.period);
396 self.ring.copy_ordered(&mut ordered);
397 let mut num = 0.0;
398 for (i, &p) in ordered.iter().enumerate() {
399 num += (i + 1) as f64 * p;
400 }
401 Some(num / self.weight_sum)
402 }
403}
404
405pub fn wma(closes: &[f64], period: usize) -> FinanceResult<Vec<Option<f64>>> {
407 validate_closes(closes)?;
408 let mut st = WmaState::new(period)?;
409 st.push_bars(closes)
410}
411
412pub fn wma_last(closes: &[f64], period: usize) -> FinanceResult<Option<f64>> {
413 validate_closes(closes)?;
414 let mut st = WmaState::new(period)?;
415 for &c in closes {
416 st.push(c)?;
417 }
418 Ok(st.last())
419}
420
421#[derive(Clone, Debug)]
434pub struct HmaState {
435 period: usize,
436 half: WmaState,
437 full: WmaState,
438 sqrt_wma: WmaState,
439 last: Option<f64>,
440}
441
442impl HmaState {
443 pub fn new(period: usize) -> FinanceResult<Self> {
444 let period = PeriodLength::new(period)?.get();
445 if period < 2 {
446 return Err(FinanceError::Unsolvable {
447 message: "HMA period must be >= 2",
448 });
449 }
450 let half_n = (period / 2).max(1);
451 let sqrt_n = ((period as f64).sqrt().floor() as usize).max(1);
452 Ok(Self {
453 period,
454 half: WmaState::new(half_n)?,
455 full: WmaState::new(period)?,
456 sqrt_wma: WmaState::new(sqrt_n)?,
457 last: None,
458 })
459 }
460
461 pub fn from_history(period: usize, closes: &[f64]) -> FinanceResult<Self> {
462 let mut s = Self::new(period)?;
463 s.push_bars(closes)?;
464 Ok(s)
465 }
466
467 pub fn period(&self) -> usize {
468 self.period
469 }
470
471 pub fn reset(&mut self) {
472 self.half.reset();
473 self.full.reset();
474 self.sqrt_wma.reset();
475 self.last = None;
476 }
477
478 pub fn push(&mut self, close: f64) -> FinanceResult<Option<f64>> {
479 let wh = self.half.push(close)?;
480 let wf = self.full.push(close)?;
481 let out = match (wh, wf) {
482 (Some(h), Some(f)) => {
483 let raw = 2.0 * h - f;
484 self.sqrt_wma.push(raw)?
485 }
486 _ => None,
487 };
488 self.last = out;
489 Ok(out)
490 }
491
492 pub fn push_bars(&mut self, closes: &[f64]) -> FinanceResult<Vec<Option<f64>>> {
493 let mut out = Vec::with_capacity(closes.len());
494 for &c in closes {
495 out.push(self.push(c)?);
496 }
497 Ok(out)
498 }
499
500 pub fn last(&self) -> Option<f64> {
501 self.last.or_else(|| self.sqrt_wma.last())
503 }
504}
505
506pub fn hma(closes: &[f64], period: usize) -> FinanceResult<Vec<Option<f64>>> {
517 validate_closes(closes)?;
518 let mut st = HmaState::new(period)?;
519 st.push_bars(closes)
520}
521
522pub fn hma_last(closes: &[f64], period: usize) -> FinanceResult<Option<f64>> {
523 validate_closes(closes)?;
524 let mut st = HmaState::new(period)?;
525 for &c in closes {
526 st.push(c)?;
527 }
528 Ok(st.last())
529}
530
531fn validate_closes(closes: &[f64]) -> FinanceResult<()> {
532 if closes.is_empty() {
533 return Err(FinanceError::EmptyInput { what: "closes" });
534 }
535 for &c in closes {
536 require_finite("close", c)?;
537 }
538 Ok(())
539}
540
541#[cfg(test)]
542mod tests {
543 use super::*;
544
545 #[test]
546 fn sma_constant() {
547 let c = [10.0; 5];
548 let s = sma(&c, 3).unwrap();
549 assert_eq!(s[2], Some(10.0));
550 assert_eq!(s[4], Some(10.0));
551 }
552
553 #[test]
554 fn ema_runs() {
555 let c: Vec<_> = (1..=30).map(|x| x as f64).collect();
556 let e = ema(&c, 10).unwrap();
557 assert!(e[8].is_none());
558 assert!(e[9].is_some());
559 }
560
561 #[test]
562 fn rejects_zero_period() {
563 assert!(sma(&[1.0, 2.0], 0).is_err());
564 }
565
566 #[test]
567 fn sma_period_one_is_identity() {
568 let c = [1.0, 2.0, 3.0];
569 let s = sma(&c, 1).unwrap();
570 assert_eq!(s[0], Some(1.0));
571 assert_eq!(s[2], Some(3.0));
572 }
573
574 #[test]
575 fn ema_seed_is_sma() {
576 let c = [1.0, 2.0, 3.0, 4.0, 5.0];
577 let e = ema(&c, 3).unwrap();
578 assert!((e[2].unwrap() - 2.0).abs() < 1e-12);
580 }
581
582 #[test]
583 fn empty_series_err() {
584 assert!(sma(&[], 3).is_err());
585 assert!(ema(&[], 3).is_err());
586 }
587
588 #[test]
589 fn nan_close_err() {
590 assert!(sma(&[1.0, f64::NAN], 2).is_err());
591 }
592
593 #[test]
594 fn last_matches_series_tail() {
595 let c: Vec<_> = (1..=25).map(|x| x as f64 * 0.5).collect();
596 let s = sma(&c, 7).unwrap();
597 assert_eq!(sma_last(&c, 7).unwrap(), s[24]);
598 let e = ema(&c, 7).unwrap();
599 assert_eq!(ema_last(&c, 7).unwrap(), e[24]);
600 }
601
602 #[test]
603 fn wma_weights_newest_heavier() {
604 let s = wma(&[1.0, 2.0, 3.0], 3).unwrap();
606 assert!((s[2].unwrap() - 14.0 / 6.0).abs() < 1e-12);
607 }
608
609 #[test]
610 fn hma_state_parity() {
611 let c: Vec<f64> = (1..=50).map(|x| 100.0 + x as f64 * 0.1).collect();
612 let batch = hma(&c, 16).unwrap();
613 let st = HmaState::from_history(16, &c).unwrap();
614 assert!((batch.last().unwrap().unwrap() - st.last().unwrap()).abs() < 1e-9);
615 }
616
617 #[test]
618 fn hma_rejects_period_one() {
619 assert!(HmaState::new(1).is_err());
620 }
621
622 #[test]
623 fn hma_tracks_rising_path() {
624 let c: Vec<f64> = (1..=60).map(|x| x as f64).collect();
625 let h = hma(&c, 9).unwrap();
626 let last = h.iter().rev().find_map(|x| *x).unwrap();
627 assert!(last > 50.0, "hma last={last}");
629 }
630
631 #[test]
632 fn wma_last_matches_series() {
633 let c: Vec<f64> = (1..=20).map(|x| x as f64).collect();
634 let s = wma(&c, 5).unwrap();
635 assert_eq!(wma_last(&c, 5).unwrap(), s[19]);
636 }
637
638 #[test]
639 fn hma_reset_clears() {
640 let c: Vec<f64> = (1..=30).map(|x| x as f64).collect();
641 let mut st = HmaState::from_history(9, &c).unwrap();
642 assert!(st.last().is_some());
643 st.reset();
644 assert!(st.last().is_none());
645 }
646}