-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsma_big.go
51 lines (43 loc) · 1.11 KB
/
sma_big.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
package ma
import (
"math/big"
)
// SMABig represents the state of a Simple Moving Average (SMA) algorithm.
type SMABig struct {
cache []*big.Float
cacheLen uint
index uint
periods *big.Float
}
// NewBigSMA creates a new SMA data structure and the initial result. The period used will be the length of the initial
// input slice.
func NewBigSMA(initial []*big.Float) (sma *SMABig, result *big.Float) {
sma = &SMABig{
cacheLen: uint(len(initial)),
}
sma.cache = make([]*big.Float, sma.cacheLen)
sma.periods = big.NewFloat(float64(sma.cacheLen))
result = big.NewFloat(0)
for i, p := range initial {
if i != 0 {
sma.cache[i] = p
}
result = result.Add(result, p)
}
result = result.Quo(result, sma.periods)
return sma, result
}
// Calculate produces the next SMA result given the next input.
func (sma *SMABig) Calculate(next *big.Float) (result *big.Float) {
sma.cache[sma.index] = next
sma.index++
if sma.index == sma.cacheLen {
sma.index = 0
}
result = big.NewFloat(0)
for _, p := range sma.cache {
result = result.Add(result, p)
}
result = result.Quo(result, sma.periods)
return result
}