From d4a9eecead23cc66ee8fe8bce37783c9e3c85c3f Mon Sep 17 00:00:00 2001 From: Lazaros Psarokostas Date: Mon, 18 Dec 2023 20:06:28 +0200 Subject: [PATCH] AverageReturn #12, AverageReturnAnnualized #13 --- gofin.go | 33 +++++++++++++++++++++++++++++++++ gofin_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/gofin.go b/gofin.go index b099beb..5c36aca 100644 --- a/gofin.go +++ b/gofin.go @@ -83,6 +83,39 @@ func HoldingPeriodReturnPercentage(initialValue, finalValue float64) float64 { return ((finalValue - initialValue) / initialValue)*100 } +// AverageReturn calculates the average return over multiple holding periods +func AverageReturn(holdingPeriodReturns []float64) float64 { + totalReturns := 0.0 + numReturns := len(holdingPeriodReturns) + + if numReturns == 0 { + return 0.0 // Avoid division by zero + } + + for _, hpr := range holdingPeriodReturns { + totalReturns += hpr + } + + return totalReturns / float64(numReturns) +} + +// AverageReturnAnnualized calculates the average annualized return over multiple holding periods +func AverageReturnAnnualized(initialValues, finalValues []float64, holdingPeriods []float64) float64 { + totalAnnualizedReturns := 0.0 + numReturns := len(initialValues) + + if numReturns == 0 { + return 0.0 // Avoid division by zero + } + + for i := 0; i < numReturns; i++ { + annualizedReturn := HoldingPeriodReturnAnnualized(initialValues[i], finalValues[i], holdingPeriods[i]) + totalAnnualizedReturns += annualizedReturn + } + + return totalAnnualizedReturns / float64(numReturns) +} + // HoldingPeriodReturnAnnualized calculates the annualized holding period return (HPR) func HoldingPeriodReturnAnnualized(initialValue, finalValue float64, holdingPeriodInYears float64) float64 { hpr := HoldingPeriodReturn(initialValue, finalValue) diff --git a/gofin_test.go b/gofin_test.go index 5278649..9e77e71 100644 --- a/gofin_test.go +++ b/gofin_test.go @@ -101,6 +101,33 @@ func TestHoldingPeriodReturnAnnualized(t *testing.T) { } } +//test AverageReturnAnnualized +func TestAverageReturnAnnualized(t *testing.T) { + var initialValues []float64 = []float64{1000.0, 1000.0} + var finalValues []float64 = []float64{1200.0, 1200.0} + var holdingPeriods []float64 = []float64{2.0, 2.0} + var expected float64 = 0.10 + + actual := AverageReturnAnnualized(initialValues, finalValues, holdingPeriods) + + if compareFloat64(actual, expected) { + t.Errorf("Test failed, expected: '%f', got: '%f'", expected, actual) + } + +} + +func TestAverageReturn(t *testing.T) { + var holdingPeriodReturns []float64 = []float64{0.10, 0.20} + var expected float64 = 0.15 + + actual := AverageReturn(holdingPeriodReturns) + + if compareFloat64(actual, expected) { + t.Errorf("Test failed, expected: '%f', got: '%f'", expected, actual) + } + +} + func TestHoldingPeriodReturnAnnualizePercentage(t *testing.T) { var initialValue float64 = 1000.0 var finalValue float64 = 1200.0