-
Notifications
You must be signed in to change notification settings - Fork 0
/
volatility.go
66 lines (54 loc) · 989 Bytes
/
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
package fincalc
import "math"
type Volatility struct {
prices []float64
}
func (v *Volatility) AddPrice(price float64) {
v.prices = append(v.prices, price)
}
func (v *Volatility) RangeVolatility() float64 {
if len(v.prices) < 1 {
return 0
}
min := v.prices[0]
max := min
for _, p := range v.prices {
if p < min {
min = p
}
if p > max {
max = p
}
}
return max - min
}
func (v *Volatility) StdDev() float64 {
m := v.Mean()
sum := 0.0
for _, v := range v.prices {
val := v - m
sum += (val * val)
}
return math.Sqrt(sum / float64(len(v.prices)-1))
}
func (v *Volatility) Mean() float64 {
sum := 0.0
for _, v := range v.prices {
sum += v
}
return sum / float64(len(v.prices))
}
func (v *Volatility) AvgDailyRange() float64 {
n := len(v.prices)
if n < 2 {
return 0
}
previous := v.prices[0]
sum := 0.0
for i := 1; i < n; i++ {
r := math.Abs(v.prices[i] - previous)
sum += r
previous = v.prices[i]
}
return sum / float64(n-1)
}