-
-
Notifications
You must be signed in to change notification settings - Fork 278
/
volume_momentum.go
107 lines (85 loc) · 2.33 KB
/
volume_momentum.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package factorzoo
import (
"fmt"
"time"
"github.com/c9s/bbgo/pkg/datatype/floats"
"github.com/c9s/bbgo/pkg/indicator"
"github.com/c9s/bbgo/pkg/types"
)
// quarterly volume momentum
// assume that the quotient of volume SMA over latest volume will dynamically revert into one.
// so this fraction value is our alpha, PMR
//go:generate callbackgen -type VMOM
type VMOM struct {
types.SeriesBase
types.IntervalWindow
// Values
Values floats.Slice
LastValue float64
volumes *types.Queue
EndTime time.Time
UpdateCallbacks []func(val float64)
}
func (inc *VMOM) Index(i int) float64 {
return inc.Last(i)
}
func (inc *VMOM) Last(i int) float64 {
return inc.Values.Last(i)
}
func (inc *VMOM) Length() int {
return inc.Values.Length()
}
var _ types.SeriesExtend = &VMOM{}
func (inc *VMOM) Update(volume float64) {
if inc.SeriesBase.Series == nil {
inc.SeriesBase.Series = inc
inc.volumes = types.NewQueue(inc.Window)
}
inc.volumes.Update(volume)
if inc.volumes.Length() >= inc.Window {
v := inc.volumes.Last(0) / inc.volumes.Mean()
inc.Values.Push(v)
}
}
func (inc *VMOM) CalculateAndUpdate(allKLines []types.KLine) {
if len(inc.Values) == 0 {
for _, k := range allKLines {
inc.PushK(k)
}
inc.EmitUpdate(inc.Last(0))
} else {
k := allKLines[len(allKLines)-1]
inc.PushK(k)
inc.EmitUpdate(inc.Last(0))
}
}
func (inc *VMOM) handleKLineWindowUpdate(interval types.Interval, window types.KLineWindow) {
if inc.Interval != interval {
return
}
inc.CalculateAndUpdate(window)
}
func (inc *VMOM) Bind(updater indicator.KLineWindowUpdater) {
updater.OnKLineWindowUpdate(inc.handleKLineWindowUpdate)
}
func (inc *VMOM) PushK(k types.KLine) {
if inc.EndTime != zeroTime && k.EndTime.Before(inc.EndTime) {
return
}
inc.Update(k.Volume.Float64())
inc.EndTime = k.EndTime.Time()
inc.EmitUpdate(inc.Last(0))
}
func calculateVolumeMomentum(klines []types.KLine, window int, valV KLineValueMapper, valP KLineValueMapper) (float64, error) {
length := len(klines)
if length == 0 || length < window {
return 0.0, fmt.Errorf("insufficient elements for calculating VOL with window = %d", window)
}
vma := 0.
for _, p := range klines[length-window : length-1] {
vma += valV(p)
}
vma /= float64(window)
momentum := valV(klines[length-1]) / vma // * (valP(klines[length-1-2]) / valP(klines[length-1]))
return momentum, nil
}