|
| 1 | +// Calculating simple ratios like Return on Investment (ROI), Debt to Equity, Gross Profit Margin |
| 2 | +// and Earnings per Sale (EPS) |
| 3 | +pub fn return_on_investment(gain: f64, cost: f64) -> f64 { |
| 4 | + (gain - cost) / cost |
| 5 | +} |
| 6 | + |
| 7 | +pub fn debt_to_equity(debt: f64, equity: f64) -> f64 { |
| 8 | + debt / equity |
| 9 | +} |
| 10 | + |
| 11 | +pub fn gross_profit_margin(revenue: f64, cost: f64) -> f64 { |
| 12 | + (revenue - cost) / revenue |
| 13 | +} |
| 14 | + |
| 15 | +pub fn earnings_per_sale(net_income: f64, pref_dividend: f64, share_avg: f64) -> f64 { |
| 16 | + (net_income - pref_dividend) / share_avg |
| 17 | +} |
| 18 | + |
| 19 | +#[cfg(test)] |
| 20 | +mod tests { |
| 21 | + use super::*; |
| 22 | + |
| 23 | + #[test] |
| 24 | + fn test_return_on_investment() { |
| 25 | + // let gain = 1200, cost = 1000 thus, ROI = (1200 - 1000)/1000 = 0.2 |
| 26 | + let result = return_on_investment(1200.0, 1000.0); |
| 27 | + assert!((result - 0.2).abs() < 0.001); |
| 28 | + } |
| 29 | + |
| 30 | + #[test] |
| 31 | + fn test_debt_to_equity() { |
| 32 | + // let debt = 300, equity = 150 thus, debt to equity ratio = 300/150 = 2 |
| 33 | + let result = debt_to_equity(300.0, 150.0); |
| 34 | + assert!((result - 2.0).abs() < 0.001); |
| 35 | + } |
| 36 | + |
| 37 | + #[test] |
| 38 | + fn test_gross_profit_margin() { |
| 39 | + // let revenue = 1000, cost = 800 thus, gross profit margin = (1000-800)/1000 = 0.2 |
| 40 | + let result = gross_profit_margin(1000.0, 800.0); |
| 41 | + assert!((result - 0.2).abs() < 0.01); |
| 42 | + } |
| 43 | + |
| 44 | + #[test] |
| 45 | + fn test_earnings_per_sale() { |
| 46 | + // let net_income = 350, pref_dividend = 50, share_avg = 25 this EPS = (350-50)/25 = 12 |
| 47 | + let result = earnings_per_sale(350.0, 50.0, 25.0); |
| 48 | + assert!((result - 12.0).abs() < 0.001); |
| 49 | + } |
| 50 | +} |
0 commit comments