Skip to content

Added an algorithm to calculate the present value of cash flows #8700

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Apr 30, 2023
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
41 changes: 41 additions & 0 deletions financial/present_value.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An error occured while parsing the file: financial/present_value.py

Traceback (most recent call last):
  File "/opt/render/project/src/algorithms_keeper/parser/python_parser.py", line 145, in parse
    reports = lint_file(
              ^^^^^^^^^^
libcst._exceptions.ParserSyntaxError: Syntax Error @ 1:1.
tokenizer error: unterminated triple-quoted string literal

"""
^

Reference: https://www.investopedia.com/terms/p/presentvalue.asp
An algorithm that calculates the present value of a stream of yearly cash flows given...
1. The discount rate (as a decimal, not a percent)
2. An array of cash flows, with the index of the cash flow being the associated year
Note: This algorithm assumes that cash flows are paid at the end of the specified year
def present_value(discount_rate: float, cash_flows: list[float]) -> float:
"""
>>> present_value(0.13, [10, 20.70, -293, 297])
4.69
>>> present_value(0.07, [-109129.39, 30923.23, 15098.93, 29734,39])
-42739.63
>>> present_value(0.07, [109129.39, 30923.23, 15098.93, 29734,39])
175519.15
>>> present_value(-1, [109129.39, 30923.23, 15098.93, 29734,39])
Traceback (most recent call last):
...
ValueError: Discount rate cannot be negative
>>> present_value(0.03, [])
Traceback (most recent call last):
...
ValueError: Cash flows list cannot be empty
"""
if discount_rate < 0:
raise ValueError("Discount rate cannot be negative")
if not cash_flows:
raise ValueError("Cash flows list cannot be empty")
present_value = sum(
cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(cash_flows)
)
return round(present_value, ndigits=2)


if __name__ == "__main__":
import doctest

doctest.testmod()