示例#1
0
文件: return.go 项目: bxy09/gfstat
/// <param name="prices"></param>
/// <param name="method"></param>
/// <returns></returns>
func Calculate(prices *utils.SlidingWindow, method string) (*utils.SlidingWindow, error) {
	if prices == nil {
		return nil, errors.New("Prices Utils Sliding Window is nil")
	}
	if prices.Count() == 0 {
		return nil, errors.New("Returns Windows content is Zero")
	}

	lastPrice := prices.First()
	returns, err := utils.NewSlidingWindow(prices.Count())
	if err != nil {
		return nil, errors.New("create a Sliding Window is Error !!")
	}

	switch method {
	case "simple":
	case "discrete":
		for i := 0; i < prices.Count(); i++ {
			price := prices.Data()[i]
			if lastPrice != 0.0 {
				returns.Add(price/lastPrice - 1.0)
			} else {
				returns.Add(0.0)
			}
			lastPrice = price
		}
	case "compound":
	case "log":
		for i := 0; i < prices.Count(); i++ {
			price := prices.Data()[i]
			if lastPrice != 0.0 {
				returns.Add(math.Log(price / lastPrice))
			} else {
				returns.Add(0.0)
			}
			lastPrice = price
		}
	default:
		return nil, errors.New("The input Method is nil !!!")
	}
	return returns, nil
}