Skip to content

Commit

Permalink
create present value module
Browse files Browse the repository at this point in the history
add documentation in readme.md
  • Loading branch information
alirezasariri78 committed Oct 30, 2024
1 parent 603db05 commit 8e9dbdb
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/financial/README.md
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
## Financial Algorithms
### [Present-Value Algorithm](./present_value.rs)
From [Wikipedia][present-value-wiki]: In economics and finance, present value (PV), also known as present discounted value, is the value of an expected income stream determined as of the date of valuation. The present value is usually less than the future value because money has interest-earning potential, a characteristic referred to as the time value of money, except during times of negative interest rates, when the present value will be equal or more than the future value

[present-value-wiki]: https://en.wikipedia.org/wiki/Present_value
4 changes: 3 additions & 1 deletion src/financial/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
mod price_plus_tax;

mod present_value;
pub use price_plus_tax::price_plus_tax;
pub use present_value::present_value;

52 changes: 52 additions & 0 deletions src/financial/present_value.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#[derive(PartialEq, Eq,Debug)]
pub enum PresentValueError{
NegetiveDiscount,
EmptyCashFlow
}


pub fn present_value(discount_rate: f64, cash_flows: Vec<f64>) -> Result<f64, PresentValueError> {
if discount_rate < 0.0 {
return Err(PresentValueError::NegetiveDiscount);
}
if cash_flows.is_empty() {
return Err(PresentValueError::EmptyCashFlow);
}

let present_value = cash_flows.iter().enumerate()
.map(|(i, &cash_flow)| cash_flow / (1.0 + discount_rate).powi(i as i32))
.sum::<f64>();

Ok((present_value * 100.0).round() / 100.0)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_present_value() {

assert_eq!(4.69,present_value(0.13, vec![10.0, 20.70, -293.0, 297.0]).unwrap());

assert_eq!( -42739.63,present_value(0.07, vec![-109129.39, 30923.23, 15098.93, 29734.0,39.0]).unwrap());

assert_eq!(175519.15,present_value(0.07, vec![109129.39, 30923.23, 15098.93, 29734.0,39.0]).unwrap());
}

#[test]
fn test_present_value_negative_discount_rate() {
assert_eq!(PresentValueError::NegetiveDiscount,present_value(-1.0, vec![10.0, 20.70, -293.0, 297.0]).unwrap_err());

}

#[test]
fn test_present_value_empty_cash_flow() {
assert_eq!(PresentValueError::EmptyCashFlow,present_value(1.0, vec![]).unwrap_err());
}

#[test]
fn test_present_value_zero_discount_rate() {
assert_eq!(184924.55,present_value(0.0, vec![109129.39, 30923.23, 15098.93, 29734.0,39.0]).unwrap());
}
}

0 comments on commit 8e9dbdb

Please sign in to comment.