finance-solution 0.4.1

Finance math: TVM, cashflow, amortization, equity path metrics, technical analysis (SMA/EMA/WMA/HMA/MACD/BB/Keltner/Donchian/Stoch/VWAP/RVOL/RSI/ATR/LinReg), and options (BSM, Black76, GK, CRR American) with Result-only APIs, solutions, tables, and incremental state.
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
//! **Present value calculations.** Given a final amount, a number of periods such as years, and fixed
//! or varying interest rates, what is the current value?
//!
//! For most common usages, we recommend the [`present_value_solution`](./fn.present_value_solution.html) function to provide a better debugging experience and additional features.
//!
//! If you have a more complicated use case which has varying rates per period, use the [`present_value_schedule_solution`](./fn.present_value_schedule_solution.html) function.
//!
// ! If you need to calculate the future value given a present value, a number of periods, and one
// ! or more rates use [`future_value`] or related functions.
// !
// ! If you need to calculate a fixed rate given a present value, future value, and number of periods
// ! use [`rate`] or related functions.
// !
// ! If you need to calculate the number of periods given a fixed rate and a present and future value
// ! use [`periods`] or related functions.
//! # Formulas
//!
//! ## Simple Compounding
//!
//! With simple compound interest, the present value is calculated with:
//!
//! > <img src="http://i.upmath.me/svg/present%5C_value%20%3D%20%7Bfuture%5C_value%20%5Cover%20(1%2Brate)%5E%7Bperiods%7D%7D" />
//!
//! Or using some more usual variable names:
//!
//! > <img src="http://i.upmath.me/svg/pv%20%3D%20%7Bfv%20%5Cover%20(1%2Br)%5En%7D" />
//!
//! `n` is often used for the number of periods, though it may be `t` for time if each period is
//! assumed to be one year as in continuous compounding. `r` is the periodic rate, though this may
//! appear as `i` for interest.
//!
//! Throughout this crate we use `pv` for present value and `fv` for future value. You may see these
//! values called `P` for principal in some references.
//!
//! Within the [TvmSolution](././tvm_simple/struct.TvmSolution.html) struct we record the formula used for the particular calculation
//! using both concrete values and symbols. For example if we calculated the present value of an
//! investment that grows by 1.5% per month for 48 months using simple compounding and reaches a
//! future value of $50,000 the solution struct would contain these fields:
//! ```text
//! formula: "24468.0848 = 50000.0000 / (1.015000 ^ 48)",
//! symbolic_formula: "pv = fv / (1 + r)^n",
//! ```
//!
//! ## Continuous Compounding
//!
//! With continuous compounding the formula is:
//!
//! > <img src="http://i.upmath.me/svg/present%5C_value%20%3D%20%7Bfuture%5C_value%20%5Cover%20e%5E%7Brate%20%5Ctimes%20periods%7D%7D" />
//!
//! or:
//!
//! > <img src="http:i.upmath.me/svg/pv%20%3D%20%7Bfv%20%5Cover%20e%5E%7Br%20%5Ctimes%20n%7D%7D" />
//!
//! With continuous compounding the period is assumed to be years and `t` (time) is often used as
//! the variable name. Within this crate we stick with `n` for the number of periods so that it's
//! easier to compare formulas when they're printed as simple text as part of the [TvmSolution](./struct.TvmSolution.html)
//! struct. Taking the example above but switching to continuous compounding the struct would
//! contain these fields:
//! ```text
//! formula: "24337.6128 = 50000.0000 / 2.718282^(0.015000 * 48)",
//! symbolic_formula: "pv = fv / e^(rt)",
//! ```
use log::warn;

use super::tvm::*;

/// Returns the current value of a future amount using a fixed rate.
///
/// Related functions:
/// * To calculate a present value with a fixed rate and return a struct that shows the formula and
/// optionally produces the the period-by-period values use [`present_value_solution`](./fn.present_value_solution.html).
/// * To calculate the present value if the rates vary by period use [`present_value_schedule`](./fn.present_value_schedule.html)
/// or [`present_value_schedule_solution`](./fn.present_value_schedule_solution.html).
///
/// See the [present_value](./index.html) module page for the formulas.
///
/// # Arguments
/// * `rate` - The rate at which the investment grows or shrinks per period,
/// expressed as a floating point number. For instance 0.05 would mean 5% growth. Often appears as
/// `r` or `i` in formulas.
/// * `periods` - The number of periods such as quarters or years. Often appears as `n` or `t`.
/// * `future_value` - The final value of the investment.
/// * `continuous_compounding` - True for continuous compounding, false for simple compounding.
///
/// # Errors
/// The call returns [`FinanceError`] if `rate` is less than -1.0 as this would mean the investment is
/// losing more than its full value every period. It returns an error also if the future value is zero as
/// in this case there's no way to determine the present value.
///
/// # Examples
/// Investment that grows month by month.
/// ```
/// use finance_solution::*;
///
/// // The investment will grow by 1.1% per month.
/// let rate = 0.011;
///
/// // The investment will grow for 12 months.
/// let periods = 12;
///
/// // The final value will be $50,000.
/// let future_value = 50_000;
///
/// let continuous_compounding = false;
///
/// // Find the current value.
/// let present_value = present_value(rate, periods, future_value as f64, continuous_compounding).unwrap();
/// dbg!(&present_value);
///
/// // Confirm that the present value is correct to four decimal places (one hundredth of a cent).
/// assert_rounded_4(-43_848.6409, present_value);
/// ```
/// Error case: rate less than −100% per period is outside the domain.
/// ```
/// # use finance_solution::{present_value, FinanceError};
/// let rate = -1.05;
/// let periods = 6;
/// let future_value = -10_000.75;
/// let err = present_value(rate, periods, future_value, false).unwrap_err();
/// assert!(matches!(err, FinanceError::InvalidRate { .. }));
/// ```
/// # Errors
/// Returns [`FinanceError::InvalidRate`] if `rate < -1.0`, [`FinanceError::ZeroValue`] if
/// `future_value` is zero/subnormal, or [`FinanceError::NonFinite`] for non-finite values.
///
/// # Examples
/// ```
/// use finance_solution::{present_value, FinanceError, FinanceResult};
///
/// assert!(present_value(0.05, 10, 1000.0, false).is_ok());
///
/// match present_value(-1.5, 10, 1000.0, false) {
///     Err(FinanceError::InvalidRate { rate }) => assert_eq!(rate, -1.5),
///     other => panic!("expected InvalidRate, got {other:?}"),
/// }
///
/// match present_value(0.05, 10, 0.0, false) {
///     Err(FinanceError::ZeroValue { field }) => assert_eq!(field, "future_value"),
///     other => panic!("expected ZeroValue, got {other:?}"),
/// }
///
/// fn discount(fv: f64) -> FinanceResult<f64> {
///     present_value(0.06, 8, fv, false)
/// }
/// match discount(50_000.0) {
///     Ok(pv) => assert!(pv < 0.0),
///     Err(e) => panic!("{e}"),
/// }
/// ```
pub fn present_value<T, C>(
    rate: f64,
    periods: u32,
    future_value: T,
    compounding: C,
) -> crate::FinanceResult<f64>
where
    T: Into<f64> + Copy,
    C: Into<crate::Compounding>,
{
    present_value_internal(
        rate,
        periods as f64,
        future_value.into(),
        compounding.into().is_continuous(),
    )
}

/// Calculates the current value of a future amount using a fixed rate and returns a struct
/// with the inputs and the calculated value. This is used for keeping track of a collection of
/// financial scenarios so that they can be examined later.
///
/// See the [present_value](./index.html) module page for the formulas.
///
/// Related functions:
/// * For simply calculating a single present value using a fixed rate use [`present_value`](./fn.present_value.html).
/// * To calculate the present value if the rates vary by period use [`present_value_schedule`](./fn.present_value_schedule.html)
/// or [`present_value_schedule_solution`](./fn.present_value_schedule_solution.html).
///
/// # Arguments
/// * `rate` - The rate at which the investment grows or shrinks per period,
/// expressed as a floating point number. For instance 0.05 would mean 5% growth. Often appears as
/// `r` or `i` in formulas.
/// * `periods` - The number of periods such as quarters or years. Often appears as `n` or `t`.
/// * `future_value` - The final value of the investment.
/// * `continuous_compounding` - True for continuous compounding, false for simple compounding.
///
/// # Errors
/// The call returns [`FinanceError`] if `rate` is less than -1.0 as this would mean the investment is
/// losing more than its full value every period. It returns an error also if the future value is zero as
/// in this case there's no way to determine the present value.
///
/// # Examples
/// Calculate a present value and examine the period-by-period values.
/// ```
/// use finance_solution::*;
///
/// // The rate is 8.45% per year.
/// let rate = 0.0845;
///
/// // The investment will grow for six years.
/// let periods = 6;
///
/// // The final value is $50,000.
/// let future_value = 50_000;
///
/// let continuous_compounding = false;
///
/// // Calculate the present value and create a struct with the input values and
/// // the formula used.
/// let solution = present_value_solution(rate, periods, future_value, continuous_compounding).unwrap();
/// dbg!(&solution);
///
/// let present_value = solution.present_value();
/// assert_rounded_4(present_value, -30_732.1303);
///
/// // Examine the formulas.
/// let formula = solution.formula();
/// dbg!(&formula);
/// assert_eq!(formula, "-30732.1303 = -50000.0000 / (1.084500 ^ 6)");
/// let symbolic_formula = solution.symbolic_formula();
/// dbg!(&symbolic_formula);
/// assert_eq!("pv = -fv / (1 + r)^n", symbolic_formula);
///
/// // Calculate the amount at the end of each period.
/// let series = solution.series();
/// dbg!(&series);
/// ```
/// Build a collection of present value calculations where the future value and periodic rate are
/// fixed but the number of periods varies, then filter the results.
/// ```
/// // The rate is 0.9% per month.
/// # use finance_solution::*;
/// let rate = 0.009;
///
/// // The final value is $100,000.
/// let future_value = 100_000;
///
/// let continuous_compounding = false;
///
/// // We'll keep a collection of the calculated present values along with their inputs.
/// let mut scenarios = vec![];
///
/// // Calculate the present value for terms ranging from 1 to 36 months.
/// for periods in 1..=36 {
///     // Calculate the future value for this number of months and add the details to the
///     // collection.
///     scenarios.push(present_value_solution(rate, periods, future_value, continuous_compounding).unwrap());
/// }
/// dbg!(&scenarios);
/// assert_eq!(36, scenarios.len());
///
/// // Keep only the scenarios where the present value (which is negative) is greater than or
/// // than or equal to -$80,000.
/// scenarios.retain(|x| x.present_value() >= -80_000.00);
/// dbg!(&scenarios);
/// assert_eq!(12, scenarios.len());
///
/// // Find the range of months for the remaining scenarios.
/// let min_months = scenarios.iter().map(|x| x.periods()).min().unwrap();
/// let max_months = scenarios.iter().map(|x| x.periods()).max().unwrap();
/// dbg!(min_months, max_months);
/// assert_eq!(25, min_months);
/// assert_eq!(36, max_months);
///
/// // Check the formulas for the first of the remaining scenarios.
/// let formula = scenarios[0].formula();
/// dbg!(&formula);
/// assert_eq!("-79932.0303 = -100000.0000 / (1.009000 ^ 25)", formula);
/// let symbolic_formula = scenarios[0].symbolic_formula();
/// dbg!(&symbolic_formula);
/// assert_eq!("pv = -fv / (1 + r)^n", symbolic_formula);
///
/// ```
/// Error case: rate less than −100% per period is outside the domain.
/// ```
/// # use finance_solution::{present_value_solution, FinanceError};
/// let rate = -1.11;
/// let periods = 12;
/// let future_value = 100_000.85;
/// let err = present_value_solution(rate, periods, future_value, false).unwrap_err();
/// assert!(matches!(err, FinanceError::InvalidRate { .. }));
/// ```
pub fn present_value_solution<T, C>(
    rate: f64,
    periods: u32,
    future_value: T,
    compounding: C,
) -> crate::FinanceResult<TvmSolution>
where
    T: Into<f64> + Copy,
    C: Into<crate::Compounding>,
{
    present_value_solution_internal(
        rate,
        periods as f64,
        future_value.into(),
        compounding.into().is_continuous(),
    )
}

/// Calculates a present value based on rates that change for each period.
///
/// Related functions:
/// * To calculate the present value with varying rates and return a struct that can produce the
/// period-by-period values use [`present_value_schedule_solution`](./fn.present_value_schedule_solution.html).
/// * If there is a single fixed rate use [present_value](./fn.present_value.html) or [present_value_solution](./fn.present_value_solution.html).
///
/// # Arguments
/// * `rates` - A collection of rates, one for each period.
/// * `future_value` - The ending value of the investment.
///
/// # Errors
/// The call returns [`FinanceError`] if any of the rates is less than -1.0 as this would mean the investment is
/// losing more than its full value every period. It returns an error also if the future value is zero as
/// in this case there's no way to determine the present value.
///
/// # Examples
/// Calculate the present value of an investment whose rates vary by year.
/// ```
/// // The annual rate varies from -3.4% to 12.9%.
/// let rates = [0.04, -0.034, 0.0122, 0.129, 8.5];
///
/// // The value of the investment after applying all of these periodic rates
/// // will be $30_000.
/// let future_value = 30_000.00;
///
/// // Calculate the present value.
/// let present_value = finance_solution::present_value_schedule(&rates, future_value).unwrap();
/// dbg!(&present_value);
/// ```
pub fn present_value_schedule<T>(rates: &[f64], future_value: T) -> crate::FinanceResult<f64>
where
    T: Into<f64> + Copy,
{
    let future_value = future_value.into();
    crate::util::error::require_rates(rates)?;
    crate::util::error::require_money("future_value", future_value)?;
    if !future_value.is_normal() {
        return Err(crate::FinanceError::ZeroValue {
            field: "future_value",
        });
    }
    let periods = rates.len();
    let mut present_value = -future_value;
    for i in (0..periods).rev() {
        present_value /= 1.0 + rates[i];
    }
    if present_value.is_finite() {
        Ok(present_value)
    } else {
        Err(crate::FinanceError::NonFinite {
            field: "present_value",
            value: present_value,
        })
    }
}

/// Calculates a present value based on rates that change for each period and returns a struct
/// with the inputs and the calculated value.
///
/// Related functions:
/// * To calculate the present value as a single number if the rates vary by period use
/// [present_value_schedule](./fn.present_value_schedule.html).
/// * If there is a single fixed rate use [present_value](./fn.present_value.html) or
/// [present_value_solution](./fn.present_value_solution.html).
///
/// # Arguments
/// * `rates` - A collection of rates, one for each period.
/// * `future_value` - The ending value of the investment.
///
/// # Errors
/// The call returns [`FinanceError`] if any of the rates is less than -1.0 as this would mean the investment is
/// losing more than its full value every period. It returns an error also if the future value is zero as
/// in this case there's no way to determine the present value.
///
/// # Examples
/// Calculate the value of an investment whose rates vary by year, then view only those periods
/// where the rate is negative.
/// ```
/// use finance_solution::*;
///
/// // The quarterly rate varies from -0.5% to 4%.
/// let rates = [0.04, 0.008, 0.0122, -0.005];
///
/// // The value of the investment after applying all of these periodic rates
/// // will be $25_000.
/// let future_value = 25_000.00;
///
/// // Calculate the present value and keep track of the inputs and the formula
/// // in a struct.
/// let solution = present_value_schedule_solution(&rates, future_value).unwrap();
/// dbg!(&solution);
///
/// let present_value = solution.present_value();
/// assert_rounded_4(present_value, -23_678.6383);
///
/// // Calculate the value for each period.
/// let series = solution.series();
/// dbg!(&series);
/// ```
pub fn present_value_schedule_solution<T>(
    rates: &[f64],
    future_value: T,
) -> crate::FinanceResult<TvmScheduleSolution>
where
    T: Into<f64> + Copy,
{
    let future_value = future_value.into();
    let present_value = present_value_schedule(rates, future_value)?;
    Ok(TvmScheduleSolution::new(
        TvmVariable::PresentValue,
        rates,
        present_value,
        future_value,
    ))
}

pub(crate) fn present_value_internal(
    rate: f64,
    periods: f64,
    future_value: f64,
    continuous_compounding: bool,
) -> crate::FinanceResult<f64> {
    crate::util::error::require_rate(rate)?;
    crate::util::error::require_money("future_value", future_value)?;
    if !future_value.is_normal() {
        return Err(crate::FinanceError::ZeroValue {
            field: "future_value",
        });
    }
    if rate.abs() > 1.0 {
        warn!(
            "You provided a periodic rate ({}) greater than 1. Are you sure you expect a {}% return?",
            rate,
            rate * 100.0
        );
    }
    let present_value = if continuous_compounding {
        -future_value / std::f64::consts::E.powf(rate * periods)
    } else {
        -future_value / (1.0 + rate).powf(periods)
    };
    if present_value.is_finite() {
        Ok(present_value)
    } else {
        Err(crate::FinanceError::NonFinite {
            field: "present_value",
            value: present_value,
        })
    }
}

pub(crate) fn present_value_solution_internal(
    rate: f64,
    periods: f64,
    future_value: f64,
    continuous_compounding: bool,
) -> crate::FinanceResult<TvmSolution> {
    let present_value =
        present_value_internal(rate, periods, future_value, continuous_compounding)?;
    let rate_multiplier = 1.0 + rate;
    let (formula, symbolic_formula) = if continuous_compounding {
        let formula = format!(
            "{:.4} = {:.4} / {:.6}^({:.6} * {})",
            present_value,
            -future_value,
            std::f64::consts::E,
            rate,
            periods
        );
        let symbolic_formula = "pv = -fv / e^(rt)";
        (formula, symbolic_formula)
    } else {
        let formula = format!(
            "{:.4} = {:.4} / ({:.6} ^ {})",
            present_value, -future_value, rate_multiplier, periods
        );
        let symbolic_formula = "pv = -fv / (1 + r)^n";
        (formula, symbolic_formula)
    };
    Ok(TvmSolution::new_fractional_periods(
        TvmVariable::PresentValue,
        continuous_compounding,
        rate,
        periods,
        present_value,
        future_value,
        &formula,
        symbolic_formula,
    ))
}

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

    #[test]
    fn test_present_value_schedule() {
        let rates = [0.04, 0.07, -0.12, -0.03, 0.11];
        let future_value = 100_000.25;

        let present_value = present_value_schedule(&rates, future_value).unwrap();
        assert_rounded_4(-94843.2841, present_value);

        let solution = present_value_schedule_solution(&rates, future_value).unwrap();
        assert_rounded_4(100000.2500, solution.future_value());
        assert_rounded_4(-94843.2841, solution.present_value());

        let series = solution.series();
        assert_eq!(6, series.len());

        let period = &series[0];
        assert_eq!(0, period.period());
        assert_rounded_6(0.0, period.rate());
        assert_rounded_4(-present_value, period.value());

        let period = &series[1];
        assert_eq!(1, period.period());
        assert_rounded_6(0.04, period.rate());
        assert_rounded_4(98_637.0154, period.value());

        let period = &series[2];
        assert_eq!(2, period.period());
        assert_rounded_6(0.07, period.rate());
        assert_rounded_4(105_541.6065, period.value());

        let period = &series[3];
        assert_eq!(3, period.period());
        assert_rounded_6(-0.12, period.rate());
        assert_rounded_4(92_876.6137, period.value());

        let period = &series[4];
        assert_eq!(4, period.period());
        assert_rounded_6(-0.03, period.rate());
        assert_rounded_4(90_090.3153, period.value());

        let period = &series[5];
        assert_eq!(5, period.period());
        assert_rounded_6(0.11, period.rate());
        assert_rounded_4(100_000.2500, period.value());
    }

    /*
    macro_rules! compare_to_excel {
        ( $r:expr, $n:expr, $fv:expr, $pv_excel:expr, $pv_manual_simple:expr, $pv_manual_cont:expr ) => {
            println!("$r = {}, $n = {}, $fv = {}, $pv_excel: {}, $pv_manual_simple = {}, $pv_manual_cont = {}", $r, $n, $fv, $pv_excel, $pv_manual_simple, $pv_manual_cont);
            assert_approx_equal!($pv_excel, $pv_manual_simple);

            let pv_calc_simple = present_value($r, $n, $fv, false).unwrap();
            println!("pv_calc_simple = {}", pv_calc_simple);
            assert_approx_equal!($pv_excel, pv_calc_simple);

            let pv_calc_cont = present_value($r, $n, $fv, true).unwrap();
            println!("pv_calc_cont = {}", pv_calc_cont);
            assert_approx_equal!($pv_manual_cont, pv_calc_cont);

            let ratio = pv_calc_cont / pv_calc_simple;
            println!("ratio = {}", ratio);
            assert!(ratio > 0.0);
            assert!(ratio <= 1.0);
        }
    }
    */

    fn compare_to_excel(
        test_case: usize,
        r: f64,
        n: u32,
        fv: f64,
        pv_excel: f64,
        pv_manual_simple: f64,
        pv_manual_cont: f64,
    ) {
        let display = false;

        if display {
            println!("test_case = {}, r = {}, n = {}, fv = {}, pv_excel: {}, pv_manual_simple = {}, pv_manual_cont = {}", test_case, r, n, fv, pv_excel, pv_manual_simple, pv_manual_cont)
        };
        assert_approx_equal!(pv_excel, pv_manual_simple);

        let pv_calc_simple = present_value(r, n, fv, false).unwrap();
        if display {
            println!("pv_calc_simple = {}", pv_calc_simple)
        };
        assert_approx_equal!(pv_excel, pv_calc_simple);

        let pv_calc_cont = present_value(r, n, fv, true).unwrap();
        if display {
            println!("pv_calc_cont = {}", pv_calc_cont)
        };
        assert_approx_equal!(pv_manual_cont, pv_calc_cont);

        let ratio = pv_calc_cont / pv_calc_simple;
        if display {
            println!("ratio = {}", ratio)
        };
        assert!(ratio >= 0.0);
        assert!(ratio <= 1.0);

        // Solution with simple compounding.
        let solution = present_value_solution(r, n, fv, false).unwrap();
        if display {
            dbg!(&solution);
        }
        solution.invariant();
        assert!(solution.calculated_field().is_present_value());
        assert_eq!(false, solution.continuous_compounding());
        assert_approx_equal!(r, solution.rate());
        assert_eq!(n, solution.periods());
        assert_approx_equal!(n as f64, solution.fractional_periods());
        assert_approx_equal!(pv_excel, solution.present_value());
        assert_approx_equal!(fv, solution.future_value());

        // Solution with continuous compounding.
        let solution = present_value_solution(r, n, fv, true).unwrap();
        if display {
            dbg!(&solution);
        }
        solution.invariant();
        assert!(solution.calculated_field().is_present_value());
        assert!(solution.continuous_compounding());
        assert_approx_equal!(r, solution.rate());
        assert_eq!(n, solution.periods());
        assert_approx_equal!(n as f64, solution.fractional_periods());
        assert_approx_equal!(pv_manual_cont, solution.present_value());
        assert_approx_equal!(fv, solution.future_value());

        let rates = initialized_vector(n as usize, r);

        // Schedule solution.
        let solution = present_value_schedule_solution(&rates, fv).unwrap();
        if display {
            dbg!(&solution);
        }
        solution.invariant();
        assert!(solution.calculated_field().is_present_value());
        assert_eq!(n, solution.periods());
        assert_approx_equal!(pv_excel, solution.present_value());
        assert_approx_equal!(fv, solution.future_value());
    }

    #[test]
    fn test_present_value_against_excel() {
        compare_to_excel(
            1,
            0.01f64,
            90,
            1f64,
            -0.408391185151344f64,
            -0.408391185151344f64,
            -0.406569659740599f64,
        );
        compare_to_excel(
            2,
            -0.01f64,
            85,
            -1.5f64,
            3.52451788132823f64,
            3.52451788132823f64,
            3.50947027788899f64,
        );
        compare_to_excel(3, 0f64, 80, 2.25f64, -2.25f64, -2.25f64, -2.25f64);
        compare_to_excel(
            4,
            0.05f64,
            75,
            -3.375f64,
            0.0869113201859512f64,
            0.0869113201859512f64,
            0.0793723922640307f64,
        );
        compare_to_excel(
            5,
            -0.05f64,
            70,
            5.0625f64,
            -183.53236712846f64,
            -183.53236712846f64,
            -167.64697554088f64,
        );
        compare_to_excel(
            6,
            0.01f64,
            65,
            -7.59375f64,
            3.97710447262579f64,
            3.97710447262579f64,
            3.96428511727897f64,
        );
        compare_to_excel(
            7,
            -0.01f64,
            60,
            11.390625f64,
            -20.8178501685176f64,
            -20.8178501685176f64,
            -20.7550719606981f64,
        );
        compare_to_excel(
            8,
            0f64,
            55,
            -17.0859375f64,
            17.0859375f64,
            17.0859375f64,
            17.0859375f64,
        );
        compare_to_excel(
            9,
            0.05f64,
            50,
            25.62890625f64,
            -2.23493614322574f64,
            -2.23493614322574f64,
            -2.10374873426328f64,
        );
        compare_to_excel(
            10,
            -0.05f64,
            45,
            -38.443359375f64,
            386.597546504632f64,
            386.597546504632f64,
            364.740438412197f64,
        );
        compare_to_excel(
            11,
            0.01f64,
            40,
            57.6650390625f64,
            -38.7309044888379f64,
            -38.7309044888379f64,
            -38.6540316390219f64,
        );
        compare_to_excel(
            12,
            -0.01f64,
            35,
            -86.49755859375f64,
            122.962317182378f64,
            122.962317182378f64,
            122.745878432934f64,
        );
        compare_to_excel(
            13,
            0f64,
            30,
            129.746337890625f64,
            -129.746337890625f64,
            -129.746337890625f64,
            -129.746337890625f64,
        );
        compare_to_excel(
            14,
            0.05f64,
            25,
            -194.619506835937f64,
            57.4716797951039f64,
            57.4716797951039f64,
            55.7594222710607f64,
        );
        compare_to_excel(
            15,
            -0.05f64,
            20,
            291.929260253906f64,
            -814.33953749853f64,
            -814.33953749853f64,
            -793.546003343685f64,
        );
        compare_to_excel(
            16,
            0.01f64,
            15,
            -437.893890380859f64,
            377.179672510109f64,
            377.179672510109f64,
            376.898764278606f64,
        );
        compare_to_excel(
            17,
            -0.01f64,
            12,
            656.840835571289f64,
            -741.033445550103f64,
            -741.033445550103f64,
            -740.585974095395f64,
        );
        compare_to_excel(
            18,
            0f64,
            10,
            -985.261253356933f64,
            985.261253356933f64,
            985.261253356933f64,
            985.261253356933f64,
        );
        compare_to_excel(
            19,
            0.05f64,
            7,
            1477.8918800354f64,
            -1050.31016709206f64,
            -1050.31016709206f64,
            -1041.45280575294f64,
        );
        compare_to_excel(
            20,
            -0.05f64,
            5,
            -2216.8378200531f64,
            2864.94240503709f64,
            2864.94240503709f64,
            2846.47610562283f64,
        );
        compare_to_excel(
            21,
            0.01f64,
            4,
            3325.25673007965f64,
            -3195.50635796575f64,
            -3195.50635796575f64,
            -3194.87154873072f64,
        );
        compare_to_excel(
            22,
            -0.01f64,
            3,
            -4987.88509511947f64,
            5140.56501667989f64,
            5140.56501667989f64,
            5139.78881110503f64,
        );
        compare_to_excel(
            23,
            0f64,
            2,
            7481.82764267921f64,
            -7481.82764267921f64,
            -7481.82764267921f64,
            -7481.82764267921f64,
        );
        compare_to_excel(
            24,
            0.05f64,
            1,
            -11222.7414640188f64,
            10688.3252038274f64,
            10688.3252038274f64,
            10675.4019041389f64,
        );
        compare_to_excel(
            25,
            -0.05f64,
            0,
            16834.1121960282f64,
            -16834.1121960282f64,
            -16834.1121960282f64,
            -16834.1121960282f64,
        );
    }
}