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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
use std::marker::PhantomData;
use rust_decimal::prelude::FromPrimitive;
use crate::base::DecimalNumber;
use crate::calendar::*;
use crate::{BaseMoney, BaseOps, Currency, Decimal, base::Amount, macros::dec};
/// Trait defining interest calculation operations for fixed and compounding interest.
pub trait InterestOps<C> {
type InterestBuilder<'a>
where
Self: 'a;
/// Calculate fixed-interest on loan.
///
/// # Formula
/// FV = PV × (1 + (r × t))
///
/// PV = FV / (1 + (r × t))
///
/// PMT = P × r × (1+r)ᵗ / \[(1+r)ᵗ − 1\]
///
/// # Argument
/// rate: impl DecimalNumber, supports Decimal, f64, i32, i64, i128.
/// Rate is the percentage number only, e.g. 25% -> rate = 25.
///
/// # Return
/// It returns interest builder to set rate(daily, monthly, yearly) with periods(daily, monthly, yearly) of payment,
/// along with day, month and year of calculations.
///
/// The default rate is yearly and period is 12 months.
/// The default year, month and day of calculation is current date.
/// The default of rate days is Actual/Actual.
fn interest_fixed<R>(&self, rate: R) -> Option<Self::InterestBuilder<'_>>
where
R: DecimalNumber;
/// Calculate compounding-interest on loan.
///
/// # Formula
/// FV = PV × (1 + r)ᵗ
///
/// PV = FV / (1 + r)ᵗ
///
/// # Argument
/// rate: impl DecimalNumber, supports Decimal, f64, i32, i64, i128.
/// Rate is the percentage number only, e.g. 25% -> rate = 25.
///
/// # Return
/// It returns interest builder to set rate(daily, monthly, yearly) with periods(daily, monthly, yearly) of payment,
/// along with day, month and year of calculations.
///
/// The default rate is yearly and period is 12 months.
/// The default year, month and day of calculation is current date.
/// The default of rate days is Actual/Actual.
fn interest_compound<R>(&self, rate: R) -> Option<Self::InterestBuilder<'_>>
where
R: DecimalNumber;
}
impl<M, C> InterestOps<C> for M
where
M: BaseMoney<C> + BaseOps<C> + Amount<C>,
C: Currency,
{
type InterestBuilder<'a>
= Interest<'a, M, C>
where
Self: 'a;
fn interest_fixed<R>(&self, rate: R) -> Option<Self::InterestBuilder<'_>>
where
R: DecimalNumber,
{
let current_date = current_date()?;
Some(Interest {
principal: self.amount(),
rate_percent: RatePercent::Yearly(rate.get_decimal()?), // default to annual rate
total_period: Period::Months(12),
interest_type: InterestType::Fixed,
rate_days: Default::default(),
year: current_date.0,
month: current_date.1,
day: current_date.2,
contribs: None,
tax: None,
_output: PhantomData,
_currency: PhantomData,
})
}
fn interest_compound<R>(&self, rate: R) -> Option<Self::InterestBuilder<'_>>
where
R: DecimalNumber,
{
let current_date = current_date()?;
Some(Interest {
principal: self.amount(),
rate_percent: RatePercent::Yearly(rate.get_decimal()?), // default to annual rate
total_period: Period::Months(12),
interest_type: InterestType::Compounding,
rate_days: Default::default(),
year: current_date.0,
month: current_date.1,
day: current_date.2,
contribs: None,
tax: None,
_output: PhantomData,
_currency: PhantomData,
})
}
}
/// Builder for interest calculations. Built through `self::InterestOps` trait.
#[derive(Debug, Clone, Copy)]
pub struct Interest<'a, M, C> {
/// principal amount
principal: Decimal,
/// percentage of interest rate(daily, monthly, yearly)
rate_percent: RatePercent,
/// period of payment, including compounding points(daily, monthly, yearly)
total_period: Period,
/// interest type
interest_type: InterestType,
/// rate days for calculating interest rate
rate_days: RateDays,
/// year of the calculation
year: u32,
/// index of the month calculation, January -> 1
month: u32,
/// day
day: u32,
/// contributions each period(addition or negation)
contribs: Option<&'a [M]>,
/// flat-rate tax applies to each period
tax: Option<Decimal>,
_output: PhantomData<M>,
_currency: PhantomData<C>,
}
impl<'a, M, C> Interest<'a, M, C> {
/// Add contributions each period.
/// Length of contribs is at MOST length of period - 1,
/// since contribution add on the second time of the period length.
/// Value can be positive or negative and can be skipped by adding zero.
pub fn with_contribs(self, contribs: &'a [M]) -> Option<Self> {
let period_length: usize = self.total_period.get_period_length().try_into().ok()?;
if contribs.len() >= period_length {
return None;
}
Some(Self {
contribs: Some(contribs),
..self
})
}
/// Set tax flat-rate percentage applied to interest returns.
/// The tax is expressed as a percentage number, e.g. 20% -> tax = 20.
///
/// The tax is flat-rate, meaning it applies no matter how much the return is.
///
/// # Argument
/// D: impl DecimalNumber, supports Decimal, f64, i32, i64, i128.
///
pub fn with_tax<D>(self, tax: D) -> Option<Self>
where
D: crate::base::DecimalNumber,
{
Some(Self {
tax: Some(tax.get_decimal()?),
..self
})
}
}
#[derive(Debug, Clone, Copy)]
enum RatePercent {
Daily(Decimal),
Monthly(Decimal),
Yearly(Decimal),
}
impl RatePercent {
const fn get_rate_amount(&self) -> Decimal {
match self {
Self::Daily(v) | Self::Monthly(v) | Self::Yearly(v) => *v,
}
}
/// Get the actual rate relative to daily payment period.
///
/// - if rate is daily then r = r
/// - if rate is monthly then r = r / number of days in that month
/// - if rate is yearly/annual then r = r / number of days in that year
fn get_daily_rate(&self, rate_days: RateDays, year: u32, month: u32) -> Option<Decimal> {
match self {
Self::Daily(v) => v.checked_div(dec!(100)),
Self::Monthly(v) => v
.checked_div(Decimal::from_u32(rate_days.days_in_month(year, month)?)?)?
.checked_div(dec!(100)),
Self::Yearly(v) => v
.checked_div(Decimal::from_u32(rate_days.days_in_year(year)?)?)?
.checked_div(dec!(100)),
}
}
/// Get the actual rate relative to monthly payment period.
///
/// - if rate is daily then r = r * number of days in that month
/// - if rate is monthly then r = r
/// - if rate is yearly then r = r / 12
fn get_monthly_rate(&self, rate_days: RateDays, year: u32, month: u32) -> Option<Decimal> {
match self {
Self::Daily(v) => v
.checked_mul(Decimal::from_u32(rate_days.days_in_month(year, month)?)?)?
.checked_div(dec!(100)),
Self::Monthly(v) => v.checked_div(dec!(100)),
Self::Yearly(v) => v
.checked_div(Decimal::from_u32(12)?)?
.checked_div(dec!(100)),
}
}
/// Get the actual rate relative to yearly/annual payment period.
///
/// - if rate is daily then r = r * number of days in that year
/// - if rate is monthly then r = r * 12
/// - if rate is yearly then r = r
fn get_yearly_rate(&self, rate_days: RateDays, year: u32) -> Option<Decimal> {
match self {
Self::Daily(v) => v
.checked_mul(Decimal::from_u32(rate_days.days_in_year(year)?)?)?
.checked_div(dec!(100)),
Self::Monthly(v) => v
.checked_mul(Decimal::from_u32(12)?)?
.checked_div(dec!(100)),
Self::Yearly(v) => v.checked_div(dec!(100)),
}
}
fn get_quarterly_rate(&self, rate_days: RateDays, year: u32, month: u32) -> Option<Decimal> {
match self {
Self::Daily(v) => {
let (first_month_year, first_month) = (year, month);
let (second_month_year, second_month, _) =
first_month.next_month(first_month_year)?;
let (third_month_year, third_month, _) =
second_month.next_month(second_month_year)?;
let total_days = rate_days
.days_in_month(year, first_month)?
.checked_add(rate_days.days_in_month(second_month_year, second_month)?)?
.checked_add(rate_days.days_in_month(third_month_year, third_month)?)?;
v.checked_mul(Decimal::from_u32(total_days)?)?
.checked_div(dec!(100))
}
Self::Monthly(v) => {
let quarter_rate = v.checked_mul(dec!(3))?;
quarter_rate.checked_div(dec!(100))
}
Self::Yearly(v) => {
let quarter_rate = v.checked_div(dec!(4))?;
quarter_rate.checked_div(dec!(100))
}
}
}
fn get_semi_annualy_rate(&self, rate_days: RateDays, year: u32, month: u32) -> Option<Decimal> {
match self {
Self::Daily(v) => {
let (first_month_year, first_month) = (year, month);
let (second_month_year, second_month, _) =
first_month.next_month(first_month_year)?;
let (third_month_year, third_month, _) =
second_month.next_month(second_month_year)?;
let (fourth_month_year, fourth_month, _) =
third_month.next_month(third_month_year)?;
let (fifth_month_year, fifth_month, _) =
fourth_month.next_month(fourth_month_year)?;
let (sixth_month_year, sixth_month, _) =
fifth_month.next_month(fifth_month_year)?;
let total_days = rate_days
.days_in_month(first_month_year, first_month)?
.checked_add(rate_days.days_in_month(second_month_year, second_month)?)?
.checked_add(rate_days.days_in_month(third_month_year, third_month)?)?
.checked_add(rate_days.days_in_month(fourth_month_year, fourth_month)?)?
.checked_add(rate_days.days_in_month(fifth_month_year, fifth_month)?)?
.checked_add(rate_days.days_in_month(sixth_month_year, sixth_month)?)?;
v.checked_mul(Decimal::from_u32(total_days)?)?
.checked_div(dec!(100))
}
Self::Monthly(v) => {
let quarter_rate = v.checked_mul(dec!(6))?;
quarter_rate.checked_div(dec!(100))
}
Self::Yearly(v) => {
let quarter_rate = v.checked_div(dec!(2))?;
quarter_rate.checked_div(dec!(100))
}
}
}
}
#[derive(Debug, Clone, Copy)]
enum InterestType {
Fixed,
Compounding,
}
#[derive(Debug, Clone, Copy)]
enum Period {
Days(u32),
Months(u32),
Years(u32),
Quarters(u32),
SemiAnnuals(u32),
}
impl Period {
fn get_period_length(&self) -> u32 {
match self {
Period::Days(t)
| Period::Months(t)
| Period::Years(t)
| Period::Quarters(t)
| Period::SemiAnnuals(t) => *t,
}
}
}
/// Get number of days in a month and in a year according to ISO 15022 MT565: (16) Field 22F
#[derive(Debug, Clone, Copy, Default)]
pub enum RateDays {
/// 30 days per month / 360 days per year (Bond Basis)
Rate30360,
/// 30 days per month / 365 days per year
Rate30365,
/// 30 days per month / Actual days in the year (365 or 366)
Rate30Actual,
/// Actual days per month / 360 days per year (Money Market)
RateActual360,
/// Actual days per month / 365 days per year (Retail Banking)
RateActual365,
/// Actual days per month / Actual days in the year (Treasury)
#[default]
RateActualActual,
}
impl RateDays {
fn days_in_month(&self, year: u32, month: u32) -> Option<u32> {
match self {
Self::Rate30360 | Self::Rate30365 | Self::Rate30Actual => Some(30),
Self::RateActual360 | Self::RateActual365 | Self::RateActualActual => {
days_in_month(year, month)
}
}
}
fn days_in_year(&self, year: u32) -> Option<u32> {
match self {
Self::Rate30360 | Self::RateActual360 => Some(360),
Self::Rate30365 | Self::RateActual365 => Some(365),
Self::Rate30Actual | Self::RateActualActual => Some(days_in_year(year)),
}
}
}
impl<'a, M, C> Interest<'a, M, C>
where
M: BaseMoney<C> + BaseOps<C> + Default,
C: Currency,
{
/// Sets the interest rate to daily.
pub const fn daily(self) -> Self {
Self {
rate_percent: RatePercent::Daily(self.rate_percent.get_rate_amount()),
..self
}
}
/// Sets the period of interest payments each day for n days.
pub const fn days(self, n: u32) -> Self {
Self {
total_period: Period::Days(n),
..self
}
}
/// Sets the interest rate to monthly.
pub const fn monthly(self) -> Self {
Self {
rate_percent: RatePercent::Monthly(self.rate_percent.get_rate_amount()),
..self
}
}
/// Sets the period of interest payments each month for n months.
pub const fn months(self, n: u32) -> Self {
Self {
total_period: Period::Months(n),
..self
}
}
/// Sets the interest rate to yearly/annual.
pub const fn yearly(self) -> Self {
Self {
rate_percent: RatePercent::Yearly(self.rate_percent.get_rate_amount()),
..self
}
}
/// Sets the period of interest payments each year for n years.
pub const fn years(self, n: u32) -> Self {
Self {
total_period: Period::Years(n),
..self
}
}
/// Sets the period of interest payments every 3 months.
pub const fn quarters(self, n: u32) -> Self {
Self {
total_period: Period::Quarters(n),
..self
}
}
/// Sets the period of interest payments every 6 months.
pub const fn semi_annuals(self, n: u32) -> Self {
Self {
total_period: Period::SemiAnnuals(n),
..self
}
}
/// Sets start of the calculation year.
pub const fn year(self, year: u32) -> Self {
Self { year, ..self }
}
/// Sets start of the calculation month by index, January = 1.
pub const fn month(self, month: u32) -> Self {
Self { month, ..self }
}
/// Set start of the calculation day date.
pub const fn day(self, day: u32) -> Self {
Self { day, ..self }
}
/// Set rate days
pub const fn rate_days(self, rate_days: RateDays) -> Self {
Self { rate_days, ..self }
}
/// Calculate the returns(total interests)
pub fn returns(&self) -> Option<M> {
match self.interest_type {
InterestType::Fixed => interest_impl::get_returns_fixed(self),
InterestType::Compounding => interest_impl::get_returns_compounding(self),
}
}
/// Calculate the future value of a money: Principal + Interests.
pub fn future_value(&self) -> Option<M>
where
M: BaseMoney<C> + BaseOps<C> + Amount<C>,
{
interest_impl::get_future_value(self)
}
/// Calculate the present value of future goal.
pub fn present_value(&self) -> Option<M>
where
M: BaseMoney<C> + BaseOps<C> + Amount<C>,
{
match self.interest_type {
InterestType::Fixed => interest_impl::get_present_value_fixed(self),
InterestType::Compounding => interest_impl::get_present_value_compounding(self),
}
}
/// Calculate amortized payment(PMT)
/// PMT = P × r × (1+r)ⁿ / [(1+r)ⁿ − 1]
/// where r is the period rate and n is the total number of periods.
/// PMT is amortized against fixed-rate loan.
pub fn payment(&self) -> Option<M> {
match self.interest_type {
InterestType::Fixed => interest_impl::get_pmt(self),
_ => None,
}
}
}
// ===========================================================================
// ============================= Implementations =============================
// ===========================================================================
mod interest_impl {
use crate::{
BaseMoney, BaseOps, Currency, IterOps,
accounting::interest::{Interest, InterestType, Period},
base::Amount,
calendar::{AddMonths, get_years_months, get_years_months_days},
macros::dec,
};
/// Get total returns of fixed-rate
///
/// FV = PV * (1 + (r * t))
pub(crate) fn get_returns_fixed<M, C>(bld: &Interest<M, C>) -> Option<M>
where
M: BaseMoney<C> + BaseOps<C> + Default,
C: Currency,
{
let total_interest = match bld.total_period {
Period::Days(t) => {
let years_months_days = get_years_months_days(bld.year, bld.month, bld.day, t)?;
let mut interest_total = dec!(0);
let mut current_principal = bld.principal;
let mut contrib_index = 0;
for year in years_months_days {
for month in year.1 {
for _day in month.1 {
interest_total = interest_total.checked_add(
current_principal.checked_mul(bld.rate_percent.get_daily_rate(
bld.rate_days,
year.0,
month.0,
)?)?,
)?;
if let Some(contribs) = bld.contribs {
let contrib = if let Some(c) = contribs.get(contrib_index) {
c.amount()
} else {
dec!(0)
};
current_principal = current_principal.checked_add(contrib)?;
if current_principal <= dec!(0) {
return Some(M::default());
}
contrib_index = contrib_index.checked_add(1)?;
}
}
}
}
Some(interest_total)
}
Period::Months(t) => {
let year_months = get_years_months(bld.year, bld.month, t)?;
let mut total_interest = dec!(0);
let mut current_principal = bld.principal;
let mut contrib_index = 0;
for (year, months) in year_months {
for month in months {
total_interest = total_interest.checked_add(
current_principal.checked_mul(bld.rate_percent.get_monthly_rate(
bld.rate_days,
year,
month,
)?)?,
)?;
if let Some(contribs) = bld.contribs {
let contrib = if let Some(c) = contribs.get(contrib_index) {
c.amount()
} else {
dec!(0)
};
current_principal = current_principal.checked_add(contrib)?;
if current_principal <= dec!(0) {
return Some(M::default());
}
contrib_index = contrib_index.checked_add(1)?;
}
}
}
Some(total_interest)
}
Period::Years(t) => {
let mut interest_total = dec!(0);
let mut current_year = bld.year;
let mut current_principal = bld.principal;
let mut contrib_index = 0;
for _y in 0..t {
interest_total = interest_total.checked_add(
current_principal.checked_mul(
bld.rate_percent
.get_yearly_rate(bld.rate_days, current_year)?,
)?,
)?;
current_year = current_year.checked_add(1)?;
if let Some(contribs) = bld.contribs {
let contrib = if let Some(c) = contribs.get(contrib_index) {
c.amount()
} else {
dec!(0)
};
current_principal = current_principal.checked_add(contrib)?;
if current_principal <= dec!(0) {
return Some(M::default());
}
contrib_index = contrib_index.checked_add(1)?;
}
}
Some(interest_total)
}
Period::Quarters(t) => {
let mut total_interest = dec!(0);
let mut current_year = bld.year;
let mut current_month = bld.month;
let mut current_principal = bld.principal;
let mut contrib_index = 0;
for _q in 0..t {
total_interest = total_interest.checked_add(current_principal.checked_mul(
bld.rate_percent.get_quarterly_rate(
bld.rate_days,
current_year,
current_month,
)?,
)?)?;
let (next_quarter_year, next_quarter_month, _) =
current_month.add_months(current_year, 3)?;
current_year = next_quarter_year;
current_month = next_quarter_month;
if let Some(contribs) = bld.contribs {
let contrib = if let Some(c) = contribs.get(contrib_index) {
c.amount()
} else {
dec!(0)
};
current_principal = current_principal.checked_add(contrib)?;
if current_principal <= dec!(0) {
return Some(M::default());
}
contrib_index = contrib_index.checked_add(1)?;
}
}
Some(total_interest)
}
Period::SemiAnnuals(t) => {
let mut total_interest = dec!(0);
let mut current_year = bld.year;
let mut current_month = bld.month;
let mut current_principal = bld.principal;
let mut contrib_index = 0;
for _s in 0..t {
total_interest = total_interest.checked_add(current_principal.checked_mul(
bld.rate_percent.get_semi_annualy_rate(
bld.rate_days,
current_year,
current_month,
)?,
)?)?;
let (next_halfyear_year, next_halfyear_month, _) =
current_month.add_months(current_year, 6)?;
current_year = next_halfyear_year;
current_month = next_halfyear_month;
if let Some(contribs) = bld.contribs {
let contrib = if let Some(c) = contribs.get(contrib_index) {
c.amount()
} else {
dec!(0)
};
current_principal = current_principal.checked_add(contrib)?;
if current_principal <= dec!(0) {
return Some(M::default());
}
contrib_index = contrib_index.checked_add(1)?;
}
}
Some(total_interest)
}
};
M::new(total_interest?).ok()
}
/// Get total returns of compounding rate.
///
/// FV = PV * (1 + r)^t
pub(crate) fn get_returns_compounding<M, C>(bld: &Interest<M, C>) -> Option<M>
where
M: BaseMoney<C> + BaseOps<C> + Default,
C: Currency,
{
let total_interest = match bld.total_period {
Period::Days(t) => {
let years_months_days = get_years_months_days(bld.year, bld.month, bld.day, t)?;
let mut total_interest = dec!(0);
let mut current_principal = bld.principal;
let mut contrib_index = 0;
for year in years_months_days {
for month in year.1 {
for _day in month.1 {
let current_interest = current_principal.checked_mul(
bld.rate_percent
.get_daily_rate(bld.rate_days, year.0, month.0)?,
)?;
total_interest = total_interest.checked_add(current_interest)?;
current_principal = current_principal.checked_add(current_interest)?;
if let Some(contribs) = bld.contribs {
let contrib = if let Some(c) = contribs.get(contrib_index) {
c.amount()
} else {
dec!(0)
};
current_principal = current_principal.checked_add(contrib)?;
if current_principal <= dec!(0) {
return Some(M::default());
}
contrib_index = contrib_index.checked_add(1)?;
}
}
}
}
Some(total_interest)
}
Period::Months(t) => {
let years_months = get_years_months(bld.year, bld.month, t)?;
let mut total_interest = dec!(0);
let mut current_principal = bld.principal;
let mut contrib_index = 0;
for year in years_months {
for month in year.1 {
let current_interest = current_principal.checked_mul(
bld.rate_percent
.get_monthly_rate(bld.rate_days, year.0, month)?,
)?;
total_interest = total_interest.checked_add(current_interest)?;
current_principal = current_principal.checked_add(current_interest)?;
if let Some(contribs) = bld.contribs {
let contrib = if let Some(c) = contribs.get(contrib_index) {
c.amount()
} else {
dec!(0)
};
current_principal = current_principal.checked_add(contrib)?;
if current_principal <= dec!(0) {
return Some(M::default());
}
contrib_index = contrib_index.checked_add(1)?;
}
}
}
Some(total_interest)
}
Period::Years(t) => {
let mut total_interest = dec!(0);
let mut current_principal = bld.principal;
let mut current_year = bld.year;
let mut contrib_index = 0;
for _y in 0..t {
let current_interest = current_principal.checked_mul(
bld.rate_percent
.get_yearly_rate(bld.rate_days, current_year)?,
)?;
total_interest = total_interest.checked_add(current_interest)?;
current_principal = current_principal.checked_add(current_interest)?;
current_year = current_year.checked_add(1)?;
if let Some(contribs) = bld.contribs {
let contrib = if let Some(c) = contribs.get(contrib_index) {
c.amount()
} else {
dec!(0)
};
current_principal = current_principal.checked_add(contrib)?;
if current_principal <= dec!(0) {
return Some(M::default());
}
contrib_index = contrib_index.checked_add(1)?;
}
}
Some(total_interest)
}
Period::Quarters(t) => {
let mut current_principal = bld.principal;
let mut total_interest = dec!(0);
let mut current_year = bld.year;
let mut current_month = bld.month;
let mut contrib_index = 0;
for _q in 0..t {
let current_interest =
current_principal.checked_mul(bld.rate_percent.get_quarterly_rate(
bld.rate_days,
current_year,
current_month,
)?)?;
total_interest = total_interest.checked_add(current_interest)?;
current_principal = current_principal.checked_add(current_interest)?;
let (next_quarter_year, next_quarter_month, _) =
current_month.add_months(current_year, 3)?;
current_year = next_quarter_year;
current_month = next_quarter_month;
if let Some(contribs) = bld.contribs {
let contrib = if let Some(c) = contribs.get(contrib_index) {
c.amount()
} else {
dec!(0)
};
current_principal = current_principal.checked_add(contrib)?;
if current_principal <= dec!(0) {
return Some(M::default());
}
contrib_index = contrib_index.checked_add(1)?;
}
}
Some(total_interest)
}
Period::SemiAnnuals(t) => {
let mut current_principal = bld.principal;
let mut total_interest = dec!(0);
let mut current_year = bld.year;
let mut current_month = bld.month;
let mut contrib_index = 0;
for _q in 0..t {
let current_interest =
current_principal.checked_mul(bld.rate_percent.get_semi_annualy_rate(
bld.rate_days,
current_year,
current_month,
)?)?;
total_interest = total_interest.checked_add(current_interest)?;
current_principal = current_principal.checked_add(current_interest)?;
let (next_halfyear_year, next_halfyear_month, _) =
current_month.add_months(current_year, 6)?;
current_year = next_halfyear_year;
current_month = next_halfyear_month;
if let Some(contribs) = bld.contribs {
let contrib = if let Some(c) = contribs.get(contrib_index) {
c.amount()
} else {
dec!(0)
};
current_principal = current_principal.checked_add(contrib)?;
if current_principal <= dec!(0) {
return Some(M::default());
}
contrib_index = contrib_index.checked_add(1)?;
}
}
Some(total_interest)
}
};
M::new(total_interest?).ok()
}
use crate::PercentOps;
/// Get future value: principal + contributions + total interests
///
/// FV = PV * (1 + (r * t))
pub(crate) fn get_future_value<C, M>(bld: &Interest<M, C>) -> Option<M>
where
M: BaseMoney<C> + BaseOps<C> + Amount<C> + Default + PercentOps<C, Output = M>,
C: Currency,
{
let principal = bld.principal;
let returns = {
let mut returns = match bld.interest_type {
InterestType::Fixed => get_returns_fixed(bld)?,
InterestType::Compounding => get_returns_compounding(bld)?,
};
// apply tax if it exists
if let Some(tax) = bld.tax {
returns = returns.percent_sub(tax)?;
}
returns
};
let mut total_contribs = M::default();
if let Some(contribs) = bld.contribs
&& !contribs.is_empty()
{
total_contribs = total_contribs.checked_add(contribs.checked_sum()?)?;
}
returns.checked_add(principal)?.checked_add(total_contribs)
}
/// Get present value on fixed-rate interest
///
/// PV = FV / (1 + (r * t))
pub(crate) fn get_present_value_fixed<C, M>(bld: &Interest<M, C>) -> Option<M>
where
M: BaseMoney<C> + BaseOps<C>,
C: Currency,
{
let ret = match bld.total_period {
Period::Days(t) => {
let years_months_days = get_years_months_days(bld.year, bld.month, bld.day, t)?;
let mut actual_r = dec!(0);
for year in years_months_days {
for month in year.1 {
for _day in month.1 {
actual_r = actual_r.checked_add(bld.rate_percent.get_daily_rate(
bld.rate_days,
year.0,
month.0,
)?)?;
}
}
}
let divisor = dec!(1).checked_add(actual_r)?;
bld.principal.checked_div(divisor)
}
Period::Months(t) => {
let years_months = get_years_months(bld.year, bld.month, t)?;
let mut actual_r = dec!(0);
for year in years_months {
for month in year.1 {
actual_r = actual_r.checked_add(bld.rate_percent.get_monthly_rate(
bld.rate_days,
year.0,
month,
)?)?;
}
}
let divisor = dec!(1).checked_add(actual_r)?;
bld.principal.checked_div(divisor)
}
Period::Years(t) => {
let mut actual_r = dec!(0);
let mut current_year = bld.year;
for _y in 0..t {
actual_r = actual_r.checked_add(
bld.rate_percent
.get_yearly_rate(bld.rate_days, current_year)?,
)?;
current_year = current_year.checked_add(1)?;
}
let divisor = dec!(1).checked_add(actual_r)?;
bld.principal.checked_div(divisor)
}
Period::Quarters(t) => {
let mut actual_r = dec!(0);
let mut current_year = bld.year;
let mut current_month = bld.month;
for _q in 0..t {
actual_r = actual_r.checked_add(bld.rate_percent.get_quarterly_rate(
bld.rate_days,
current_year,
current_month,
)?)?;
let (next_quarter_year, next_quarter_month, _) =
current_month.add_months(current_year, 3)?;
current_year = next_quarter_year;
current_month = next_quarter_month;
}
let divisor = dec!(1).checked_add(actual_r)?;
bld.principal.checked_div(divisor)
}
Period::SemiAnnuals(t) => {
let mut actual_r = dec!(0);
let mut current_year = bld.year;
let mut current_month = bld.month;
for _q in 0..t {
actual_r = actual_r.checked_add(bld.rate_percent.get_semi_annualy_rate(
bld.rate_days,
current_year,
current_month,
)?)?;
let (next_halfyear_year, next_halfyear_month, _) =
current_month.add_months(current_year, 6)?;
current_year = next_halfyear_year;
current_month = next_halfyear_month;
}
let divisor = dec!(1).checked_add(actual_r)?;
bld.principal.checked_div(divisor)
}
};
M::new(ret?).ok()
}
/// Get present value on compounding-rate interest
///
/// PV = FV / (1 + r)^t
pub(crate) fn get_present_value_compounding<C, M>(bld: &Interest<M, C>) -> Option<M>
where
M: BaseMoney<C> + BaseOps<C>,
C: Currency,
{
let ret = match bld.total_period {
Period::Days(t) => {
let years_months_days = get_years_months_days(bld.year, bld.month, bld.day, t)?;
let mut divisor = dec!(1);
for year in years_months_days {
for month in year.1 {
for _day in month.1 {
let d = dec!(1).checked_add(bld.rate_percent.get_daily_rate(
bld.rate_days,
year.0,
month.0,
)?)?;
divisor = divisor.checked_mul(d)?;
}
}
}
bld.principal.checked_div(divisor)
}
Period::Months(t) => {
let years_months = get_years_months(bld.year, bld.month, t)?;
let mut divisor = dec!(1);
for year in years_months {
for month in year.1 {
let d = dec!(1).checked_add(bld.rate_percent.get_monthly_rate(
bld.rate_days,
year.0,
month,
)?)?;
divisor = divisor.checked_mul(d)?;
}
}
bld.principal.checked_div(divisor)
}
Period::Years(t) => {
let mut current_year = bld.year;
let mut divisor = dec!(1);
for _y in 0..t {
let d = dec!(1).checked_add(
bld.rate_percent
.get_yearly_rate(bld.rate_days, current_year)?,
)?;
divisor = divisor.checked_mul(d)?;
current_year = current_year.checked_add(1)?;
}
bld.principal.checked_div(divisor)
}
Period::Quarters(t) => {
let mut divisor = dec!(1);
let mut current_year = bld.year;
let mut current_month = bld.month;
for _q in 0..t {
let d = dec!(1).checked_add(bld.rate_percent.get_quarterly_rate(
bld.rate_days,
current_year,
current_month,
)?)?;
divisor = divisor.checked_mul(d)?;
let (next_quarter_year, next_quarter_month, _) =
current_month.add_months(current_year, 3)?;
current_year = next_quarter_year;
current_month = next_quarter_month;
}
bld.principal.checked_div(divisor)
}
Period::SemiAnnuals(t) => {
let mut divisor = dec!(1);
let mut current_year = bld.year;
let mut current_month = bld.month;
for _q in 0..t {
let d = dec!(1).checked_add(bld.rate_percent.get_semi_annualy_rate(
bld.rate_days,
current_year,
current_month,
)?)?;
divisor = divisor.checked_mul(d)?;
let (next_halfyear_year, next_halfyear_month, _) =
current_month.add_months(current_year, 6)?;
current_year = next_halfyear_year;
current_month = next_halfyear_month;
}
bld.principal.checked_div(divisor)
}
};
M::new(ret?).ok()
}
/// Get PMT payment on fixed-rate interest
///
/// PMT = P × r × (1+r)ⁿ / [(1+r)ⁿ − 1]
///
/// PMT is calculated against fixed-rate loan.
pub(crate) fn get_pmt<C, M>(bld: &Interest<M, C>) -> Option<M>
where
M: BaseMoney<C> + BaseOps<C>,
C: Currency,
{
let pmt = match bld.total_period {
Period::Years(t) => {
// c accumulates (1+r)ⁿ; r_period holds the last period rate.
let mut c = dec!(1);
let mut r_period = dec!(0);
let mut current_year = bld.year;
for _ in 0..t {
let r = bld
.rate_percent
.get_yearly_rate(bld.rate_days, current_year)?;
r_period = r;
// (1+r)ⁿ
c = c.checked_mul(dec!(1).checked_add(r)?)?;
current_year = current_year.checked_add(1)?;
}
// PMT = P × r × (1+r)ⁿ / [(1+r)ⁿ − 1]
let c_minus_1 = c.checked_sub(dec!(1))?;
let d = r_period.checked_mul(c)?.checked_div(c_minus_1)?;
bld.principal.checked_mul(d)
}
Period::Months(t) => {
let mut c = dec!(1);
let mut r_period = dec!(0);
let years_months = get_years_months(bld.year, bld.month, t)?;
for year in years_months {
for month in year.1.iter() {
let r = bld
.rate_percent
.get_monthly_rate(bld.rate_days, year.0, *month)?;
r_period = r;
// (1+r)ⁿ
c = c.checked_mul(dec!(1).checked_add(r)?)?;
}
}
// PMT = P × r × (1+r)ⁿ / [(1+r)ⁿ − 1]
let c_minus_1 = c.checked_sub(dec!(1))?;
let d = r_period.checked_mul(c)?.checked_div(c_minus_1)?;
bld.principal.checked_mul(d)
}
Period::Days(t) => {
let mut c = dec!(1);
let mut r_period = dec!(0);
let years_months_days = get_years_months_days(bld.year, bld.month, bld.day, t)?;
for year in years_months_days {
for month in year.1 {
for _day in month.1.iter() {
let r =
bld.rate_percent
.get_daily_rate(bld.rate_days, year.0, month.0)?;
r_period = r;
// (1+r)ⁿ
c = c.checked_mul(dec!(1).checked_add(r)?)?;
}
}
}
// PMT = P × r × (1+r)ⁿ / [(1+r)ⁿ − 1]
let c_minus_1 = c.checked_sub(dec!(1))?;
let d = r_period.checked_mul(c)?.checked_div(c_minus_1)?;
bld.principal.checked_mul(d)
}
Period::Quarters(t) => {
let mut c = dec!(1);
let mut r_period = dec!(0);
let mut current_year = bld.year;
let mut current_month = bld.month;
for _ in 0..t {
let r = bld.rate_percent.get_quarterly_rate(
bld.rate_days,
current_year,
current_month,
)?;
r_period = r;
c = c.checked_mul(dec!(1).checked_add(r)?)?;
let (next_year, next_month, _) = current_month.add_months(current_year, 3)?;
current_year = next_year;
current_month = next_month;
}
// PMT = P × r × (1+r)ⁿ / [(1+r)ⁿ − 1]
let c_minus_1 = c.checked_sub(dec!(1))?;
let d = r_period.checked_mul(c)?.checked_div(c_minus_1)?;
bld.principal.checked_mul(d)
}
Period::SemiAnnuals(t) => {
let mut c = dec!(1);
let mut r_period = dec!(0);
let mut current_year = bld.year;
let mut current_month = bld.month;
for _ in 0..t {
let r = bld.rate_percent.get_semi_annualy_rate(
bld.rate_days,
current_year,
current_month,
)?;
r_period = r;
c = c.checked_mul(dec!(1).checked_add(r)?)?;
let (next_year, next_month, _) = current_month.add_months(current_year, 6)?;
current_year = next_year;
current_month = next_month;
}
// PMT = P × r × (1+r)ⁿ / [(1+r)ⁿ − 1]
let c_minus_1 = c.checked_sub(dec!(1))?;
let d = r_period.checked_mul(c)?.checked_div(c_minus_1)?;
bld.principal.checked_mul(d)
}
};
M::new(pmt?).ok()
}
}