2023-05-29 13:42:22 +00:00
|
|
|
package indicator
|
|
|
|
|
|
|
|
type EWMAStream struct {
|
2023-05-30 03:35:24 +00:00
|
|
|
Float64Series
|
2023-05-29 13:42:22 +00:00
|
|
|
|
|
|
|
window int
|
|
|
|
multiplier float64
|
|
|
|
}
|
|
|
|
|
|
|
|
func EWMA2(source Float64Source, window int) *EWMAStream {
|
|
|
|
s := &EWMAStream{
|
2023-05-30 04:13:55 +00:00
|
|
|
Float64Series: NewFloat64Series(),
|
|
|
|
window: window,
|
|
|
|
multiplier: 2.0 / float64(1+window),
|
2023-05-29 13:42:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if sub, ok := source.(Float64Subscription); ok {
|
|
|
|
sub.AddSubscriber(s.calculateAndPush)
|
|
|
|
} else {
|
|
|
|
source.OnUpdate(s.calculateAndPush)
|
|
|
|
}
|
|
|
|
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *EWMAStream) calculateAndPush(v float64) {
|
|
|
|
v2 := s.calculate(v)
|
|
|
|
s.slice.Push(v2)
|
|
|
|
s.EmitUpdate(v2)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *EWMAStream) calculate(v float64) float64 {
|
2023-05-31 11:35:44 +00:00
|
|
|
last := s.slice.Last(0)
|
2023-05-29 13:42:22 +00:00
|
|
|
m := s.multiplier
|
|
|
|
return (1.0-m)*last + m*v
|
|
|
|
}
|