2022-04-26 08:32:31 +00:00
|
|
|
package indicator
|
|
|
|
|
|
|
|
import (
|
2022-08-25 09:31:42 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/datatype/floats"
|
2022-04-26 08:32:31 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Refer: Cumulative Moving Average, Cumulative Average
|
|
|
|
// Refer: https://en.wikipedia.org/wiki/Moving_average
|
2023-05-31 11:35:44 +00:00
|
|
|
//
|
2022-04-26 08:32:31 +00:00
|
|
|
//go:generate callbackgen -type CA
|
|
|
|
type CA struct {
|
2022-06-29 12:49:02 +00:00
|
|
|
types.SeriesBase
|
2023-05-31 11:35:44 +00:00
|
|
|
Interval types.Interval
|
|
|
|
Values floats.Slice
|
|
|
|
length float64
|
2023-06-01 06:27:03 +00:00
|
|
|
updateCallbacks []func(value float64)
|
2022-04-26 08:32:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (inc *CA) Update(x float64) {
|
2022-06-29 12:49:02 +00:00
|
|
|
if len(inc.Values) == 0 {
|
|
|
|
inc.SeriesBase.Series = inc
|
|
|
|
}
|
2023-06-01 06:27:03 +00:00
|
|
|
|
2023-05-31 11:35:44 +00:00
|
|
|
newVal := (inc.Values.Last(0)*inc.length + x) / (inc.length + 1.)
|
2022-04-26 08:32:31 +00:00
|
|
|
inc.length += 1
|
|
|
|
inc.Values.Push(newVal)
|
|
|
|
if len(inc.Values) > MaxNumOfEWMA {
|
|
|
|
inc.Values = inc.Values[MaxNumOfEWMATruncateSize-1:]
|
2022-06-29 12:49:02 +00:00
|
|
|
inc.length = float64(len(inc.Values))
|
2022-04-26 08:32:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-31 11:35:44 +00:00
|
|
|
func (inc *CA) Last(i int) float64 {
|
|
|
|
return inc.Values.Last(i)
|
2022-04-26 08:32:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (inc *CA) Index(i int) float64 {
|
2023-05-31 11:35:44 +00:00
|
|
|
return inc.Last(i)
|
2022-04-26 08:32:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (inc *CA) Length() int {
|
|
|
|
return len(inc.Values)
|
|
|
|
}
|
|
|
|
|
2022-06-29 12:49:02 +00:00
|
|
|
var _ types.SeriesExtend = &CA{}
|
2022-04-26 08:32:31 +00:00
|
|
|
|
2022-07-13 17:12:36 +00:00
|
|
|
func (inc *CA) PushK(k types.KLine) {
|
|
|
|
inc.Update(k.Close.Float64())
|
|
|
|
}
|
|
|
|
|
|
|
|
func (inc *CA) CalculateAndUpdate(allKLines []types.KLine) {
|
2022-04-26 08:32:31 +00:00
|
|
|
for _, k := range allKLines {
|
2022-07-13 17:12:36 +00:00
|
|
|
inc.PushK(k)
|
2023-05-31 11:35:44 +00:00
|
|
|
inc.EmitUpdate(inc.Last(0))
|
2022-04-26 08:32:31 +00:00
|
|
|
}
|
|
|
|
}
|