-
-
Notifications
You must be signed in to change notification settings - Fork 301
/
Copy pathkalmanfilter.go
78 lines (63 loc) · 1.85 KB
/
kalmanfilter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package indicator
import (
"math"
"github.com/c9s/bbgo/pkg/datatype/floats"
"github.com/c9s/bbgo/pkg/types"
)
// Refer: https://www.kalmanfilter.net/kalman1d.html
// One-dimensional Kalman filter
//go:generate callbackgen -type KalmanFilter
type KalmanFilter struct {
types.SeriesBase
types.IntervalWindow
AdditionalSmoothWindow uint
amp2 *types.Queue // measurement uncertainty
k float64 // Kalman gain
measurements *types.Queue
Values floats.Slice
UpdateCallbacks []func(value float64)
}
func (inc *KalmanFilter) Update(value float64) {
var measureMove = value
if inc.measurements != nil {
measureMove = value - inc.measurements.Last(0)
}
inc.update(value, math.Abs(measureMove))
}
func (inc *KalmanFilter) update(value, amp float64) {
if len(inc.Values) == 0 {
inc.amp2 = types.NewQueue(inc.Window)
inc.amp2.Update(amp * amp)
inc.measurements = types.NewQueue(inc.Window)
inc.measurements.Update(value)
inc.Values.Push(value)
return
}
// measurement
inc.measurements.Update(value)
inc.amp2.Update(amp * amp)
q := math.Sqrt(types.Mean(inc.amp2)) * float64(1+inc.AdditionalSmoothWindow)
// update
lastPredict := inc.Values.Last(0)
curState := value + (value - lastPredict)
estimated := lastPredict + inc.k*(curState-lastPredict)
// predict
inc.Values.Push(estimated)
p := math.Abs(curState - estimated)
inc.k = p / (p + q)
}
func (inc *KalmanFilter) Index(i int) float64 {
return inc.Last(i)
}
func (inc *KalmanFilter) Length() int {
return inc.Values.Length()
}
func (inc *KalmanFilter) Last(i int) float64 {
return inc.Values.Last(i)
}
// interfaces implementation check
var _ Simple = &KalmanFilter{}
var _ types.SeriesExtend = &KalmanFilter{}
func (inc *KalmanFilter) PushK(k types.KLine) {
inc.update(k.Close.Float64(), (k.High.Float64()-k.Low.Float64())/2)
}