mirror of
https://github.com/c9s/bbgo.git
synced 2024-11-25 16:25:16 +00:00
indicator: move EWMA2 to ewma2.go
This commit is contained in:
parent
8c7962f07f
commit
68570e1eeb
46
pkg/indicator/ewma2.go
Normal file
46
pkg/indicator/ewma2.go
Normal file
|
@ -0,0 +1,46 @@
|
|||
package indicator
|
||||
|
||||
import (
|
||||
"github.com/c9s/bbgo/pkg/datatype/floats"
|
||||
"github.com/c9s/bbgo/pkg/types"
|
||||
)
|
||||
|
||||
//go:generate callbackgen -type EWMAStream
|
||||
type EWMAStream struct {
|
||||
Float64Updater
|
||||
types.SeriesBase
|
||||
|
||||
slice floats.Slice
|
||||
|
||||
window int
|
||||
multiplier float64
|
||||
}
|
||||
|
||||
func EWMA2(source Float64Source, window int) *EWMAStream {
|
||||
s := &EWMAStream{
|
||||
window: window,
|
||||
multiplier: 2.0 / float64(1+window),
|
||||
}
|
||||
|
||||
s.SeriesBase.Series = s.slice
|
||||
|
||||
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 {
|
||||
last := s.slice.Last()
|
||||
m := s.multiplier
|
||||
return (1.0-m)*last + m*v
|
||||
}
|
|
@ -1,7 +1,6 @@
|
|||
package indicator
|
||||
|
||||
import (
|
||||
"github.com/c9s/bbgo/pkg/datatype/floats"
|
||||
"github.com/c9s/bbgo/pkg/types"
|
||||
)
|
||||
|
||||
|
@ -32,43 +31,3 @@ type Float64Subscription interface {
|
|||
types.Series
|
||||
AddSubscriber(f func(v float64))
|
||||
}
|
||||
|
||||
//go:generate callbackgen -type EWMAStream
|
||||
type EWMAStream struct {
|
||||
Float64Updater
|
||||
types.SeriesBase
|
||||
|
||||
slice floats.Slice
|
||||
|
||||
window int
|
||||
multiplier float64
|
||||
}
|
||||
|
||||
func EWMA2(source Float64Source, window int) *EWMAStream {
|
||||
s := &EWMAStream{
|
||||
window: window,
|
||||
multiplier: 2.0 / float64(1+window),
|
||||
}
|
||||
|
||||
s.SeriesBase.Series = s.slice
|
||||
|
||||
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 {
|
||||
last := s.slice.Last()
|
||||
m := s.multiplier
|
||||
return (1.0-m)*last + m*v
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user