forked from cinar/indicator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backtest.go
78 lines (63 loc) · 1.86 KB
/
backtest.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) 2021 Onur Cinar. All Rights Reserved.
// The source code is provided under MIT License.
//
// https://github.com/cinar/indicator
package indicator
// The NormalizeActions takes a list of independenc actions,
// such as SELL, SELL, BUY, SELL, HOLD, SELL, and produces
// a normalized list where the actions are following the
// proper BUY, HOLD, SELL, HOLD order.
func NormalizeActions(actions []Action) []Action {
normalized := make([]Action, len(actions))
last := SELL
for i, action := range actions {
if (action != HOLD) && (action != last) {
normalized[i] = action
last = action
} else {
normalized[i] = HOLD
}
}
return normalized
}
// The CountTransactions takes a list of normalized actions,
// and counts the BUY and SELL actions.
func CountTransactions(actions []Action) int {
count := 0
for _, action := range actions {
if (action == BUY) || (action == SELL) {
count++
}
}
return count
}
// The ApplyActions takes the given list of prices, applies the
// given list of normalized actions, and returns the gains.
func ApplyActions(prices []float64, actions []Action) []float64 {
gains := make([]float64, len(actions))
initialBalance := 1.0
balance := initialBalance
shares := 0.0
for i := 0; i < len(actions); i++ {
if actions[i] == BUY {
if balance > 0 {
shares = balance / prices[i]
balance = 0
}
} else if actions[i] == SELL {
if shares > 0 {
balance = shares * prices[i]
shares = 0
}
}
gains[i] = ((shares * prices[i]) + balance - initialBalance) / initialBalance
}
return gains
}
// The NormalizeGains takes the given list of prices, calculates the
// price gains, substracts it from the given list of gains.
func NormalizeGains(prices, gains []float64) []float64 {
priceGains := Sum(len(prices), percentDiff(prices, 1))
normalized := substract(gains, priceGains)
return normalized
}