1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package com.nickokiss.investor.calc;
22
23 import java.math.BigDecimal;
24
25 import com.nickokiss.investor.fin.element.Annuity;
26 import com.nickokiss.investor.fin.element.StreamElement;
27 import com.nickokiss.investor.fin.env.CompoundingStrategy;
28 import com.nickokiss.investor.fin.env.ConstantInterestRateStrategy;
29 import com.nickokiss.investor.fin.env.Env;
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 public class AnnuityCalc {
45
46 private MathCalc mathCalc = new MathCalc();
47 private CompoundInterestCalc intCalc = new CompoundInterestCalc();
48
49
50
51
52 public BigDecimal getPresentValue(BigDecimal annualAmount, BigDecimal interestRate, BigDecimal periodsPerYear, BigDecimal numberOfPeriods) {
53
54
55 BigDecimal growth = intCalc.getGrowth(interestRate, periodsPerYear, numberOfPeriods.negate());
56
57 BigDecimal factor = mathCalc.ONE.subtract(growth);
58
59 BigDecimal perpetualAnnuityPV = mathCalc.div(annualAmount, interestRate);
60
61 return perpetualAnnuityPV.multiply(factor);
62 }
63
64
65
66
67 public BigDecimal getPresentValue(BigDecimal periodAmount, BigDecimal periodInterestRate, BigDecimal numberOfPeriods) {
68
69
70 return getPresentValue(periodAmount, periodInterestRate, mathCalc.ONE, numberOfPeriods);
71 }
72
73
74
75
76
77
78
79
80
81 public BigDecimal getPeriodAmount(BigDecimal presentValue, BigDecimal periodInterestRate, BigDecimal numberOfPeriods) {
82
83 BigDecimal growth = intCalc.getGrowth(periodInterestRate, mathCalc.ONE, numberOfPeriods);
84
85 BigDecimal factor = mathCalc.div(growth, growth.subtract(mathCalc.ONE));
86
87 return presentValue.multiply(periodInterestRate).multiply(factor);
88 }
89
90
91
92
93
94
95
96
97
98
99
100
101 public BigDecimal getNumberOfPeriods(BigDecimal presentValue, BigDecimal periodAmount, BigDecimal periodInterestRate) {
102
103
104 BigDecimal logNumber = mathCalc.ONE.subtract(mathCalc.div(presentValue.multiply(periodInterestRate), periodAmount));
105
106 BigDecimal base = mathCalc.ONE.add(periodInterestRate);
107
108 return mathCalc.log(base, logNumber).negate();
109 }
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125 public BigDecimal getValue(Annuity annuity, BigDecimal interestRate, CompoundingStrategy cs, BigDecimal time) {
126
127 Env env = new Env();
128 env.setCompoundingStrategy(cs);
129 env.setInterestRateStrategy(new ConstantInterestRateStrategy(interestRate));
130
131 BigDecimal elementValue = mathCalc.div(annuity.getAnnualAmount(), interestRate);
132 StreamElement annuityElement = new StreamElement();
133 annuityElement.setValue(elementValue);
134 annuityElement.setTime(annuity.getLenght());
135 return elementValue.subtract(annuityElement.getValue(env, time));
136 }
137
138 }