Skip to content

Commit cd61434

Browse files
Add return on investment algorithm to financial
1 parent 6c04620 commit cd61434

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

financial/return_on_investment.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# https://www.investopedia.com/terms/r/returnoninvestment.asp
2+
3+
from __future__ import annotations
4+
5+
6+
def return_on_investment(
7+
gain_from_investment: float, cost_of_investment: float
8+
) -> float:
9+
"""
10+
Return on Investment (ROI) measures the profitability of an investment
11+
relative to its cost, expressed as a percentage.
12+
13+
Formula: ROI = (Gain - Cost) / Cost * 100
14+
15+
>>> return_on_investment(1000.0, 500.0)
16+
100.0
17+
>>> return_on_investment(500.0, 500.0)
18+
0.0
19+
>>> return_on_investment(200.0, 500.0)
20+
-60.0
21+
>>> return_on_investment(0.0, 500.0)
22+
-100.0
23+
>>> return_on_investment(1000.0, 0.0)
24+
Traceback (most recent call last):
25+
...
26+
ValueError: cost_of_investment must be > 0
27+
>>> return_on_investment(1000.0, -100.0)
28+
Traceback (most recent call last):
29+
...
30+
ValueError: cost_of_investment must be > 0
31+
"""
32+
if cost_of_investment <= 0:
33+
raise ValueError("cost_of_investment must be > 0")
34+
return round(
35+
(gain_from_investment - cost_of_investment) / cost_of_investment * 100, 2
36+
)
37+
38+
39+
if __name__ == "__main__":
40+
import doctest
41+
42+
doctest.testmod()

0 commit comments

Comments
 (0)