forked from sdcoffey/techan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
indicator_money_flow.go
74 lines (58 loc) · 2.16 KB
/
indicator_money_flow.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
package techan
import (
"math"
"github.com/sdcoffey/big"
)
type moneyFlowIndexIndicator struct {
mfIndicator Indicator
oneHundred big.Decimal
}
// NewMoneyFlowIndexIndicator returns a derivative Indicator which returns the money flow index of the base indicator
// in a given time frame. A more in-depth explanation of money flow index can be found here:
// https://www.investopedia.com/terms/m/mfi.asp
func NewMoneyFlowIndexIndicator(series *TimeSeries, timeframe int) Indicator {
return moneyFlowIndexIndicator{
mfIndicator: NewMoneyFlowRatioIndicator(series, timeframe),
oneHundred: big.NewFromString("100"),
}
}
func (mfi moneyFlowIndexIndicator) Calculate(index int) big.Decimal {
moneyFlowRatio := mfi.mfIndicator.Calculate(index)
return mfi.oneHundred.Sub(mfi.oneHundred.Div(big.ONE.Add(moneyFlowRatio)))
}
type moneyFlowRatioIndicator struct {
typicalPrice Indicator
volume Indicator
window int
}
// NewMoneyFlowRatioIndicator returns a derivative Indicator which returns the money flow ratio of the base indicator
// in a given time frame. Money flow ratio is the positive money flow divided by the negative money flow during the
// same time frame
func NewMoneyFlowRatioIndicator(series *TimeSeries, timeframe int) Indicator {
return moneyFlowRatioIndicator{
typicalPrice: NewTypicalPriceIndicator(series),
volume: NewVolumeIndicator(series),
window: timeframe,
}
}
func (mfr moneyFlowRatioIndicator) Calculate(index int) big.Decimal {
if index < mfr.window-1 {
return big.ZERO
}
positiveMoneyFlow := big.ZERO
negativeMoneyFlow := big.ZERO
typicalPrice := mfr.typicalPrice.Calculate(index)
for i := index; i > index-mfr.window && i > 0; i-- {
prevTypicalPrice := mfr.typicalPrice.Calculate(i - 1)
if typicalPrice.GT(prevTypicalPrice) {
positiveMoneyFlow = positiveMoneyFlow.Add(typicalPrice.Mul(mfr.volume.Calculate(i)))
} else if typicalPrice.LT(prevTypicalPrice) {
negativeMoneyFlow = negativeMoneyFlow.Add(typicalPrice.Mul(mfr.volume.Calculate(i)))
}
typicalPrice = prevTypicalPrice
}
if negativeMoneyFlow.EQ(big.ZERO) {
return big.NewDecimal(math.Inf(1))
}
return positiveMoneyFlow.Div(negativeMoneyFlow)
}