Merge pull request #687 from zenixls2/fix/drift

fix: check for div zero in drift indicator
This commit is contained in:
Zenix 2022-06-08 11:17:48 +09:00 committed by GitHub
commit cca813e5e5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 58 additions and 9 deletions

View File

@ -22,16 +22,25 @@ type Drift struct {
func (inc *Drift) Update(value float64) {
if inc.chng == nil {
inc.SMA = &SMA{IntervalWindow: types.IntervalWindow{inc.Interval, inc.Window}}
inc.SMA = &SMA{IntervalWindow: types.IntervalWindow{Interval: inc.Interval, Window: inc.Window}}
inc.chng = types.NewQueue(inc.Window)
}
chng := math.Log(value / inc.LastValue)
inc.LastValue = value
return
}
var chng float64
if value == 0 {
chng = 0
} else {
chng = math.Log(value / inc.LastValue)
inc.LastValue = value
}
inc.SMA.Update(chng)
inc.chng.Update(chng)
if inc.chng.Length() >= inc.Window {
stdev := types.Stdev(inc.chng, inc.Window)
drift := inc.SMA.Last() - stdev * stdev * 0.5
drift := inc.SMA.Last() - stdev*stdev*0.5
inc.Values.Push(drift)
}
}
func (inc *Drift) Index(i int) float64 {

View File

@ -0,0 +1,40 @@
package indicator
import (
"encoding/json"
"testing"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
"github.com/stretchr/testify/assert"
)
func Test_Drift(t *testing.T) {
var randomPrices = []byte(`[1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 4, 1, 2, 3, 4, 5, 6, 7, 8, 9]`)
var input []fixedpoint.Value
if err := json.Unmarshal(randomPrices, &input); err != nil {
panic(err)
}
tests := []struct {
name string
kLines []types.KLine
all int
}{
{
name: "random_case",
kLines: buildKLines(input),
all: 47,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
drift := Drift{IntervalWindow: types.IntervalWindow{Window: 3}}
drift.calculateAndUpdate(tt.kLines)
assert.Equal(t, drift.Length(), tt.all)
for _, v := range drift.Values {
assert.LessOrEqual(t, v, 1.0)
}
})
}
}