From f8573f1123a75799c6986c1c854798a0ec5059c0 Mon Sep 17 00:00:00 2001 From: Will Charczuk Date: Fri, 15 Jul 2016 13:27:45 -0700 Subject: [PATCH] adding GetLastBoundedValue and tests --- bollinger_band_series.go | 28 ++++++++++++++++++++++++++++ bollinger_band_series_test.go | 19 +++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/bollinger_band_series.go b/bollinger_band_series.go index 3529aa5..fef8be5 100644 --- a/bollinger_band_series.go +++ b/bollinger_band_series.go @@ -81,6 +81,34 @@ func (bbs *BollingerBandsSeries) GetBoundedValue(index int) (x, y1, y2 float64) return } +// GetLastBoundedValue returns the last bounded value for the series. +func (bbs *BollingerBandsSeries) GetLastBoundedValue() (x, y1, y2 float64) { + if bbs.InnerSeries == nil { + return + } + windowSize := bbs.GetWindowSize() + seriesLength := bbs.InnerSeries.Len() + startAt := seriesLength - windowSize + if startAt < 0 { + startAt = 0 + } + + vb := NewRingBufferWithCapacity(windowSize) + for index := startAt; index < seriesLength; index++ { + xn, yn := bbs.InnerSeries.GetValue(index) + vb.Enqueue(yn) + x = xn + } + + ay := bbs.getAverage(vb) + std := bbs.getStdDev(vb) + + y1 = ay + (bbs.GetK() * std) + y2 = ay - (bbs.GetK() * std) + + return +} + // Render renders the series. func (bbs BollingerBandsSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style) { s := bbs.Style.WithDefaultsFrom(defaults) diff --git a/bollinger_band_series_test.go b/bollinger_band_series_test.go index 5394afd..67a34f4 100644 --- a/bollinger_band_series_test.go +++ b/bollinger_band_series_test.go @@ -1,6 +1,7 @@ package chart import ( + "math" "testing" "github.com/blendlabs/go-assert" @@ -30,3 +31,21 @@ func TestBollingerBandSeries(t *testing.T) { assert.True(y1values[x] > y2values[x]) } } + +func TestBollingerBandLastValue(t *testing.T) { + assert := assert.New(t) + + s1 := mockValueProvider{ + X: Seq(1.0, 100.0), + Y: Seq(1.0, 100.0), + } + + bbs := &BollingerBandsSeries{ + InnerSeries: s1, + } + + x, y1, y2 := bbs.GetLastBoundedValue() + assert.Equal(100.0, x) + assert.Equal(100, math.Floor(y1)) + assert.Equal(95, math.Floor(y2)) +}