diff --git a/gofin.go b/gofin.go index 466f6ea..b099beb 100644 --- a/gofin.go +++ b/gofin.go @@ -83,6 +83,19 @@ func HoldingPeriodReturnPercentage(initialValue, finalValue float64) float64 { return ((finalValue - initialValue) / initialValue)*100 } +// HoldingPeriodReturnAnnualized calculates the annualized holding period return (HPR) +func HoldingPeriodReturnAnnualized(initialValue, finalValue float64, holdingPeriodInYears float64) float64 { + hpr := HoldingPeriodReturn(initialValue, finalValue) + return math.Pow(1+hpr, 1/holdingPeriodInYears) - 1 +} + +// HoldingPeriodReturnAnnualized calculates the annualized holding period return (HPR) +// as a percentage +func HoldingPeriodReturnAnnualizedPercentage(initialValue, finalValue float64, holdingPeriodInYears float64) float64 { + hpr := HoldingPeriodReturn(initialValue, finalValue) + return (math.Pow(1+hpr, 1/holdingPeriodInYears) - 1)*100 +} + func PresentValueAnnuityDue(interestRate float64, periods int, cashFlows []float64) float64 { presentValueAnnuityDue := 0.0 for i := 0; i < len(cashFlows); i++ { diff --git a/gofin_test.go b/gofin_test.go index 0c29bd0..5278649 100644 --- a/gofin_test.go +++ b/gofin_test.go @@ -76,7 +76,6 @@ func TestHoldingPeriodReturn(t *testing.T) { } } - func TestHoldingPeriodReturnPercentage(t *testing.T) { var initialValue float64 = 1000.0 var finalValue float64 = 1200.0 @@ -89,6 +88,31 @@ func TestHoldingPeriodReturnPercentage(t *testing.T) { } } +func TestHoldingPeriodReturnAnnualized(t *testing.T) { + var initialValue float64 = 1000.0 + var finalValue float64 = 1200.0 + var holdingPeriodInYears = 2.0 + var expected float64 = 0.10 + + actual := HoldingPeriodReturnAnnualized(initialValue, finalValue, holdingPeriodInYears) + + 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 + var holdingPeriodInYears = 2.0 + var expected float64 = 9.54 + + actual := HoldingPeriodReturnAnnualizedPercentage(initialValue, finalValue, holdingPeriodInYears) + + if compareFloat64(actual, expected) { + t.Errorf("Test failed, expected: '%f', got: '%f'", expected, actual) + } +} func TestFutureValueAnnuity(t *testing.T) { var payment float64 = 100