forked from go-gota/gota
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add series.Rolling (go-gota#76) and RollingWindow.Mean
- Loading branch information
Showing
2 changed files
with
85 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
package series | ||
|
||
import "math" | ||
|
||
// RollingWindow is used for rolling window calculations. | ||
type RollingWindow struct { | ||
window int | ||
series Series | ||
} | ||
|
||
// Rolling creates new RollingWindow | ||
func (s Series) Rolling(window int) RollingWindow { | ||
return RollingWindow{ | ||
window: window, | ||
series: s, | ||
} | ||
} | ||
|
||
// Mean returns the rolling mean. | ||
func (r RollingWindow) Mean() (s Series) { | ||
s = New([]float64{}, Float, "mean") | ||
|
||
for i := 1; i <= r.series.Len(); i++ { | ||
if i < r.window { | ||
s.Append(math.NaN()) | ||
continue | ||
} | ||
|
||
index := []int{} | ||
for j := i - r.window; j < i; j++ { | ||
index = append(index, j) | ||
} | ||
|
||
mean := r.series.Subset(index).Mean() | ||
s.Append(mean) | ||
} | ||
|
||
return | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package series | ||
|
||
import ( | ||
"math" | ||
"strings" | ||
"testing" | ||
) | ||
|
||
func TestSeries_RollingMean(t *testing.T) { | ||
tests := []struct { | ||
window int | ||
series Series | ||
expected Series | ||
}{ | ||
{ | ||
3, | ||
Ints([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}), | ||
Floats([]float64{math.NaN(), math.NaN(), 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0}), | ||
}, | ||
{ | ||
2, | ||
Floats([]float64{1.0, 2.0, 3.0}), | ||
Floats([]float64{math.NaN(), 1.5, 2.5}), | ||
}, | ||
{ | ||
0, | ||
Floats([]float64{}), | ||
Floats([]float64{}), | ||
}, | ||
} | ||
|
||
for testnum, test := range tests { | ||
expected := test.expected | ||
received := test.series.Rolling(test.window).Mean() | ||
|
||
for i := 0; i < expected.Len(); i++ { | ||
if strings.Compare(expected.Elem(i).String(), | ||
received.Elem(i).String()) != 0 { | ||
t.Errorf( | ||
"Test:%v\nExpected:\n%v\nReceived:\n%v", | ||
testnum, expected, received, | ||
) | ||
} | ||
} | ||
} | ||
} |