corp-finance-core 1.1.0

Institutional-grade corporate finance calculations with 128-bit decimal precision — DCF, WACC, comps, LBO, credit metrics, derivatives, fixed income, options, and 60+ specialty modules. No f64 in financials. WASM-compatible.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
//! Net Interest Margin (NIM) analysis.
//!
//! Covers:
//! 1. **NIM calculation** -- net interest income / earning assets.
//! 2. **Weighted-average asset yield and liability cost**.
//! 3. **Rate/volume/mix variance decomposition**.
//! 4. **Interest rate sensitivity gap analysis** (RSA - RSL).
//!
//! All arithmetic uses `rust_decimal::Decimal`. No `f64`.

use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};

use crate::error::CorpFinanceError;
use crate::CorpFinanceResult;

// ---------------------------------------------------------------------------
// Input / Output
// ---------------------------------------------------------------------------

/// A single item in the asset mix breakdown.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssetMixItem {
    pub name: String,
    pub balance: Decimal,
    pub yield_rate: Decimal,
}

/// A single item in the liability mix breakdown.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LiabilityMixItem {
    pub name: String,
    pub balance: Decimal,
    pub cost_rate: Decimal,
}

/// Input for NIM analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NimAnalysisInput {
    /// Total interest income for the period.
    pub interest_income: Decimal,
    /// Total interest expense for the period.
    pub interest_expense: Decimal,
    /// Total earning assets (average balance).
    pub earning_assets: Decimal,
    /// Breakdown of earning assets by category.
    pub asset_mix: Vec<AssetMixItem>,
    /// Breakdown of interest-bearing liabilities by category.
    pub liability_mix: Vec<LiabilityMixItem>,
    /// Prior period interest income.
    pub prior_interest_income: Decimal,
    /// Prior period interest expense.
    pub prior_interest_expense: Decimal,
    /// Prior period earning assets.
    pub prior_earning_assets: Decimal,
    /// Rate-sensitive assets for gap analysis.
    pub rate_sensitive_assets: Decimal,
    /// Rate-sensitive liabilities for gap analysis.
    pub rate_sensitive_liabilities: Decimal,
}

/// Rate/volume/mix variance decomposition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateVolumeVariance {
    /// Change in NII attributable to changes in rates.
    pub rate_effect: Decimal,
    /// Change in NII attributable to changes in volume.
    pub volume_effect: Decimal,
    /// Residual (mix/interaction) effect.
    pub mix_effect: Decimal,
}

/// Output of NIM analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NimAnalysisOutput {
    /// Net interest margin (as decimal, e.g. 0.03 = 3%).
    pub nim: Decimal,
    /// Net interest income = interest_income - interest_expense.
    pub net_interest_income: Decimal,
    /// Spread = weighted avg asset yield - weighted avg liability cost.
    pub spread: Decimal,
    /// Weighted average asset yield.
    pub asset_yield: Decimal,
    /// Weighted average liability cost.
    pub liability_cost: Decimal,
    /// Rate/volume/mix variance decomposition.
    pub rate_volume_variance: RateVolumeVariance,
    /// Interest rate sensitivity gap (RSA - RSL).
    pub interest_sensitivity_gap: Decimal,
    /// Gap ratio = gap / earning_assets.
    pub gap_ratio: Decimal,
}

// ---------------------------------------------------------------------------
// Core function
// ---------------------------------------------------------------------------

/// Perform NIM analysis including spread, rate/volume variance, and gap analysis.
pub fn analyze_nim(input: &NimAnalysisInput) -> CorpFinanceResult<NimAnalysisOutput> {
    validate_nim_input(input)?;

    // Net interest income
    let nii = input.interest_income - input.interest_expense;

    // NIM
    let nim = nii / input.earning_assets;

    // Weighted average asset yield
    let asset_yield = weighted_average_yield(&input.asset_mix)?;

    // Weighted average liability cost
    let liability_cost = weighted_average_cost(&input.liability_mix)?;

    // Spread
    let spread = asset_yield - liability_cost;

    // Rate/volume/mix variance
    let prior_nii = input.prior_interest_income - input.prior_interest_expense;

    let rate_volume_variance = if input.prior_earning_assets == Decimal::ZERO {
        // No prior period data -- cannot decompose
        RateVolumeVariance {
            rate_effect: Decimal::ZERO,
            volume_effect: Decimal::ZERO,
            mix_effect: Decimal::ZERO,
        }
    } else {
        let prior_nim = prior_nii / input.prior_earning_assets;
        let total_change = nii - prior_nii;

        // Volume effect: change in earning assets times prior NIM
        let volume_effect = (input.earning_assets - input.prior_earning_assets) * prior_nim;

        // Rate effect: prior earning assets times change in NIM
        let rate_effect = input.prior_earning_assets * (nim - prior_nim);

        // Mix effect: residual
        let mix_effect = total_change - volume_effect - rate_effect;

        RateVolumeVariance {
            rate_effect,
            volume_effect,
            mix_effect,
        }
    };

    // Gap analysis
    let interest_sensitivity_gap = input.rate_sensitive_assets - input.rate_sensitive_liabilities;
    let gap_ratio = interest_sensitivity_gap / input.earning_assets;

    Ok(NimAnalysisOutput {
        nim,
        net_interest_income: nii,
        spread,
        asset_yield,
        liability_cost,
        rate_volume_variance,
        interest_sensitivity_gap,
        gap_ratio,
    })
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn weighted_average_yield(items: &[AssetMixItem]) -> CorpFinanceResult<Decimal> {
    if items.is_empty() {
        return Ok(Decimal::ZERO);
    }
    let total_balance: Decimal = items.iter().map(|a| a.balance).sum();
    if total_balance == Decimal::ZERO {
        return Err(CorpFinanceError::DivisionByZero {
            context: "asset_mix total balance is zero".into(),
        });
    }
    let weighted_sum: Decimal = items.iter().map(|a| a.balance * a.yield_rate).sum();
    Ok(weighted_sum / total_balance)
}

fn weighted_average_cost(items: &[LiabilityMixItem]) -> CorpFinanceResult<Decimal> {
    if items.is_empty() {
        return Ok(Decimal::ZERO);
    }
    let total_balance: Decimal = items.iter().map(|l| l.balance).sum();
    if total_balance == Decimal::ZERO {
        return Err(CorpFinanceError::DivisionByZero {
            context: "liability_mix total balance is zero".into(),
        });
    }
    let weighted_sum: Decimal = items.iter().map(|l| l.balance * l.cost_rate).sum();
    Ok(weighted_sum / total_balance)
}

// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------

fn validate_nim_input(input: &NimAnalysisInput) -> CorpFinanceResult<()> {
    if input.earning_assets <= Decimal::ZERO {
        return Err(CorpFinanceError::InvalidInput {
            field: "earning_assets".into(),
            reason: "Earning assets must be positive.".into(),
        });
    }
    if input.interest_income < Decimal::ZERO {
        return Err(CorpFinanceError::InvalidInput {
            field: "interest_income".into(),
            reason: "Interest income cannot be negative.".into(),
        });
    }
    if input.interest_expense < Decimal::ZERO {
        return Err(CorpFinanceError::InvalidInput {
            field: "interest_expense".into(),
            reason: "Interest expense cannot be negative.".into(),
        });
    }
    for item in &input.asset_mix {
        if item.balance < Decimal::ZERO {
            return Err(CorpFinanceError::InvalidInput {
                field: "asset_mix.balance".into(),
                reason: format!("Asset '{}' has negative balance.", item.name),
            });
        }
    }
    for item in &input.liability_mix {
        if item.balance < Decimal::ZERO {
            return Err(CorpFinanceError::InvalidInput {
                field: "liability_mix.balance".into(),
                reason: format!("Liability '{}' has negative balance.", item.name),
            });
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn approx_eq(a: Decimal, b: Decimal, eps: Decimal) -> bool {
        (a - b).abs() < eps
    }

    fn sample_assets() -> Vec<AssetMixItem> {
        vec![
            AssetMixItem {
                name: "Commercial Loans".into(),
                balance: dec!(500_000_000),
                yield_rate: dec!(0.055),
            },
            AssetMixItem {
                name: "Mortgage Loans".into(),
                balance: dec!(300_000_000),
                yield_rate: dec!(0.04),
            },
            AssetMixItem {
                name: "Securities".into(),
                balance: dec!(200_000_000),
                yield_rate: dec!(0.03),
            },
        ]
    }

    fn sample_liabilities() -> Vec<LiabilityMixItem> {
        vec![
            LiabilityMixItem {
                name: "Demand Deposits".into(),
                balance: dec!(400_000_000),
                cost_rate: dec!(0.005),
            },
            LiabilityMixItem {
                name: "Time Deposits".into(),
                balance: dec!(300_000_000),
                cost_rate: dec!(0.025),
            },
            LiabilityMixItem {
                name: "Wholesale Funding".into(),
                balance: dec!(200_000_000),
                cost_rate: dec!(0.035),
            },
        ]
    }

    fn base_input() -> NimAnalysisInput {
        NimAnalysisInput {
            interest_income: dec!(45_000_000),
            interest_expense: dec!(17_000_000),
            earning_assets: dec!(1_000_000_000),
            asset_mix: sample_assets(),
            liability_mix: sample_liabilities(),
            prior_interest_income: dec!(42_000_000),
            prior_interest_expense: dec!(15_000_000),
            prior_earning_assets: dec!(950_000_000),
            rate_sensitive_assets: dec!(600_000_000),
            rate_sensitive_liabilities: dec!(500_000_000),
        }
    }

    #[test]
    fn test_basic_nim_calculation() {
        let input = base_input();
        let out = analyze_nim(&input).unwrap();
        // NIM = (45M - 17M) / 1B = 0.028
        assert_eq!(out.nim, dec!(0.028));
        assert_eq!(out.net_interest_income, dec!(28_000_000));
    }

    #[test]
    fn test_nim_as_percentage() {
        let input = base_input();
        let out = analyze_nim(&input).unwrap();
        // 2.8% NIM is typical for a bank
        let nim_pct = out.nim * dec!(100);
        assert!(nim_pct > dec!(2) && nim_pct < dec!(5));
    }

    #[test]
    fn test_weighted_avg_asset_yield() {
        let input = base_input();
        let out = analyze_nim(&input).unwrap();
        // 500M*5.5% + 300M*4% + 200M*3% = 27.5M+12M+6M = 45.5M
        // Total assets = 1B -> yield = 0.0455
        let expected = dec!(0.0455);
        assert!(approx_eq(out.asset_yield, expected, dec!(0.0001)));
    }

    #[test]
    fn test_weighted_avg_liability_cost() {
        let input = base_input();
        let out = analyze_nim(&input).unwrap();
        // 400M*0.5% + 300M*2.5% + 200M*3.5% = 2M+7.5M+7M = 16.5M
        // Total liabilities = 900M -> cost = 0.01833...
        let expected = dec!(16_500_000) / dec!(900_000_000);
        assert!(approx_eq(out.liability_cost, expected, dec!(0.00001)));
    }

    #[test]
    fn test_spread_positive() {
        let input = base_input();
        let out = analyze_nim(&input).unwrap();
        assert!(
            out.spread > Decimal::ZERO,
            "Spread should be positive for a profitable bank"
        );
    }

    #[test]
    fn test_spread_equals_yield_minus_cost() {
        let input = base_input();
        let out = analyze_nim(&input).unwrap();
        let expected_spread = out.asset_yield - out.liability_cost;
        assert!(approx_eq(out.spread, expected_spread, dec!(0.000001)));
    }

    #[test]
    fn test_rate_volume_variance_sums_to_total_change() {
        let input = base_input();
        let out = analyze_nim(&input).unwrap();
        let prior_nii = dec!(42_000_000) - dec!(15_000_000); // 27M
        let total_change = out.net_interest_income - prior_nii;
        let variance_sum = out.rate_volume_variance.rate_effect
            + out.rate_volume_variance.volume_effect
            + out.rate_volume_variance.mix_effect;
        assert!(
            approx_eq(variance_sum, total_change, dec!(0.01)),
            "Rate+Volume+Mix should sum to total NII change. Got {}, expected {}",
            variance_sum,
            total_change
        );
    }

    #[test]
    fn test_volume_effect_positive_when_assets_grow() {
        let input = base_input();
        let out = analyze_nim(&input).unwrap();
        // Earning assets grew from 950M to 1B, prior NII was positive
        assert!(
            out.rate_volume_variance.volume_effect > Decimal::ZERO,
            "Volume effect should be positive when assets grow"
        );
    }

    #[test]
    fn test_gap_analysis() {
        let input = base_input();
        let out = analyze_nim(&input).unwrap();
        // Gap = 600M - 500M = 100M
        assert_eq!(out.interest_sensitivity_gap, dec!(100_000_000));
    }

    #[test]
    fn test_gap_ratio() {
        let input = base_input();
        let out = analyze_nim(&input).unwrap();
        // Gap ratio = 100M / 1B = 0.1
        assert_eq!(out.gap_ratio, dec!(0.1));
    }

    #[test]
    fn test_negative_gap() {
        let mut input = base_input();
        input.rate_sensitive_assets = dec!(400_000_000);
        input.rate_sensitive_liabilities = dec!(600_000_000);
        let out = analyze_nim(&input).unwrap();
        assert_eq!(out.interest_sensitivity_gap, dec!(-200_000_000));
        assert!(out.gap_ratio < Decimal::ZERO);
    }

    #[test]
    fn test_zero_earning_assets_rejected() {
        let mut input = base_input();
        input.earning_assets = Decimal::ZERO;
        assert!(analyze_nim(&input).is_err());
    }

    #[test]
    fn test_negative_earning_assets_rejected() {
        let mut input = base_input();
        input.earning_assets = dec!(-100);
        assert!(analyze_nim(&input).is_err());
    }

    #[test]
    fn test_negative_interest_income_rejected() {
        let mut input = base_input();
        input.interest_income = dec!(-1);
        assert!(analyze_nim(&input).is_err());
    }

    #[test]
    fn test_negative_asset_balance_rejected() {
        let mut input = base_input();
        input.asset_mix[0].balance = dec!(-100);
        assert!(analyze_nim(&input).is_err());
    }

    #[test]
    fn test_negative_liability_balance_rejected() {
        let mut input = base_input();
        input.liability_mix[0].balance = dec!(-100);
        assert!(analyze_nim(&input).is_err());
    }

    #[test]
    fn test_empty_asset_mix_yields_zero() {
        let mut input = base_input();
        input.asset_mix = vec![];
        let out = analyze_nim(&input).unwrap();
        assert_eq!(out.asset_yield, Decimal::ZERO);
    }

    #[test]
    fn test_empty_liability_mix_yields_zero() {
        let mut input = base_input();
        input.liability_mix = vec![];
        let out = analyze_nim(&input).unwrap();
        assert_eq!(out.liability_cost, Decimal::ZERO);
    }

    #[test]
    fn test_rising_rate_scenario() {
        // Higher current rates, same volume
        let input = NimAnalysisInput {
            interest_income: dec!(55_000_000),
            interest_expense: dec!(25_000_000),
            earning_assets: dec!(1_000_000_000),
            asset_mix: vec![AssetMixItem {
                name: "Loans".into(),
                balance: dec!(1_000_000_000),
                yield_rate: dec!(0.055),
            }],
            liability_mix: vec![LiabilityMixItem {
                name: "Deposits".into(),
                balance: dec!(800_000_000),
                cost_rate: dec!(0.03125),
            }],
            prior_interest_income: dec!(45_000_000),
            prior_interest_expense: dec!(17_000_000),
            prior_earning_assets: dec!(1_000_000_000),
            rate_sensitive_assets: dec!(700_000_000),
            rate_sensitive_liabilities: dec!(500_000_000),
        };
        let out = analyze_nim(&input).unwrap();
        // NIM = (55M-25M)/1B = 0.03
        assert_eq!(out.nim, dec!(0.03));
        // Volume effect should be 0 (same earning assets)
        assert_eq!(out.rate_volume_variance.volume_effect, Decimal::ZERO);
        // Rate effect should capture the improvement
        assert!(out.rate_volume_variance.rate_effect > Decimal::ZERO);
    }

    #[test]
    fn test_prior_earning_assets_zero_gives_zero_variance() {
        let mut input = base_input();
        input.prior_earning_assets = Decimal::ZERO;
        let out = analyze_nim(&input).unwrap();
        assert_eq!(out.rate_volume_variance.rate_effect, Decimal::ZERO);
        assert_eq!(out.rate_volume_variance.volume_effect, Decimal::ZERO);
        assert_eq!(out.rate_volume_variance.mix_effect, Decimal::ZERO);
    }

    #[test]
    fn test_serialization_roundtrip() {
        let input = base_input();
        let out = analyze_nim(&input).unwrap();
        let json = serde_json::to_string(&out).unwrap();
        let _: NimAnalysisOutput = serde_json::from_str(&json).unwrap();
    }

    #[test]
    fn test_typical_community_bank() {
        let input = NimAnalysisInput {
            interest_income: dec!(12_000_000),
            interest_expense: dec!(3_000_000),
            earning_assets: dec!(300_000_000),
            asset_mix: vec![
                AssetMixItem {
                    name: "CRE Loans".into(),
                    balance: dec!(150_000_000),
                    yield_rate: dec!(0.05),
                },
                AssetMixItem {
                    name: "C&I Loans".into(),
                    balance: dec!(100_000_000),
                    yield_rate: dec!(0.045),
                },
                AssetMixItem {
                    name: "Treasuries".into(),
                    balance: dec!(50_000_000),
                    yield_rate: dec!(0.025),
                },
            ],
            liability_mix: vec![
                LiabilityMixItem {
                    name: "Core Deposits".into(),
                    balance: dec!(200_000_000),
                    cost_rate: dec!(0.008),
                },
                LiabilityMixItem {
                    name: "CDs".into(),
                    balance: dec!(50_000_000),
                    cost_rate: dec!(0.03),
                },
            ],
            prior_interest_income: dec!(11_500_000),
            prior_interest_expense: dec!(2_800_000),
            prior_earning_assets: dec!(290_000_000),
            rate_sensitive_assets: dec!(180_000_000),
            rate_sensitive_liabilities: dec!(120_000_000),
        };
        let out = analyze_nim(&input).unwrap();
        // NIM = 9M / 300M = 0.03
        assert_eq!(out.nim, dec!(0.03));
        assert!(out.spread > Decimal::ZERO);
        assert_eq!(out.interest_sensitivity_gap, dec!(60_000_000));
    }
}