indicator: add v2 sma

This commit is contained in:
c9s 2023-06-01 08:11:30 +08:00
parent 47e869a9f7
commit ee8bbe3418
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
3 changed files with 31 additions and 33 deletions

View File

@ -1,7 +1,6 @@
package indicator package indicator
import ( import (
"fmt"
"time" "time"
"github.com/c9s/bbgo/pkg/datatype/floats" "github.com/c9s/bbgo/pkg/datatype/floats"
@ -82,21 +81,3 @@ func (inc *SMA) LoadK(allKLines []types.KLine) {
inc.PushK(k) inc.PushK(k)
} }
} }
func calculateSMA(kLines []types.KLine, window int, priceF KLineValueMapper) (float64, error) {
length := len(kLines)
if length == 0 || length < window {
return 0.0, fmt.Errorf("insufficient elements for calculating SMA with window = %d", window)
}
if length != window {
return 0.0, fmt.Errorf("too much klines passed in, requires only %d klines", window)
}
sum := 0.0
for _, k := range kLines {
sum += priceF(k)
}
avg := sum / float64(window)
return avg, nil
}

View File

@ -17,17 +17,11 @@ func RSI2(source Float64Source, window int) *RSIStream {
Float64Series: NewFloat64Series(), Float64Series: NewFloat64Series(),
window: window, window: window,
} }
s.Bind(source, s)
if sub, ok := source.(Float64Subscription); ok {
sub.AddSubscriber(s.calculateAndPush)
} else {
source.OnUpdate(s.calculateAndPush)
}
return s return s
} }
func (s *RSIStream) calculate(_ float64) float64 { func (s *RSIStream) Calculate(_ float64) float64 {
var gainSum, lossSum float64 var gainSum, lossSum float64
var sourceLen = s.source.Length() var sourceLen = s.source.Length()
var limit = min(s.window, sourceLen) var limit = min(s.window, sourceLen)
@ -48,9 +42,3 @@ func (s *RSIStream) calculate(_ float64) float64 {
rsi := 100.0 - (100.0 / (1.0 + rs)) rsi := 100.0 - (100.0 / (1.0 + rs))
return rsi return rsi
} }
func (s *RSIStream) calculateAndPush(x float64) {
rsi := s.calculate(x)
s.slice.Push(rsi)
s.EmitUpdate(rsi)
}

29
pkg/indicator/v2_sma.go Normal file
View File

@ -0,0 +1,29 @@
package indicator
import "github.com/c9s/bbgo/pkg/types"
type SMAStream struct {
Float64Series
window int
rawValues *types.Queue
}
func SMA2(source Float64Source, window int) *SMAStream {
s := &SMAStream{
Float64Series: NewFloat64Series(),
window: window,
rawValues: types.NewQueue(window),
}
s.Bind(source, s)
return s
}
func (s *SMAStream) Calculate(v float64) float64 {
s.rawValues.Update(v)
sma := s.rawValues.Mean(s.window)
return sma
}
func (s *SMAStream) Truncate() {
s.slice.Truncate(MaxNumOfSMA)
}