Implement movingAverage

This commit is contained in:
Alexander Zobnin
2021-05-27 18:17:32 +03:00
parent 2e3e235fa7
commit ec38c3981c
2 changed files with 46 additions and 0 deletions

View File

@@ -62,6 +62,7 @@ func init() {
"offset": applyOffset, "offset": applyOffset,
"delta": applyDelta, "delta": applyDelta,
"rate": applyRate, "rate": applyRate,
"movingAverage": applyMovingAverage,
"removeAboveValue": applyRemoveAboveValue, "removeAboveValue": applyRemoveAboveValue,
"removeBelowValue": applyRemoveBelowValue, "removeBelowValue": applyRemoveBelowValue,
"transformNull": applyTransformNull, "transformNull": applyTransformNull,
@@ -245,6 +246,16 @@ func applyTransformNull(series timeseries.TimeSeries, params ...interface{}) (ti
return series.Transform(transformFunc), nil return series.Transform(transformFunc), nil
} }
func applyMovingAverage(series timeseries.TimeSeries, params ...interface{}) (timeseries.TimeSeries, error) {
nFloat, err := MustFloat64(params[0])
if err != nil {
return nil, errParsingFunctionParam(err)
}
n := int(nFloat)
return series.SimpleMovingAverage(n), nil
}
func applyAggregateBy(series []*timeseries.TimeSeriesData, params ...interface{}) ([]*timeseries.TimeSeriesData, error) { func applyAggregateBy(series []*timeseries.TimeSeriesData, params ...interface{}) ([]*timeseries.TimeSeriesData, error) {
pInterval, err := MustString(params[0]) pInterval, err := MustString(params[0])
pAgg, err := MustString(params[1]) pAgg, err := MustString(params[1])

View File

@@ -0,0 +1,35 @@
package timeseries
import "math"
func (ts TimeSeries) SimpleMovingAverage(n int) TimeSeries {
if ts.Len() == 0 {
return ts
}
sma := NewTimeSeries()
// It's not possible to calculate MA if n greater than number of points
n = int(math.Min(float64(ts.Len()), float64(n)))
for i := n; i < ts.Len(); i++ {
windowEdgeRight := i
windowCount := 0
var windowSum float64 = 0
for j := 0; j < n; j++ {
point := ts[i-j]
if point.Value != nil {
windowSum += *point.Value
windowCount++
}
}
if windowCount > 0 {
windowAvg := windowSum / float64(windowCount)
sma = append(sma, TimePoint{Time: ts[windowEdgeRight].Time, Value: &windowAvg})
} else {
sma = append(sma, TimePoint{Time: ts[windowEdgeRight].Time, Value: nil})
}
}
return sma
}