-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhw.go
78 lines (66 loc) · 1.94 KB
/
hw.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
// Package holtwinters implements simple Holt-Winters forecasting
/*
Translated from the python code at
http://grisha.org/blog/2016/02/17/triple-exponential-smoothing-forecasting-part-iii/
*/
package main
func initialTrend(series []float64, slen int) float64 {
slenf := float64(slen)
var sum float64
for i := 0; i < slen; i++ {
sum += (series[i+slen] - series[i]) / slenf
}
return sum / slenf
}
func initialSeasonalComponents(series []float64, slen int) []float64 {
seasonals := make([]float64, slen)
seasonAverages := make([]float64, slen)
nSeasons := len(series) / slen
// compute season averages
for j := 0; j < nSeasons; j++ {
seasonAverages[j] = fsum(series[slen*j:slen*j+slen]) / float64(slen)
}
// compute initial values
for i := 0; i < slen; i++ {
var sum float64
for j := 0; j < nSeasons; j++ {
sum += series[slen*j+i] - seasonAverages[j]
seasonals[i] = sum / float64(nSeasons)
}
}
return series //seasonals
}
func fsum(s []float64) float64 {
var sum float64
for _, v := range s {
sum += v
}
return sum
}
func TripleExponentialSmoothing(series []float64, slen int, alpha, beta, gamma float64, nPredictions int) []float64 {
var result []float64
seasonals := initialSeasonalComponents(series, slen)
var trend float64
var smooth, lastSmooth float64
for i := 0; i < len(series)+nPredictions; i++ {
if i == 0 {
// initial values
smooth = series[0]
trend = initialTrend(series, slen)
result = append(result, series[0])
continue
}
if i >= len(series) {
// we are forecasting
m := float64(i - len(series) + 1)
result = append(result, (smooth+m*trend)+seasonals[i%slen])
continue
}
val := series[i]
lastSmooth, smooth = smooth, alpha*(val-seasonals[i%slen])+(1-alpha)*(smooth+trend)
trend = beta*(smooth-lastSmooth) + (1-beta)*trend
seasonals[i%slen] = gamma*(val-smooth) + (1-gamma)*seasonals[i%slen]
result = append(result, smooth+trend+seasonals[i%slen])
}
return result
}