Skip to content

Commit

Permalink
Add series.Rolling (go-gota#76) and RollingWindow.Mean
Browse files Browse the repository at this point in the history
  • Loading branch information
jfussion committed May 5, 2020
1 parent a9b7a7e commit 5bbeaf0
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
39 changes: 39 additions & 0 deletions series/rolling_window.go
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
}
46 changes: 46 additions & 0 deletions series/rolling_window_test.go
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,
)
}
}
}
}

0 comments on commit 5bbeaf0

Please sign in to comment.