-
Notifications
You must be signed in to change notification settings - Fork 5
/
minimum.go
99 lines (79 loc) · 1.61 KB
/
minimum.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
/*
Copyright 2020 Binh Nguyen
Licensed under terms of MIT license (see LICENSE)
*/
package tago
import (
"fmt"
"math"
)
/*
Minimum returns the lowest value in a given time frame
# Parameters
* _n_ - size of time frame (integer greater than 0)
# Example
```
```
*/
type Minimum struct {
// number of periods (must be an integer greater than 0)
n int
// internal parameters for calculations
minIndex int
curIndex int
// slice of data needed for calculation
data []float64
}
// NewMinimum creates a new Minimum with the given number of periods
// Example: NewMinimum(9)
func NewMinimum(n int) (*Minimum, error) {
if n <= 0 {
return nil, ErrInvalidParameters
}
data := make([]float64, n)
for i := range data {
data[i] = math.Inf(1)
}
return &Minimum{
n: n,
minIndex: 0,
curIndex: 0,
data: data,
}, nil
}
// Next takes the next input and returns the next Minimum value
func (m *Minimum) Next(input float64) float64 {
// add input to data
m.curIndex = (m.curIndex + 1) % m.n
m.data[m.curIndex] = input
if input < m.data[m.minIndex] {
m.minIndex = m.curIndex
} else if m.curIndex == m.minIndex {
m.minIndex = findMinIndex(m.data)
}
return m.data[m.minIndex]
}
func findMinIndex(data []float64) int {
min := math.Inf(1)
index := 0
for i, v := range data {
if v < min {
min = v
index = i
}
}
return index
}
// Reset resets the indicators to a clean state
func (m *Minimum) Reset() {
data := make([]float64, m.n)
for i := range data {
data[i] = math.Inf(-1)
}
m.data = data
m.curIndex = 0
m.minIndex = 0
}
func (m *Minimum) String() string {
return fmt.Sprintf("Min(%d)", m.n)
}