-
Notifications
You must be signed in to change notification settings - Fork 7
/
ma.go
91 lines (82 loc) · 2.34 KB
/
ma.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
package ta
import (
// "fmt"
)
// Mean gets the mean value for an array of float64 values
func Mean(values []float64) float64 {
var total float64=0
for _,element := range values {
total += element
}
return total / float64(len(values))
}
// Sma produces the Simple Moving Average for the
// supplied array of float64 values for a given period
func Sma(values []float64, period int) []float64{
var result []float64
if len(values) < period {
return result
}
for index,_ := range values {
indexPlusOne := index+1
if(indexPlusOne>=period) {
avg := Mean(values[indexPlusOne-period:indexPlusOne])
result = append(result, avg)
}
}
return result
}
// Wma produces a Weighted Moving Average (as finance understand it to be) for the
// supplied array of float64 values for a given period
func Wma(values []float64, period int) []float64{
var result []float64
for index,_ := range values {
indexPlusOne := index+1
if(indexPlusOne>=period) {
var res []float64
sl := values[indexPlusOne-period:indexPlusOne]
// Get the sum of the number of entries
var sum float64=0
for idx,_ := range sl {
sum += float64(idx+1)
}
for idx,element := range sl {
res = append(res, element*(float64(idx+1)/sum))
}
var total float64=0
for _,element := range res {
total += element
}
result = append(result, total)
}
}
return result
}
// Ema calculates the Exponential Moving Average for the
// supplied array of float64 values for a given period
func Ema(values []float64, period int) []float64 {
sma := Sma(values, period)
var result []float64
var multiplier = (2.0 / (float64(period) + 1.0) )
result = append(result,sma[0])
for i := (len(values)-len(sma))+1; i < len(values); i++ {
lastVal := result[len(result)-1]
ema := (values[i] - lastVal) * multiplier + lastVal
result = append(result,ema)
}
return result
}
func Dema(values []float64, period int) []float64 {
var result []float64
ema := Ema(values, period)
emaAgain := Ema(ema, period)
var emaDouble []float64
for _,element := range ema {
emaDouble = append(emaDouble, (2.0 * element))
}
offset := len(emaDouble)-len(emaAgain)
for index,element := range emaAgain {
result = append(result, (emaDouble[index+offset] - element))
}
return result
}