Skip to content

Commit 87776ee

Browse files
Create present value module (#495)
1 parent 02f2ecb commit 87776ee

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using Algorithms.Financial;
5+
using FluentAssertions;
6+
using NUnit.Framework;
7+
8+
namespace Algorithms.Tests.Financial;
9+
10+
public static class PresentValueTests
11+
{
12+
[TestCase(0.13,new[] { 10.0, 20.70, -293.0, 297.0 },4.69)]
13+
[TestCase(0.07,new[] { -109129.39, 30923.23, 15098.93, 29734.0, 39.0 }, -42739.63)]
14+
[TestCase(0.07, new[] { 109129.39, 30923.23, 15098.93, 29734.0, 39.0 }, 175519.15)]
15+
[TestCase(0.0, new[] { 109129.39, 30923.23, 15098.93, 29734.0, 39.0 }, 184924.55)]
16+
17+
public static void Present_Value_General_Tests(double discountRate,double[] cashFlow ,double expected)
18+
=>
19+
PresentValue.Calculate(discountRate, cashFlow.ToList())
20+
.Should()
21+
.Be(expected);
22+
23+
24+
[TestCase(-1.0, new[] { 10.0, 20.70, -293.0, 297.0 })]
25+
[TestCase(1.0,new double[] {})]
26+
27+
public static void Present_Value_Exception_Tests(double discountRate, double[] cashFlow)
28+
=> Assert.Throws<ArgumentException>(() => PresentValue.Calculate(discountRate, cashFlow.ToList()));
29+
}

Algorithms/Financial/PresentValue.cs

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
5+
namespace Algorithms.Financial;
6+
7+
/// <summary>
8+
/// PresentValue is the value of an expected income stream determined as of the date of valuation.
9+
/// </summary>
10+
public static class PresentValue
11+
{
12+
public static double Calculate(double discountRate, List<double> cashFlows)
13+
{
14+
if (discountRate < 0)
15+
{
16+
throw new ArgumentException("Discount rate cannot be negative");
17+
}
18+
19+
if (cashFlows.Count == 0)
20+
{
21+
throw new ArgumentException("Cash flows list cannot be empty");
22+
}
23+
24+
double presentValue = cashFlows.Select((t, i) => t / Math.Pow(1 + discountRate, i)).Sum();
25+
26+
return Math.Round(presentValue, 2);
27+
}
28+
}

0 commit comments

Comments
 (0)