Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions Algorithms.Tests/Financial/PresentValueTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using Algorithms.Financial;
using FluentAssertions;
using NUnit.Framework;

namespace Algorithms.Tests.Financial;

public static class PresentValueTests
{
[Test]
public static void Present_Value_General_Tests()
{
PresentValue.Calculate(0.13, [10.0, 20.70, -293.0, 297.0])
.Should()
.Be(4.69);

PresentValue.Calculate(0.07, [-109129.39, 30923.23, 15098.93, 29734.0, 39.0])
.Should()
.Be(-42739.63);

PresentValue.Calculate(0.07, [109129.39, 30923.23, 15098.93, 29734.0, 39.0])
.Should()
.Be(175519.15);

PresentValue.Calculate(0.0, [109129.39, 30923.23, 15098.93, 29734.0, 39.0])
.Should()
.Be(184924.55);
}

[Test]
public static void Present_Value_Exception_Tests()
{
Assert.Throws<ArgumentException>(() => PresentValue.Calculate(-1.0, [10.0, 20.70, -293.0, 297.0]));
Assert.Throws<ArgumentException>(() => PresentValue.Calculate(1.0, []));
}
}
28 changes: 28 additions & 0 deletions Algorithms/Financial/PresentValue.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;

namespace Algorithms.Financial;

/// <summary>
/// PresentValue is the value of an expected income stream determined as of the date of valuation.
/// </summary>
public static class PresentValue
{
public static double Calculate(double discountRate, List<double> cashFlows)
{
if (discountRate < 0)
{
throw new ArgumentException("Discount rate cannot be negative");
}

if (cashFlows == null || cashFlows.Count == 0)
{
throw new ArgumentException("Cash flows list cannot be empty");
}

double presentValue = cashFlows.Select((t, i) => t / Math.Pow(1 + discountRate, i)).Sum();

return Math.Round(presentValue, 2);
}
}
Loading