sdcoffey / techan

Technical Analysis Library for Golang
https://godoc.org/github.com/sdcoffey/techan
MIT License
840 stars 143 forks source link

SMA Bug in v0.12.1 ? #50

Open shkim opened 2 years ago

shkim commented 2 years ago
package main

import (
    "fmt"
    "time"

    "github.com/sdcoffey/big"
    "github.com/sdcoffey/techan"
)

func calcSma(series *techan.TimeSeries, days int) []big.Decimal {
    closePrices := techan.NewClosePriceIndicator(series)
    sma := techan.NewSimpleMovingAverage(closePrices, days)

    cnt := len(series.Candles)
    ret := make([]big.Decimal, cnt)
    for idx := range ret {
        ret[idx] = sma.Calculate(idx)
    }
    return ret
}

func main() {
    series := techan.NewTimeSeries()
    for i := 1; i <= 30; i++ {
        day := time.Date(2020, 5, i, 0, 0, 0, 0, time.Local)
        candle := techan.NewCandle(techan.TimePeriod{
            Start: day,
            End:   day.Add(time.Duration(23) * time.Hour),
        })

        candle.ClosePrice = big.NewDecimal(float64(100 + i))
        added := series.AddCandle(candle)
        if !added {
            fmt.Println("AddCandle failed")
            return
        }
    }

    indicators := calcSma(series, 10)
    fmt.Println("SMA:", indicators)
}

with version 0.12.0

module main

go 1.17

require (
    github.com/sdcoffey/big v0.7.0
    github.com/sdcoffey/techan v0.12.0
)

the program run result is: SMA: [101 101.5 102 102.5 103 103.5 104 104.5 105 105.5 106.5 107.5 108.5 109.5 110.5 111.5 112.5 113.5 114.5 115.5 116.5 117.5 118.5 119.5 120.5 121.5 122.5 123.5 124.5 125.5]

I think above result is correct, but with v0.12.1

 module main

go 1.17

require (
    github.com/sdcoffey/big v0.7.0
    github.com/sdcoffey/techan v0.12.1
)

the result is: SMA: [0 0 0 0 0 0 0 0 0 105.5 106.5 107.5 108.5 109.5 110.5 111.5 112.5 113.5 114.5 115.5 116.5 117.5 118.5 119.5 120.5 121.5 122.5 123.5 124.5 125.5]

I think the initial 0s are incorrect.

Is this a bug or a new feature?

mrkarn007 commented 1 year ago

@shkim this should be the actual output for SMA: [0 0 0 0 0 0 0 0 0 105.5 106.5 107.5 108.5 109.5 110.5 111.5 112.5 113.5 114.5 115.5 116.5 117.5 118.5 119.5 120.5 121.5 122.5 123.5 124.5 125.5]. Zero will appear for index < period and from period itself mean value will appear based on the calculation.