-
Notifications
You must be signed in to change notification settings - Fork 13
/
wma.go
78 lines (62 loc) · 1.47 KB
/
wma.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
// Copyright (c) 2014-2017 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package filters
import (
"fmt"
"github.com/bitmark-inc/logger"
"sync"
)
type WMA struct {
sync.RWMutex
Filter
samples []float64
it int
current float64
n float64
total float64
numerator float64
denominator float64
}
func NewWMA(start float64, n uint64) Filter {
filter := WMA{
samples: make([]float64, n),
current: start,
n: float64(n),
total: float64(n), // * (n + 1) / 2),
numerator: float64(n * (n + 1) / 2),
denominator: float64(n * (n + 1) / 2),
}
for i := uint64(0); i < n; i += 1 {
filter.samples[i] = start
}
return &filter
}
func (filter *WMA) Name() string {
filter.RLock()
defer filter.RUnlock()
return fmt.Sprintf("Weighted Moving Average %d", len(filter.samples))
}
func (filter *WMA) Process(s float64) float64 {
filter.Lock()
defer filter.Unlock()
if s < 0 {
logger.Panicf("wma negative sample: %f", s)
}
filter.numerator += filter.n*s - filter.total
filter.total += s - filter.samples[filter.it]
filter.samples[filter.it] = s
if filter.it += 1; filter.it >= len(filter.samples) {
filter.it = 0
}
filter.current = filter.numerator / filter.denominator
if filter.current < 0 {
filter.current = 0
}
return filter.current
}
func (filter *WMA) Current() float64 {
filter.RLock()
defer filter.RUnlock()
return filter.current
}