@ratmath/finance 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +72 -0
- package/LICENSE +21 -0
- package/README.md +93 -2
- package/docs/llms.txt +123 -0
- package/index.d.ts +590 -0
- package/index.js +18 -0
- package/package.json +79 -4
- package/src/bonds.js +237 -0
- package/src/cashflow.js +218 -0
- package/src/life.js +160 -0
- package/src/loans.js +188 -0
- package/src/money.js +296 -0
- package/src/options.js +280 -0
- package/src/plan.js +11 -0
- package/src/portfolio.js +226 -0
- package/src/scenario.js +247 -0
- package/src/solve.js +125 -0
- package/src/tvm.js +157 -0
- package/src/uncertain.js +390 -0
package/src/scenario.js
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
// Scenarios: accounts, flows of money between them and rates that change,
|
|
2
|
+
// projected period by period into a table of balances. The projection is
|
|
3
|
+
// exact, so two scenarios can be compared to the cent, and because it is
|
|
4
|
+
// an exact rational function of its inputs its derivatives are exact too:
|
|
5
|
+
// `sensitivity` carries them through the projection alongside the values.
|
|
6
|
+
import { Rational } from "@ratmath/core";
|
|
7
|
+
import { refuse, amount, ZERO, ONE, Q, rounder, date } from "./money.js";
|
|
8
|
+
|
|
9
|
+
/** A value together with its derivative with respect to one chosen input. */
|
|
10
|
+
export class Dual {
|
|
11
|
+
constructor(v, d = ZERO) {
|
|
12
|
+
this.v = v;
|
|
13
|
+
this.d = d;
|
|
14
|
+
this.isDual = true;
|
|
15
|
+
}
|
|
16
|
+
add(o) {
|
|
17
|
+
return A.add(this, amount(o));
|
|
18
|
+
}
|
|
19
|
+
subtract(o) {
|
|
20
|
+
return A.sub(this, amount(o));
|
|
21
|
+
}
|
|
22
|
+
multiply(o) {
|
|
23
|
+
return A.mul(this, amount(o));
|
|
24
|
+
}
|
|
25
|
+
divide(o) {
|
|
26
|
+
return A.div(this, amount(o));
|
|
27
|
+
}
|
|
28
|
+
negate() {
|
|
29
|
+
return new Dual(this.v.negate(), this.d.negate());
|
|
30
|
+
}
|
|
31
|
+
pow(n) {
|
|
32
|
+
return A.pow(this, Number(n));
|
|
33
|
+
}
|
|
34
|
+
compareTo(o) {
|
|
35
|
+
return this.v.compareTo(A.val(amount(o)));
|
|
36
|
+
}
|
|
37
|
+
toString() {
|
|
38
|
+
return this.v.toString();
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const isD = (x) => x instanceof Dual;
|
|
42
|
+
const lift = (x) => (isD(x) ? x : new Dual(x, ZERO));
|
|
43
|
+
// arithmetic that works on Rationals and carries derivatives when a Dual is involved
|
|
44
|
+
const A = {
|
|
45
|
+
val: (x) => (isD(x) ? x.v : x),
|
|
46
|
+
add: (a, b) => (isD(a) || isD(b) ? new Dual(lift(a).v.add(lift(b).v), lift(a).d.add(lift(b).d)) : a.add(b)),
|
|
47
|
+
sub: (a, b) => (isD(a) || isD(b) ? new Dual(lift(a).v.subtract(lift(b).v), lift(a).d.subtract(lift(b).d)) : a.subtract(b)),
|
|
48
|
+
mul(a, b) {
|
|
49
|
+
if (!isD(a) && !isD(b)) return a.multiply(b);
|
|
50
|
+
const [x, y] = [lift(a), lift(b)];
|
|
51
|
+
return new Dual(x.v.multiply(y.v), x.d.multiply(y.v).add(x.v.multiply(y.d)));
|
|
52
|
+
},
|
|
53
|
+
div(a, b) {
|
|
54
|
+
if (!isD(a) && !isD(b)) return a.divide(b);
|
|
55
|
+
const [x, y] = [lift(a), lift(b)];
|
|
56
|
+
return new Dual(x.v.divide(y.v), x.d.multiply(y.v).subtract(x.v.multiply(y.d)).divide(y.v.multiply(y.v)));
|
|
57
|
+
},
|
|
58
|
+
pow(a, n) {
|
|
59
|
+
if (!isD(a)) return a.pow(n);
|
|
60
|
+
return n === 0 ? new Dual(ONE, ZERO) : new Dual(a.v.pow(n), a.d.multiply(a.v.pow(n - 1)).multiply(Q(n)));
|
|
61
|
+
},
|
|
62
|
+
neg: (a) => (isD(a) ? a.negate() : a.negate()),
|
|
63
|
+
sign: (a) => {
|
|
64
|
+
const n = A.val(a).numerator;
|
|
65
|
+
return n > 0n ? 1 : n < 0n ? -1 : 0;
|
|
66
|
+
},
|
|
67
|
+
cmp: (a, b) => A.val(a).compareTo(A.val(b)),
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const monthLabel = (start, k) => {
|
|
71
|
+
const d = start.addMonths(k);
|
|
72
|
+
return `${String(d.year).padStart(4, "0")}-${String(d.month).padStart(2, "0")}`;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
export class Scenario {
|
|
76
|
+
/**
|
|
77
|
+
* { periods, periodsPerYear = 12, start ("2027-01", optional), accounts,
|
|
78
|
+
* flows, rounding = false }.
|
|
79
|
+
* An account: { name, balance = 0, rate = 0 (annual, credited each period
|
|
80
|
+
* as rate/periodsPerYear; a negative balance is a debt and is charged the
|
|
81
|
+
* same way), rateChanges: [{ from: period, rate }], rates (one annual rate
|
|
82
|
+
* per period, overriding the others while it lasts) }.
|
|
83
|
+
* A flow: { name, amount, to, from, start = 1, end, every = 1, at (one
|
|
84
|
+
* period only), growth (a rate applied once a year from the flow's start),
|
|
85
|
+
* until: "paid" (stop when the `to` account is no longer in debt), then
|
|
86
|
+
* (an account that receives the money once that happens), index (one
|
|
87
|
+
* multiplier per period; a zero skips the period) }. A flow with
|
|
88
|
+
* only `to` is money arriving; with only `from`, money leaving.
|
|
89
|
+
* Each period: interest on the opening balances, then the flows in order.
|
|
90
|
+
*/
|
|
91
|
+
constructor({ periods, periodsPerYear = 12, start, accounts = [], flows = [], rounding = false, name } = {}) {
|
|
92
|
+
if (!Number.isInteger(periods) || periods < 1 || periods > 2400) refuse("bad-scenario", "periods is a whole number from 1 to 2400");
|
|
93
|
+
this.name = name;
|
|
94
|
+
this.periods = periods;
|
|
95
|
+
this.periodsPerYear = periodsPerYear;
|
|
96
|
+
this.start = start === undefined ? null : date(start);
|
|
97
|
+
if (this.start && periodsPerYear !== 12) refuse("bad-scenario", "a start month needs monthly periods");
|
|
98
|
+
this.rounding = rounding;
|
|
99
|
+
const when = (x, what) => {
|
|
100
|
+
if (x === undefined || x === null) return null;
|
|
101
|
+
if (Number.isInteger(x) && x >= 1) return x;
|
|
102
|
+
if (typeof x === "string" && this.start) {
|
|
103
|
+
const d = date(x);
|
|
104
|
+
return (d.year - this.start.year) * 12 + (d.month - this.start.month) + 1;
|
|
105
|
+
}
|
|
106
|
+
return refuse("bad-scenario", `${what} is a period number${this.start ? ' or a month such as "2028-06"' : ""}`);
|
|
107
|
+
};
|
|
108
|
+
const names = new Set();
|
|
109
|
+
this.accounts = accounts.map((a) => {
|
|
110
|
+
if (typeof a.name !== "string" || names.has(a.name)) refuse("bad-scenario", "each account has its own name");
|
|
111
|
+
names.add(a.name);
|
|
112
|
+
if (a.rates !== undefined && !Array.isArray(a.rates)) refuse("bad-scenario", "rates is a list of annual rates, one per period");
|
|
113
|
+
return { name: a.name, balance: amount(a.balance ?? 0), rate: amount(a.rate ?? 0), rates: a.rates ? a.rates.map(amount) : null, rateChanges: (a.rateChanges ?? []).map((c) => ({ from: when(c.from, "a rate change"), rate: amount(c.rate) })).sort((p, q) => p.from - q.from) };
|
|
114
|
+
});
|
|
115
|
+
if (!this.accounts.length) refuse("bad-scenario", "a scenario has at least one account");
|
|
116
|
+
const known = (n, f) => (n === undefined || n === null ? null : names.has(n) ? n : refuse("bad-scenario", `flow "${f}" names an account "${n}" that does not exist`));
|
|
117
|
+
this.flows = flows.map((f, k) => {
|
|
118
|
+
const label = f.name ?? `flow ${k + 1}`;
|
|
119
|
+
const flow = { name: label, amount: amount(f.amount), to: known(f.to, label), from: known(f.from, label), then: known(f.then, label), start: when(f.at ?? f.start, "a flow's start") ?? 1, end: f.at !== undefined ? when(f.at, "at") : when(f.end, "a flow's end"), every: f.every ?? 1, growth: f.growth === undefined ? null : amount(f.growth), index: f.index ? f.index.map(amount) : null, until: f.until ?? null };
|
|
120
|
+
if (f.index !== undefined && !Array.isArray(f.index)) refuse("bad-scenario", `flow "${label}": index is a list of multipliers, one per period`);
|
|
121
|
+
if (!flow.to && !flow.from) refuse("bad-scenario", `flow "${label}" needs an account to come from or go to`);
|
|
122
|
+
if (!Number.isInteger(flow.every) || flow.every < 1) refuse("bad-scenario", "every is a whole number of periods");
|
|
123
|
+
if (flow.until !== null && (flow.until !== "paid" || !flow.to)) refuse("bad-scenario", 'until is "paid", on a flow into an account that is in debt');
|
|
124
|
+
return flow;
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
/** The projection: one row per period. */
|
|
128
|
+
project() {
|
|
129
|
+
const r = this.rounding === false ? (x) => x : ((f) => (x) => (isD(x) ? refuse("bad-scenario", "sensitivity needs an unrounded scenario") : f(x)))(rounder(this.rounding));
|
|
130
|
+
const m = Q(this.periodsPerYear);
|
|
131
|
+
const bal = Object.fromEntries(this.accounts.map((a) => [a.name, a.balance]));
|
|
132
|
+
const rows = [];
|
|
133
|
+
const sums = { interest: Object.fromEntries(this.accounts.map((a) => [a.name, ZERO])), flows: Object.fromEntries(this.flows.map((f) => [f.name, ZERO])) };
|
|
134
|
+
const minimum = Object.fromEntries(this.accounts.map((a) => [a.name, { balance: a.balance, period: 0 }]));
|
|
135
|
+
let firstNegative = null;
|
|
136
|
+
const net = () => Object.values(bal).reduce((s, x) => A.add(s, x), ZERO);
|
|
137
|
+
const opening = { period: 0, date: this.start ? monthLabel(this.start, -1) : null, balances: { ...bal }, interest: {}, flows: {}, netWorth: net() };
|
|
138
|
+
for (let k = 1; k <= this.periods; k++) {
|
|
139
|
+
const row = { period: k, date: this.start ? monthLabel(this.start, k - 1) : null, interest: {}, flows: {} };
|
|
140
|
+
for (const a of this.accounts) {
|
|
141
|
+
let rate = a.rate;
|
|
142
|
+
for (const c of a.rateChanges) if (c.from <= k) rate = c.rate;
|
|
143
|
+
if (a.rates && k <= a.rates.length) rate = a.rates[k - 1];
|
|
144
|
+
const interest = r(A.mul(bal[a.name], A.div(rate, m)));
|
|
145
|
+
bal[a.name] = A.add(bal[a.name], interest);
|
|
146
|
+
row.interest[a.name] = interest;
|
|
147
|
+
sums.interest[a.name] = A.add(sums.interest[a.name], interest);
|
|
148
|
+
}
|
|
149
|
+
for (const f of this.flows) {
|
|
150
|
+
if (k < f.start || (f.end !== null && k > f.end) || (k - f.start) % f.every !== 0) continue;
|
|
151
|
+
let x = f.amount;
|
|
152
|
+
if (f.growth !== null) x = A.mul(x, A.pow(A.add(ONE, f.growth), Math.floor((k - f.start) / this.periodsPerYear)));
|
|
153
|
+
if (f.index && k <= f.index.length) {
|
|
154
|
+
if (f.index[k - 1].numerator === 0n) continue;
|
|
155
|
+
x = A.mul(x, f.index[k - 1]);
|
|
156
|
+
}
|
|
157
|
+
x = r(x);
|
|
158
|
+
let into = f.to;
|
|
159
|
+
let spill = null;
|
|
160
|
+
if (f.until === "paid") {
|
|
161
|
+
const owed = A.neg(bal[f.to]);
|
|
162
|
+
if (A.sign(owed) <= 0) {
|
|
163
|
+
if (!f.then) continue;
|
|
164
|
+
into = f.then;
|
|
165
|
+
} else if (A.cmp(x, owed) > 0) {
|
|
166
|
+
if (f.then) spill = A.sub(x, owed);
|
|
167
|
+
if (!f.then) x = owed;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (f.from) bal[f.from] = A.sub(bal[f.from], x);
|
|
171
|
+
if (spill) {
|
|
172
|
+
bal[into] = A.add(bal[into], A.sub(x, spill));
|
|
173
|
+
bal[f.then] = A.add(bal[f.then], spill);
|
|
174
|
+
} else if (into) bal[into] = A.add(bal[into], x);
|
|
175
|
+
row.flows[f.name] = x;
|
|
176
|
+
sums.flows[f.name] = A.add(sums.flows[f.name], x);
|
|
177
|
+
}
|
|
178
|
+
row.balances = { ...bal };
|
|
179
|
+
row.netWorth = net();
|
|
180
|
+
for (const a of this.accounts) {
|
|
181
|
+
if (A.cmp(bal[a.name], minimum[a.name].balance) < 0) minimum[a.name] = { balance: bal[a.name], period: k };
|
|
182
|
+
if (firstNegative === null && A.sign(bal[a.name]) < 0 && A.sign(a.balance) >= 0) firstNegative = { account: a.name, period: k, date: row.date };
|
|
183
|
+
}
|
|
184
|
+
rows.push(row);
|
|
185
|
+
}
|
|
186
|
+
return { name: this.name, opening, rows, final: { ...bal }, netWorth: net(), minimum, firstNegative, totals: sums, accounts: this.accounts.map((a) => a.name) };
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
export const scenario = (spec) => (spec instanceof Scenario ? spec : new Scenario(spec));
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Scenarios side by side: compare({ rent: {...}, buy: {...} }).
|
|
193
|
+
* { rows: [{ name, netWorth, difference (from the first), minimum }],
|
|
194
|
+
* best, series (net worth by period for each), crossovers (the periods at
|
|
195
|
+
* which the order of two scenarios changes) }. `measure` picks another
|
|
196
|
+
* outcome than final net worth.
|
|
197
|
+
*/
|
|
198
|
+
export function compare(scenarios, { measure = (p) => p.netWorth } = {}) {
|
|
199
|
+
const entries = Object.entries(scenarios);
|
|
200
|
+
if (entries.length < 2) refuse("bad-comparison", "compare at least two scenarios");
|
|
201
|
+
const runs = entries.map(([name, s]) => ({ name, projection: scenario(s).project() }));
|
|
202
|
+
const rows = runs.map(({ name, projection }) => ({ name, outcome: measure(projection), netWorth: projection.netWorth, firstNegative: projection.firstNegative, lowest: Object.entries(projection.minimum).reduce((m, [account, v]) => (m === null || v.balance.compareTo(m.balance) < 0 ? { account, ...v } : m), null) }));
|
|
203
|
+
rows.forEach((row) => (row.difference = row.outcome.subtract(rows[0].outcome)));
|
|
204
|
+
const best = rows.reduce((b, row) => (row.outcome.compareTo(b.outcome) > 0 ? row : b)).name;
|
|
205
|
+
const series = Object.fromEntries(runs.map(({ name, projection }) => [name, [projection.opening.netWorth, ...projection.rows.map((x) => x.netWorth)]]));
|
|
206
|
+
const crossovers = [];
|
|
207
|
+
for (let i = 0; i < runs.length; i++) {
|
|
208
|
+
for (let j = i + 1; j < runs.length; j++) {
|
|
209
|
+
const [a, b] = [series[runs[i].name], series[runs[j].name]];
|
|
210
|
+
let last = 0;
|
|
211
|
+
for (let k = 0; k < Math.min(a.length, b.length); k++) {
|
|
212
|
+
const s = a[k].compareTo(b[k]);
|
|
213
|
+
if (s !== 0 && last !== 0 && Math.sign(s) !== last) crossovers.push({ period: k, ahead: s > 0 ? runs[i].name : runs[j].name, behind: s > 0 ? runs[j].name : runs[i].name });
|
|
214
|
+
if (s !== 0) last = Math.sign(s);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return { rows, best, series, crossovers };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Which input moves the outcome most. `build` takes the inputs and returns
|
|
223
|
+
* a scenario (or its description); `inputs` gives their values. Each input
|
|
224
|
+
* in turn is carried through the projection with its derivative, so
|
|
225
|
+
* `derivative` is the exact rate of change of the outcome, not a difference
|
|
226
|
+
* quotient. Rows are sorted by `perPercent`, the change in the outcome for
|
|
227
|
+
* a 1% change in the input; `elasticity` is the same as a share of the
|
|
228
|
+
* outcome. Inside `build` do arithmetic on the inputs with .add, .subtract,
|
|
229
|
+
* .multiply and .divide. The scenario must be unrounded.
|
|
230
|
+
*/
|
|
231
|
+
export function sensitivity(build, inputs, { measure = (p) => p.netWorth } = {}) {
|
|
232
|
+
const names = Object.keys(inputs);
|
|
233
|
+
const values = Object.fromEntries(names.map((n) => [n, amount(inputs[n])]));
|
|
234
|
+
const run = (active) => {
|
|
235
|
+
const duals = Object.fromEntries(names.map((n) => [n, new Dual(values[n], n === active ? ONE : ZERO)]));
|
|
236
|
+
return lift(measure(scenario(build(duals)).project()));
|
|
237
|
+
};
|
|
238
|
+
const base = run(null).v;
|
|
239
|
+
const rows = names.map((n) => {
|
|
240
|
+
const d = run(n).d;
|
|
241
|
+
const perPercent = d.multiply(values[n]).divide(Q(100));
|
|
242
|
+
return { input: n, value: values[n], derivative: d, perPercent, elasticity: base.numerator === 0n ? null : d.multiply(values[n]).divide(base) };
|
|
243
|
+
});
|
|
244
|
+
const abs = (q) => (q.numerator < 0n ? q.negate() : q);
|
|
245
|
+
rows.sort((a, b) => abs(b.perPercent).compareTo(abs(a.perPercent)));
|
|
246
|
+
return { base, rows, most: rows[0]?.input ?? null };
|
|
247
|
+
}
|
package/src/solve.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// Rates found by solving. Every rate equation here is a polynomial in
|
|
2
|
+
// x = 1 + r, so its roots are algebraic numbers: @ratmath/algebraic finds all
|
|
3
|
+
// the real ones, each isolated and proven, and tells a rational root from an
|
|
4
|
+
// irrational one. Long conventional cash flows (one change of sign) have
|
|
5
|
+
// exactly one positive root by Descartes' rule, and it is bracketed by exact
|
|
6
|
+
// bisection instead.
|
|
7
|
+
import { Rational, RationalInterval } from "@ratmath/core";
|
|
8
|
+
import { roots as algebraicRoots, format as algebraicFormat, sub as algebraicSub, fromRational } from "@ratmath/algebraic";
|
|
9
|
+
import { refuse, ZERO, ONE, Q } from "./money.js";
|
|
10
|
+
|
|
11
|
+
const gcd = (a, b) => {
|
|
12
|
+
[a, b] = [a < 0n ? -a : a, b < 0n ? -b : b];
|
|
13
|
+
while (b) [a, b] = [b, a % b];
|
|
14
|
+
return a;
|
|
15
|
+
};
|
|
16
|
+
/** rational coefficients (constant first) as whole numbers with the same roots */
|
|
17
|
+
export function wholeCoefficients(coeffs) {
|
|
18
|
+
const c = coeffs.slice();
|
|
19
|
+
while (c.length && c[c.length - 1].numerator === 0n) c.pop();
|
|
20
|
+
if (!c.length) return [];
|
|
21
|
+
const den = c.reduce((l, q) => (l * q.denominator) / gcd(l, q.denominator), 1n);
|
|
22
|
+
const ints = c.map((q) => (q.numerator * den) / q.denominator);
|
|
23
|
+
const g = ints.reduce(gcd, 0n);
|
|
24
|
+
return ints.map((n) => n / g);
|
|
25
|
+
}
|
|
26
|
+
export const signChanges = (values) => {
|
|
27
|
+
const s = values.map((v) => (typeof v === "bigint" ? (v > 0n ? 1 : v < 0n ? -1 : 0) : Math.sign(Number(v.numerator)))).filter(Boolean);
|
|
28
|
+
let n = 0;
|
|
29
|
+
for (let i = 1; i < s.length; i++) if (s[i] !== s[i - 1]) n++;
|
|
30
|
+
return n;
|
|
31
|
+
};
|
|
32
|
+
const horner = (ints, x) => {
|
|
33
|
+
let y = ZERO;
|
|
34
|
+
for (let i = ints.length - 1; i >= 0; i--) y = y.multiply(x).add(new Rational(ints[i]));
|
|
35
|
+
return y;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** the fraction with the smallest denominator in [lo, hi], for 0 ≤ lo < hi */
|
|
39
|
+
function simplest(lo, hi) {
|
|
40
|
+
const f = lo.numerator / lo.denominator;
|
|
41
|
+
const whole = new Rational(f);
|
|
42
|
+
if (whole.equals(lo)) return lo;
|
|
43
|
+
if (whole.add(ONE).compareTo(hi) <= 0) return whole.add(ONE);
|
|
44
|
+
return whole.add(ONE.divide(simplest(ONE.divide(hi.subtract(whole)), ONE.divide(lo.subtract(whole)))));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Every rate r > −1 with Σ coeffs[k]·(1 + r)^k = 0, in increasing order:
|
|
49
|
+
* [{ rate, exact, text, multiplicity }]. `rate` is a Rational when the root
|
|
50
|
+
* is rational and otherwise an interval proven to contain exactly one root.
|
|
51
|
+
*/
|
|
52
|
+
export function rateRoots(coeffs, { digits = 12, limit = 80 } = {}) {
|
|
53
|
+
let ints = wholeCoefficients(coeffs);
|
|
54
|
+
if (!ints.length) refuse("no-equation", "every amount is zero, so every rate works");
|
|
55
|
+
while (ints.length > 1 && ints[0] === 0n) ints = ints.slice(1); // x = 0 is r = −1, not a rate
|
|
56
|
+
const changes = signChanges(ints);
|
|
57
|
+
if (changes === 0) return [];
|
|
58
|
+
const bits = Math.ceil(digits * 3.33) + 8;
|
|
59
|
+
const degree = ints.length - 1;
|
|
60
|
+
if (degree > limit && changes === 1) {
|
|
61
|
+
// one positive root; the polynomial has the sign of its constant term before it
|
|
62
|
+
const s0 = ints[0] > 0n ? 1 : -1;
|
|
63
|
+
const sign = (x) => Math.sign(Number(horner(ints, x).numerator)) || 0;
|
|
64
|
+
let lo = ZERO;
|
|
65
|
+
let hi = ONE;
|
|
66
|
+
while (sign(hi) === s0) [lo, hi] = [hi, hi.multiply(Q(2))];
|
|
67
|
+
const eps = Q(1n, 1n << BigInt(bits));
|
|
68
|
+
while (hi.subtract(lo).compareTo(eps) > 0) {
|
|
69
|
+
const mid = lo.add(hi).divide(Q(2));
|
|
70
|
+
const s = sign(mid);
|
|
71
|
+
if (s === 0) return [{ rate: mid.subtract(ONE), exact: true, text: mid.subtract(ONE).toString(), multiplicity: 1 }];
|
|
72
|
+
if (s === s0) lo = mid;
|
|
73
|
+
else hi = mid;
|
|
74
|
+
}
|
|
75
|
+
// a rate typed as a decimal is the simplest fraction in the bracket: test it
|
|
76
|
+
const simple = simplest(lo, hi);
|
|
77
|
+
if (sign(simple) === 0) return [{ rate: simple.subtract(ONE), exact: true, text: simple.subtract(ONE).toString(), multiplicity: 1 }];
|
|
78
|
+
const iv = new RationalInterval(lo.subtract(ONE), hi.subtract(ONE));
|
|
79
|
+
return [{ rate: iv, exact: false, text: `${iv.low.toDecimal(digits)}…`, multiplicity: 1 }];
|
|
80
|
+
}
|
|
81
|
+
if (degree > 400) refuse("too-long", "a cash flow with several changes of sign and more than 400 periods is too long to solve for every rate");
|
|
82
|
+
const out = [];
|
|
83
|
+
for (const { value, multiplicity } of algebraicRoots(ints)) {
|
|
84
|
+
if (value.rational ? value.rational[0] <= 0n : value.interval(8)[1].numerator <= 0n) continue;
|
|
85
|
+
const r = algebraicSub(value, fromRational([1n, 1n]));
|
|
86
|
+
const q = r.rational;
|
|
87
|
+
if (q) out.push({ rate: new Rational(q[0], q[1]), exact: true, text: new Rational(q[0], q[1]).toString(), multiplicity });
|
|
88
|
+
else {
|
|
89
|
+
const [lo, hi] = r.interval(bits);
|
|
90
|
+
out.push({ rate: new RationalInterval(lo, hi), exact: false, text: algebraicFormat(r, { digits }).replace(/−/g, "-"), multiplicity });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The zero of a function that is known to be strictly monotone, by exact
|
|
98
|
+
* bisection: f takes a Rational and returns a Rational or an interval; the
|
|
99
|
+
* answer is an interval of width below 10^−digits (or the exact point).
|
|
100
|
+
*/
|
|
101
|
+
export function monotoneZero(f, lo, hi, { digits = 12 } = {}) {
|
|
102
|
+
const sign = (x) => {
|
|
103
|
+
const y = f(x);
|
|
104
|
+
if (y instanceof RationalInterval) return y.low.numerator > 0n ? 1 : y.high.numerator < 0n ? -1 : null;
|
|
105
|
+
return y.numerator > 0n ? 1 : y.numerator < 0n ? -1 : 0;
|
|
106
|
+
};
|
|
107
|
+
const [sl, sh] = [sign(lo), sign(hi)];
|
|
108
|
+
if (sl === 0) return lo;
|
|
109
|
+
if (sh === 0) return hi;
|
|
110
|
+
if (sl === null || sh === null || sl === sh) refuse("no-bracket", "the two ends do not bracket a solution");
|
|
111
|
+
const eps = Q(1n, 10n ** BigInt(digits));
|
|
112
|
+
// midpoints on a binary grid so the numbers stay short
|
|
113
|
+
const grid = 1n << BigInt(Math.ceil(digits * 3.33) + 8);
|
|
114
|
+
while (hi.subtract(lo).compareTo(eps) > 0) {
|
|
115
|
+
const m = lo.add(hi).divide(Q(2));
|
|
116
|
+
const mid = new Rational((m.numerator * grid) / m.denominator, grid);
|
|
117
|
+
const at = mid.compareTo(lo) > 0 && mid.compareTo(hi) < 0 ? mid : m;
|
|
118
|
+
const s = sign(at);
|
|
119
|
+
if (s === 0) return at;
|
|
120
|
+
if (s === null) break; // the function's own enclosure is as wide as the bracket
|
|
121
|
+
if (s === sl) lo = at;
|
|
122
|
+
else hi = at;
|
|
123
|
+
}
|
|
124
|
+
return new RationalInterval(lo, hi);
|
|
125
|
+
}
|
package/src/tvm.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// The time value of money: interest, equivalent rates, present and future
|
|
2
|
+
// values, annuities, and solving for whichever quantity is missing.
|
|
3
|
+
import { Rational, RationalInterval } from "@ratmath/core";
|
|
4
|
+
import { refuse, amount, ZERO, ONE, Q, power, exp, ln, ends } from "./money.js";
|
|
5
|
+
import { rateRoots } from "./solve.js";
|
|
6
|
+
|
|
7
|
+
const whole = (n, what) => {
|
|
8
|
+
const q = amount(n);
|
|
9
|
+
if (q.denominator !== 1n || q.numerator < 0n) refuse("bad-periods", `${what} is a whole number that is not negative`);
|
|
10
|
+
return Number(q.numerator);
|
|
11
|
+
};
|
|
12
|
+
const sub1 = (x) => (x instanceof RationalInterval ? new RationalInterval(x.low.subtract(ONE), x.high.subtract(ONE)) : x.subtract(ONE));
|
|
13
|
+
const scale = (x, k) => {
|
|
14
|
+
if (!(x instanceof RationalInterval)) return x.multiply(k);
|
|
15
|
+
const [a, b] = [x.low.multiply(k), x.high.multiply(k)];
|
|
16
|
+
return a.compareTo(b) <= 0 ? new RationalInterval(a, b) : new RationalInterval(b, a);
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/** Simple interest: principal·rate·time. { interest, total }. */
|
|
20
|
+
export function simpleInterest(principal, rate, time) {
|
|
21
|
+
const interest = amount(principal).multiply(amount(rate)).multiply(amount(time));
|
|
22
|
+
return { interest, total: amount(principal).add(interest) };
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* What a principal grows to in `years` at a nominal annual rate compounded
|
|
26
|
+
* periodsPerYear times a year, or "continuous". Exact when the number of
|
|
27
|
+
* periods is whole; otherwise an interval that contains the value.
|
|
28
|
+
*/
|
|
29
|
+
export function compound(principal, rate, years, { periodsPerYear = 1, digits = 12 } = {}) {
|
|
30
|
+
const [p, j, t] = [amount(principal), amount(rate), amount(years)];
|
|
31
|
+
if (periodsPerYear === "continuous") return j.multiply(t).numerator === 0n ? p : scale(exp(j.multiply(t), digits), p);
|
|
32
|
+
const m = amount(periodsPerYear);
|
|
33
|
+
return scale(power(ONE.add(j.divide(m)), m.multiply(t), digits), p);
|
|
34
|
+
}
|
|
35
|
+
/** The effective annual rate of a nominal rate compounded m times a year (or "continuous"). */
|
|
36
|
+
export function effectiveRate(nominal, periodsPerYear = 12, { digits = 12 } = {}) {
|
|
37
|
+
const j = amount(nominal);
|
|
38
|
+
if (periodsPerYear === "continuous") return j.numerator === 0n ? ZERO : sub1(exp(j, digits));
|
|
39
|
+
const m = amount(periodsPerYear);
|
|
40
|
+
return sub1(power(ONE.add(j.divide(m)), m, digits));
|
|
41
|
+
}
|
|
42
|
+
/** The nominal annual rate, compounded m times a year (or "continuous"), that has a given effective annual rate. */
|
|
43
|
+
export function nominalRate(effective, periodsPerYear = 12, { digits = 12 } = {}) {
|
|
44
|
+
const i = amount(effective);
|
|
45
|
+
if (periodsPerYear === "continuous") return i.numerator === 0n ? ZERO : ln(ONE.add(i), digits);
|
|
46
|
+
const m = amount(periodsPerYear);
|
|
47
|
+
return scale(sub1(power(ONE.add(i), ONE.divide(m), digits)), m);
|
|
48
|
+
}
|
|
49
|
+
/** A nominal rate compounded `from` times a year restated as one compounded `to` times a year. */
|
|
50
|
+
export function equivalentRate(nominal, from, to, { digits = 12 } = {}) {
|
|
51
|
+
const [j, m, k] = [amount(nominal), amount(from), amount(to)];
|
|
52
|
+
return scale(sub1(power(ONE.add(j.divide(m)), m.divide(k), digits)), k);
|
|
53
|
+
}
|
|
54
|
+
/** The real rate behind a nominal rate and an inflation rate (Fisher, exactly): (1 + n)/(1 + π) − 1. */
|
|
55
|
+
export const realRate = (nominal, inflation) => ONE.add(amount(nominal)).divide(ONE.add(amount(inflation))).subtract(ONE);
|
|
56
|
+
|
|
57
|
+
/** (1 + rate)^−periods */
|
|
58
|
+
export const discountFactor = (rate, periods, opts = {}) => power(ONE.add(amount(rate)), amount(periods).negate(), opts.digits);
|
|
59
|
+
export const futureValue = (pv, rate, periods, opts = {}) => scale(power(ONE.add(amount(rate)), amount(periods), opts.digits), amount(pv));
|
|
60
|
+
export const presentValue = (fv, rate, periods, opts = {}) => scale(discountFactor(rate, periods, opts), amount(fv));
|
|
61
|
+
|
|
62
|
+
// Σ_{k=0}^{n−1} x^k, exactly
|
|
63
|
+
const geometric = (x, n) => (x.equals(ONE) ? Q(n) : x.pow(n).subtract(ONE).divide(x.subtract(ONE)));
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* A level or growing annuity: `periods` payments, the first of `payment`,
|
|
67
|
+
* each later one (1 + growth) times the one before; at the end of each
|
|
68
|
+
* period (ordinary) or the start (due); starting after `deferred` periods.
|
|
69
|
+
* { presentValue, futureValue, total, payments }, all exact.
|
|
70
|
+
*/
|
|
71
|
+
export function annuity({ payment = 1, rate, periods, due = false, growth = 0, deferred = 0 } = {}) {
|
|
72
|
+
const [p, i, g] = [amount(payment), amount(rate), amount(growth)];
|
|
73
|
+
const n = whole(periods, "the number of payments");
|
|
74
|
+
const d = whole(deferred, "the deferral");
|
|
75
|
+
if (i.compareTo(Q(-1)) <= 0) refuse("bad-rate", "the rate must be more than −100%");
|
|
76
|
+
const v = ONE.divide(ONE.add(i));
|
|
77
|
+
// payments at times 1..n: p·Σ (1+g)^(k−1) v^k = p·v·Σ ((1+g)v)^(k−1)
|
|
78
|
+
let pv = n === 0 ? ZERO : p.multiply(v).multiply(geometric(ONE.add(g).multiply(v), n));
|
|
79
|
+
if (due) pv = pv.multiply(ONE.add(i));
|
|
80
|
+
pv = pv.multiply(v.pow(d));
|
|
81
|
+
const fv = pv.multiply(ONE.add(i).pow(n + d));
|
|
82
|
+
return { presentValue: pv, futureValue: fv, total: n === 0 ? ZERO : p.multiply(geometric(ONE.add(g), n)), payments: n };
|
|
83
|
+
}
|
|
84
|
+
/** A perpetuity: payments for ever, level or growing at a rate below the interest rate. Its present value. */
|
|
85
|
+
export function perpetuity({ payment = 1, rate, growth = 0, due = false, deferred = 0 } = {}) {
|
|
86
|
+
const [p, i, g] = [amount(payment), amount(rate), amount(growth)];
|
|
87
|
+
if (i.compareTo(g) <= 0) refuse("diverges", "a perpetuity has a present value only when the rate is above the growth rate");
|
|
88
|
+
let pv = p.divide(i.subtract(g));
|
|
89
|
+
if (due) pv = pv.multiply(ONE.add(i));
|
|
90
|
+
return pv.divide(ONE.add(i).pow(whole(deferred, "the deferral")));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The equation that ties together a present value, a level payment, a
|
|
95
|
+
* future value, a rate per period and a number of periods,
|
|
96
|
+
* pv + pmt·a + fv·(1 + rate)^−n = 0, a = (1 − (1 + rate)^−n)/rate (×(1 + rate) when due),
|
|
97
|
+
* with money received positive and money paid negative. Leave out exactly
|
|
98
|
+
* one of pv, fv, pmt, rate, n and it is solved for:
|
|
99
|
+
* pv, fv and pmt exactly; n as an exact number or an interval; rate as the
|
|
100
|
+
* list of every rate that works (`rates`), each proven.
|
|
101
|
+
*/
|
|
102
|
+
export function tvm({ pv, fv, pmt, rate, n, due = false, digits = 12 } = {}) {
|
|
103
|
+
const given = { pv, fv, pmt, rate, n };
|
|
104
|
+
const missing = Object.keys(given).filter((k) => given[k] === undefined);
|
|
105
|
+
if (missing.length !== 1) refuse("bad-problem", "leave out exactly one of pv, fv, pmt, rate, n");
|
|
106
|
+
const what = missing[0];
|
|
107
|
+
const val = (k) => amount(given[k]);
|
|
108
|
+
if (what === "rate") {
|
|
109
|
+
const N = whole(n, "n");
|
|
110
|
+
if (N === 0) refuse("bad-problem", "with no periods there is no rate to find");
|
|
111
|
+
// times x^n with x = 1 + rate: pv·x^n + pmt·(x^(n−1) + … + 1)·(x if due) + fv = 0
|
|
112
|
+
const c = Array.from({ length: N + 1 }, () => ZERO);
|
|
113
|
+
c[N] = c[N].add(val("pv"));
|
|
114
|
+
c[0] = c[0].add(val("fv"));
|
|
115
|
+
for (let k = 0; k < N; k++) c[k + (due ? 1 : 0)] = c[k + (due ? 1 : 0)].add(val("pmt"));
|
|
116
|
+
const rates = rateRoots(c, { digits });
|
|
117
|
+
return { solved: "rate", rates, rate: rates.length === 1 ? rates[0].rate : null, count: rates.length };
|
|
118
|
+
}
|
|
119
|
+
const i = val("rate");
|
|
120
|
+
if (i.compareTo(Q(-1)) <= 0) refuse("bad-rate", "the rate must be more than −100%");
|
|
121
|
+
const x = ONE.add(i);
|
|
122
|
+
const dueFactor = due ? x : ONE;
|
|
123
|
+
if (what === "n") {
|
|
124
|
+
const [P, F, M] = [val("pv"), val("fv"), val("pmt")];
|
|
125
|
+
let exact = null;
|
|
126
|
+
let ratio = null;
|
|
127
|
+
if (i.numerator === 0n) {
|
|
128
|
+
if (M.numerator === 0n) refuse("no-solution", "with no interest and no payment the balance never changes");
|
|
129
|
+
exact = P.add(F).negate().divide(M);
|
|
130
|
+
} else {
|
|
131
|
+
// x^−n = (pv + c)/(c − fv), c = pmt·dueFactor/rate
|
|
132
|
+
const c = M.multiply(dueFactor).divide(i);
|
|
133
|
+
if (c.subtract(F).numerator === 0n) refuse("no-solution", "no number of periods balances these amounts");
|
|
134
|
+
ratio = c.subtract(F).divide(P.add(c)); // = x^n
|
|
135
|
+
if (P.add(c).numerator === 0n || ratio.numerator <= 0n) refuse("no-solution", "no number of periods balances these amounts: the payment does not cover the interest, or the signs are the same");
|
|
136
|
+
const guess = Math.round(Math.log(ratio.toNumber()) / Math.log(x.toNumber()));
|
|
137
|
+
if (Number.isFinite(guess) && Math.abs(guess) < 100000 && (guess >= 0 ? x.pow(guess) : ONE.divide(x.pow(-guess))).equals(ratio)) exact = Q(guess);
|
|
138
|
+
}
|
|
139
|
+
if (exact !== null) {
|
|
140
|
+
if (exact.numerator < 0n) refuse("no-solution", "the amounts balance only at a negative number of periods");
|
|
141
|
+
return { solved: "n", n: exact, exact: true, whole: Number((exact.numerator + exact.denominator - 1n) / exact.denominator) };
|
|
142
|
+
}
|
|
143
|
+
const [a, b] = [ln(ratio, digits + 4), ln(x, digits + 4)];
|
|
144
|
+
const q = [a.low.divide(b.low), a.low.divide(b.high), a.high.divide(b.low), a.high.divide(b.high)].sort((u, w) => u.compareTo(w));
|
|
145
|
+
if (q[3].numerator < 0n) refuse("no-solution", "the amounts balance only at a negative number of periods");
|
|
146
|
+
const hi = q[3];
|
|
147
|
+
return { solved: "n", n: new RationalInterval(q[0], hi), exact: false, whole: Number((hi.numerator + hi.denominator - 1n) / hi.denominator) };
|
|
148
|
+
}
|
|
149
|
+
const N = whole(n, "n");
|
|
150
|
+
const vN = ONE.divide(x.pow(N));
|
|
151
|
+
const a = (i.numerator === 0n ? Q(N) : ONE.subtract(vN).divide(i)).multiply(dueFactor);
|
|
152
|
+
if (what === "pv") return { solved: "pv", pv: val("pmt").multiply(a).add(val("fv").multiply(vN)).negate(), exact: true };
|
|
153
|
+
if (what === "fv") return { solved: "fv", fv: val("pv").add(val("pmt").multiply(a)).divide(vN).negate(), exact: true };
|
|
154
|
+
if (a.numerator === 0n) refuse("no-solution", "with no periods a payment cannot balance the amounts");
|
|
155
|
+
return { solved: "pmt", pmt: val("pv").add(val("fv").multiply(vN)).divide(a).negate(), exact: true };
|
|
156
|
+
}
|
|
157
|
+
export { ends };
|