forked from sdcoffey/techan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
indicator_relative_strength.go
60 lines (48 loc) · 1.82 KB
/
indicator_relative_strength.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
package techan
import (
"math"
"github.com/sdcoffey/big"
)
type relativeStrengthIndexIndicator struct {
rsIndicator Indicator
oneHundred big.Decimal
}
// NewRelativeStrengthIndexIndicator returns a derivative Indicator which returns the relative strength index of the base indicator
// in a given time frame. A more in-depth explanation of relative strength index can be found here:
// https://www.investopedia.com/terms/r/rsi.asp
func NewRelativeStrengthIndexIndicator(indicator Indicator, timeframe int) Indicator {
return relativeStrengthIndexIndicator{
rsIndicator: NewRelativeStrengthIndicator(indicator, timeframe),
oneHundred: big.NewFromString("100"),
}
}
func (rsi relativeStrengthIndexIndicator) Calculate(index int) big.Decimal {
relativeStrength := rsi.rsIndicator.Calculate(index)
return rsi.oneHundred.Sub(rsi.oneHundred.Div(big.ONE.Add(relativeStrength)))
}
type relativeStrengthIndicator struct {
avgGain Indicator
avgLoss Indicator
window int
}
// NewRelativeStrengthIndicator returns a derivative Indicator which returns the relative strength of the base indicator
// in a given time frame. Relative strength is the average again of up periods during the time frame divided by the
// average loss of down period during the same time frame
func NewRelativeStrengthIndicator(indicator Indicator, timeframe int) Indicator {
return relativeStrengthIndicator{
avgGain: NewMMAIndicator(NewGainIndicator(indicator), timeframe),
avgLoss: NewMMAIndicator(NewLossIndicator(indicator), timeframe),
window: timeframe,
}
}
func (rs relativeStrengthIndicator) Calculate(index int) big.Decimal {
if index < rs.window-1 {
return big.ZERO
}
avgGain := rs.avgGain.Calculate(index)
avgLoss := rs.avgLoss.Calculate(index)
if avgLoss.EQ(big.ZERO) {
return big.NewDecimal(math.Inf(1))
}
return avgGain.Div(avgLoss)
}