rust_finprim/rate/cagr.rs
1use crate::FloatLike;
2
3/// CAGR - Compound Annual Growth Rate
4///
5/// The compound annual growth rate (CAGR) is the rate of return that would be required for an investment
6/// to grow from its beginning balance to its ending balance, assuming the profits were reinvested at the
7/// end of each period of the investment’s life span.
8///
9/// # Arguments
10/// * `beginning_balance` - The initial investment or balance
11/// * `ending_balance` - The final investment or balance
12/// * `n` - The number of years
13///
14/// # Returns
15/// * The compound annual growth rate (CAGR)
16///
17/// # Example
18/// * Beginning balance of $1000, ending balance of $2000 after 5 years
19/// ```
20/// use rust_finprim::rate::cagr;
21///
22/// let beginning_balance = 1000.0;
23/// let ending_balance = 2000.0;
24/// let n = 5.0;
25///
26/// cagr(beginning_balance, ending_balance, n);
27/// ```
28pub fn cagr<T: FloatLike>(beginning_balance: T, ending_balance: T, n: T) -> T {
29 (ending_balance / beginning_balance).powf(T::one() / n) - T::one()
30}
31
32#[cfg(test)]
33mod tests {
34 use super::*;
35
36 #[cfg(not(feature = "std"))]
37 extern crate std;
38 #[cfg(not(feature = "std"))]
39 use std::assert;
40
41 #[test]
42 fn test_cagr() {
43 let beginning_balance = 1000.0;
44 let ending_balance = 500.0;
45 let n = 5.0;
46 let result = cagr(beginning_balance, ending_balance, n);
47 let expected: f64 = -0.12945;
48 assert!(
49 (result - expected).abs() < 1e-5,
50 "Failed on case: {}. Expected: {}, Result: {}",
51 "Beginning balance of $1000, ending balance of $500 after 5 years",
52 expected,
53 result
54 );
55 }
56}