use crate::model::Bar;
use crate::studies::{Indicator, IndicatorValue};
use crate::tokens::DESIGN_TOKENS;
use egui::Color32;
#[derive(Clone)]
pub struct HMA {
period: usize,
values: Vec<IndicatorValue>,
color: Color32,
visible: bool,
}
impl HMA {
pub fn new(period: usize) -> Self {
Self {
period: period.max(2),
values: Vec::new(),
color: DESIGN_TOKENS.semantic.extended.deep_purple, visible: true,
}
}
pub fn with_color(mut self, color: Color32) -> Self {
self.color = color;
self
}
fn calculate_wma(data: &[f64], period: usize) -> Vec<f64> {
let mut wma = vec![f64::NAN; data.len()];
if data.is_empty() || period == 0 {
return wma;
}
let weight_sum = (period * (period + 1)) / 2;
for i in (period - 1)..data.len() {
let mut weighted_sum = 0.0;
for j in 0..period {
let weight = (period - j) as f64;
weighted_sum += data[i - j] * weight;
}
wma[i] = weighted_sum / weight_sum as f64;
}
wma
}
}
impl Default for HMA {
fn default() -> Self {
Self::new(20)
}
}
impl Indicator for HMA {
fn name(&self) -> &str {
"HMA"
}
fn desc(&self) -> &str {
"Hull Moving Avg - Fast and smooth moving avg"
}
fn calculate(&mut self, data: &[Bar]) {
self.values.clear();
if data.is_empty() {
return;
}
let half_period = (self.period / 2).max(1);
let sqrt_period = (self.period as f64).sqrt() as usize;
let sqrt_period = sqrt_period.max(1);
let closes: Vec<f64> = data.iter().map(|b| b.close).collect();
let wma_half = Self::calculate_wma(&closes, half_period);
let wma_full = Self::calculate_wma(&closes, self.period);
let mut raw_hma = vec![f64::NAN; data.len()];
for i in 0..data.len() {
if !wma_half[i].is_nan() && !wma_full[i].is_nan() {
raw_hma[i] = 2.0 * wma_half[i] - wma_full[i];
}
}
let hma = Self::calculate_wma(&raw_hma, sqrt_period);
let min_period = self.period + sqrt_period - 1;
for i in 0..data.len() {
if i < min_period - 1 || hma[i].is_nan() {
self.values.push(IndicatorValue::None);
} else {
self.values.push(IndicatorValue::Single(hma[i]));
}
}
}
fn values(&self) -> &[IndicatorValue] {
&self.values
}
fn colors(&self) -> Vec<Color32> {
vec![self.color]
}
fn set_colors(&mut self, colors: Vec<Color32>) {
if !colors.is_empty() {
self.color = colors[0];
}
}
fn is_overlay(&self) -> bool {
true
}
fn line_cnt(&self) -> usize {
1
}
fn is_visible(&self) -> bool {
self.visible
}
fn set_visible(&mut self, visible: bool) {
self.visible = visible;
}
fn clone_box(&self) -> Box<dyn Indicator> {
Box::new(self.clone())
}
fn line_names(&self) -> Vec<String> {
vec![format!("HMA({})", self.period)]
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::{Duration, Utc};
fn create_test_bars() -> Vec<Bar> {
let start = Utc::now();
(0..50)
.map(|i| {
let price = 100.0 + i as f64;
Bar {
time: start + Duration::minutes(i * 5),
open: price,
high: price + 1.0,
low: price - 1.0,
close: price,
volume: 1000.0,
}
})
.collect()
}
#[test]
fn test_hma_calculation() {
let bars = create_test_bars();
let mut hma = HMA::new(9);
hma.calculate(&bars);
assert_eq!(hma.values().len(), bars.len());
let valid_cnt = hma
.values()
.iter()
.filter(|v| matches!(v, IndicatorValue::Single(_)))
.count();
assert!(valid_cnt > 0, "Should have some valid values");
}
#[test]
fn test_hma_responsiveness() {
let bars = create_test_bars();
let mut hma = HMA::new(9);
hma.calculate(&bars);
let last_valid = hma.values().iter().rev().find_map(|v| {
if let IndicatorValue::Single(val) = v {
Some(*val)
} else {
None
}
});
if let Some(hma_val) = last_valid {
let last_close = bars.last().unwrap().close;
assert!(
(hma_val - last_close).abs() < 5.0,
"HMA should be very responsive to price"
);
}
}
#[test]
fn test_hma_is_overlay() {
let hma = HMA::new(9);
assert!(hma.is_overlay());
}
#[test]
fn test_hma_empty_data() {
let mut hma = HMA::new(9);
hma.calculate(&[]);
assert!(hma.values().is_empty());
}
#[test]
fn test_hma_min_period() {
let bars = create_test_bars();
let mut hma = HMA::new(2);
hma.calculate(&bars);
assert_eq!(hma.values().len(), bars.len());
}
}