|
| 1 | +#ifndef CASH_FLOW_H |
| 2 | +#define CASH_FLOW_H |
| 3 | + |
| 4 | +#include <cmath> |
| 5 | +#include <stdexcept> |
| 6 | +#include <vector> |
| 7 | + |
| 8 | + |
| 9 | +/** |
| 10 | + * Net Present Value |
| 11 | + * Calculates the present value of all cash flows |
| 12 | + * |
| 13 | + * @param cash_flows Vector of cash flows (negative = outflow, positive = inflow) |
| 14 | + * @param rate Discount rate (e.g., 0.10 for 10%) |
| 15 | + * @param initial_investment Optional initial investment (default: 0.0) |
| 16 | + * @return Net present value |
| 17 | + * |
| 18 | + * Formula: NPV = sum(CF_i / (1+r)^i) - Initial Investment |
| 19 | + * |
| 20 | + * Example: |
| 21 | + * cash_flows = [-1000, 100, 200, 300, 400] |
| 22 | + * rate = 0.10 |
| 23 | + * NPV = -1000 + 100/(1.1) + 200/(1.1)^2 + 300/(1.1)^3 + 400/(1.1)^4 |
| 24 | + */ |
| 25 | +double net_present_value( |
| 26 | + const std::vector<double>& cash_flows, |
| 27 | + double rate, |
| 28 | + double initial_investment = 0.0 |
| 29 | +); |
| 30 | + |
| 31 | +/** |
| 32 | + * Internal Rate of Return |
| 33 | + * Finds the discount rate that makes NPV = 0 |
| 34 | + * Uses Newton-Raphson iterative method |
| 35 | + * |
| 36 | + * @param cash_flows Vector of cash flows |
| 37 | + * @param initial_guess Starting guess for IRR (default: 0.1 = 10%) |
| 38 | + * @param max_iterations Maximum iterations for convergence (default: 100) |
| 39 | + * @param tolerance Convergence tolerance (default: 1e-6) |
| 40 | + * @return Internal rate of return |
| 41 | + * |
| 42 | + * Algorithm: |
| 43 | + * 1. Start with initial guess |
| 44 | + * 2. Calculate NPV and dNPV/dr at current guess |
| 45 | + * 3. Update: r_new = r_old - NPV / dNPV/dr |
| 46 | + * 4. Repeat until |NPV| < tolerance |
| 47 | + * |
| 48 | + * @throws std::runtime_error if convergence fails |
| 49 | + */ |
| 50 | +double internal_rate_of_return( |
| 51 | + const std::vector<double>& cash_flows, |
| 52 | + double initial_guess = 0.1, |
| 53 | + int max_iterations = 100, |
| 54 | + double tolerance = 1e-6 |
| 55 | +); |
| 56 | + |
| 57 | +/** |
| 58 | + * Payback period |
| 59 | + * Returns the number of periods until cumulative cash flows exceed initial investment |
| 60 | + * |
| 61 | + * @param cash_flows Vector of cash flows (first element is typically initial investment) |
| 62 | + * @param initial_investment Initial investment amount |
| 63 | + * @return Number of periods until payback (returns -1 if never pays back) |
| 64 | + * |
| 65 | + * Example: |
| 66 | + * cash_flows = [100, 200, 300, 400] |
| 67 | + * initial_investment = 500 |
| 68 | + * Cumulative: 100, 300, 600 (payback at period 3) |
| 69 | + */ |
| 70 | +int payback_period( |
| 71 | + const std::vector<double>& cash_flows, |
| 72 | + double initial_investment |
| 73 | +); |
| 74 | + |
| 75 | +#endif // CASH_FLOW_H |
0 commit comments