-
-
Notifications
You must be signed in to change notification settings - Fork 301
/
volatility.go
110 lines (83 loc) · 2.36 KB
/
volatility.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
108
109
110
package indicator
import (
"fmt"
"math"
"time"
log "github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/datatype/floats"
"github.com/c9s/bbgo/pkg/types"
)
const MaxNumOfVOL = 5_000
const MaxNumOfVOLTruncateSize = 100
// var zeroTime time.Time
//go:generate callbackgen -type Volatility
type Volatility struct {
types.SeriesBase
types.IntervalWindow
Values floats.Slice
EndTime time.Time
UpdateCallbacks []func(value float64)
}
func (inc *Volatility) Last(i int) float64 {
return inc.Values.Last(i)
}
func (inc *Volatility) Index(i int) float64 {
return inc.Last(i)
}
func (inc *Volatility) Length() int {
return len(inc.Values)
}
var _ types.SeriesExtend = &Volatility{}
func (inc *Volatility) CalculateAndUpdate(allKLines []types.KLine) {
if len(allKLines) < inc.Window {
return
}
var end = len(allKLines) - 1
var lastKLine = allKLines[end]
if inc.EndTime != zeroTime && lastKLine.GetEndTime().Before(inc.EndTime) {
return
}
if len(inc.Values) == 0 {
inc.SeriesBase.Series = inc
}
var recentT = allKLines[end-(inc.Window-1) : end+1]
volatility, err := calculateVOLATILITY(recentT, inc.Window, types.KLineClosePriceMapper)
if err != nil {
log.WithError(err).Error("can not calculate volatility")
return
}
inc.Values.Push(volatility)
if len(inc.Values) > MaxNumOfVOL {
inc.Values = inc.Values[MaxNumOfVOLTruncateSize-1:]
}
inc.EndTime = allKLines[end].GetEndTime().Time()
inc.EmitUpdate(volatility)
}
func (inc *Volatility) handleKLineWindowUpdate(interval types.Interval, window types.KLineWindow) {
if inc.Interval != interval {
return
}
inc.CalculateAndUpdate(window)
}
func (inc *Volatility) Bind(updater KLineWindowUpdater) {
updater.OnKLineWindowUpdate(inc.handleKLineWindowUpdate)
}
func calculateVOLATILITY(klines []types.KLine, window int, priceF types.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)
}
sum := 0.0
for _, k := range klines {
sum += priceF(k)
}
avg := sum / float64(window)
sv := 0.0 // sum of variance
for _, j := range klines {
// The use of Pow math function func Pow(x, y float64) float64
sv += math.Pow(priceF(j)-avg, 2)
}
// The use of Sqrt math function func Sqrt(x float64) float64
sd := math.Sqrt(sv / float64(len(klines)))
return sd, nil
}