@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/package.json CHANGED
@@ -1,6 +1,81 @@
1
1
  {
2
2
  "name": "@ratmath/finance",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "The mathematics of finance for RatMath: exact money, time value, loans, bonds, scenarios, uncertain inputs and repeated runs, portfolios, options and life contingencies",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./index.d.ts",
10
+ "default": "./index.js"
11
+ },
12
+ "./package.json": "./package.json"
13
+ },
14
+ "files": [
15
+ "index.js",
16
+ "index.d.ts",
17
+ "src/",
18
+ "README.md",
19
+ "CHANGELOG.md",
20
+ "LICENSE",
21
+ "docs/llms.txt"
22
+ ],
23
+ "sideEffects": false,
24
+ "scripts": {
25
+ "test": "bun test ./tests",
26
+ "docs:build": "bun scripts/build-docs.js && node scripts/build-llms.mjs",
27
+ "docs:llms": "node scripts/build-llms.mjs"
28
+ },
29
+ "keywords": [
30
+ "finance",
31
+ "time-value-of-money",
32
+ "loan",
33
+ "amortization",
34
+ "bond",
35
+ "simulation",
36
+ "exact",
37
+ "ratmath",
38
+ "monte-carlo",
39
+ "portfolio",
40
+ "option-pricing",
41
+ "actuarial"
42
+ ],
43
+ "license": "MIT",
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "git+https://github.com/ratmath/finance.git"
47
+ },
48
+ "homepage": "https://ratmath.com/finance/",
49
+ "bugs": {
50
+ "url": "https://github.com/ratmath/finance/issues"
51
+ },
52
+ "dependencies": {
53
+ "@ratmath/algebraic": "^0.1.0",
54
+ "@ratmath/analytic": "^0.1.0",
55
+ "@ratmath/discrete": "^0.3.0",
56
+ "@ratmath/stats": "^0.3.0"
57
+ },
58
+ "peerDependencies": {
59
+ "@ratmath/core": ">=0.12.0"
60
+ },
61
+ "devDependencies": {
62
+ "@ratmath/core": "^0.12.1",
63
+ "katex": "0.19.1"
64
+ },
65
+ "types": "index.d.ts",
66
+ "author": "James Taylor",
67
+ "engines": {
68
+ "node": ">=22",
69
+ "bun": ">=1.4.2"
70
+ },
71
+ "publishConfig": {
72
+ "access": "public"
73
+ },
74
+ "workspaces": [
75
+ "vendor/analytic",
76
+ "vendor/algebraic",
77
+ "vendor/stats",
78
+ "vendor/discrete",
79
+ "vendor/logic"
80
+ ]
81
+ }
package/src/bonds.js ADDED
@@ -0,0 +1,237 @@
1
+ // Bonds and interest rates: price, yield, accrued interest, duration and
2
+ // convexity; discount factors, spot and forward rates from bond prices;
3
+ // immunisation. Yields are nominal annual rates compounded as often as the
4
+ // bond pays, the usual quoting convention.
5
+ import { Rational, RationalInterval } from "@ratmath/core";
6
+ import { refuse, amount, ZERO, ONE, Q, power, date, dayCount } from "./money.js";
7
+ import { rateRoots, monotoneZero } from "./solve.js";
8
+ import { total } from "./cashflow.js";
9
+
10
+ const times = (x, k) => {
11
+ if (!(x instanceof RationalInterval)) return x.multiply(k);
12
+ const [a, b] = [x.low.multiply(k), x.high.multiply(k)];
13
+ return a.compareTo(b) <= 0 ? new RationalInterval(a, b) : new RationalInterval(b, a);
14
+ };
15
+ const minus = (x, k) => (x instanceof RationalInterval ? new RationalInterval(x.low.subtract(k), x.high.subtract(k)) : x.subtract(k));
16
+ const sum = (xs) => xs.reduce((a, b) => a.add(b), ZERO);
17
+
18
+ export class Bond {
19
+ /**
20
+ * { face = 100, coupon (annual rate), frequency = 2, redemption = face }
21
+ * and either `periods` (whole coupon periods left, valued on a coupon
22
+ * date) or `settlement` and `maturity` dates with a day-count convention
23
+ * (default "30/360"), which gives accrued interest.
24
+ */
25
+ constructor({ face = 100, coupon = 0, frequency = 2, redemption, periods, settlement, maturity, dayCount: convention = "30/360" } = {}) {
26
+ this.face = amount(face);
27
+ this.coupon = amount(coupon);
28
+ this.frequency = Number(frequency);
29
+ if (![1, 2, 3, 4, 6, 12].includes(this.frequency)) refuse("bad-bond", "the coupon frequency is 1, 2, 3, 4, 6 or 12 a year");
30
+ this.redemption = amount(redemption ?? face);
31
+ this.couponAmount = this.face.multiply(this.coupon).divide(Q(this.frequency));
32
+ this.dayCount = convention;
33
+ if (maturity !== undefined) {
34
+ if (settlement === undefined) refuse("bad-bond", "give the settlement date with the maturity date");
35
+ const [s, m] = [date(settlement), date(maturity)];
36
+ if (m.compareTo(s) <= 0) refuse("bad-bond", "the bond has already matured at settlement");
37
+ const step = 12 / this.frequency;
38
+ // coupon dates counted back from maturity
39
+ let n = 0;
40
+ while (m.addMonths(-step * (n + 1), { endOfMonth: true }).compareTo(s) > 0) n++;
41
+ const next = m.addMonths(-step * n, { endOfMonth: true });
42
+ const previous = m.addMonths(-step * (n + 1), { endOfMonth: true });
43
+ const whole = dayCount(previous, next, convention).days;
44
+ const gone = dayCount(previous, s, convention).days;
45
+ this.periods = n + 1;
46
+ this.settlement = s;
47
+ this.maturity = m;
48
+ this.accruedDays = gone;
49
+ this.accrued = this.couponAmount.multiply(Q(gone, whole));
50
+ this.first = Q(whole - gone, whole); // periods until the next coupon
51
+ this.dates = Array.from({ length: n + 1 }, (_, k) => m.addMonths(-step * (n - k), { endOfMonth: true }));
52
+ } else {
53
+ if (!Number.isInteger(periods) || periods < 1) refuse("bad-bond", "give the whole number of coupon periods left, or settlement and maturity dates");
54
+ this.periods = periods;
55
+ this.accrued = ZERO;
56
+ this.accruedDays = 0;
57
+ this.first = ONE;
58
+ }
59
+ }
60
+ /** [{ t (coupon periods from settlement), years, amount, date? }] */
61
+ get cashflows() {
62
+ return Array.from({ length: this.periods }, (_, k) => {
63
+ const t = this.first.add(Q(k));
64
+ const flow = { t, years: t.divide(Q(this.frequency)), amount: k === this.periods - 1 ? this.couponAmount.add(this.redemption) : this.couponAmount };
65
+ if (this.dates) flow.date = this.dates[k];
66
+ return flow;
67
+ });
68
+ }
69
+ // Σ cf_k x^−k for k = 0 … n−1: the value one coupon date ahead of the first coupon, exactly
70
+ _core(x) {
71
+ let v = ZERO;
72
+ for (let k = this.periods - 1; k >= 0; k--) v = v.divide(x).add(k === this.periods - 1 ? this.couponAmount.add(this.redemption) : this.couponAmount);
73
+ return v;
74
+ }
75
+ _x(y) {
76
+ const x = ONE.add(amount(y).divide(Q(this.frequency)));
77
+ return x.numerator > 0n ? x : refuse("bad-yield", "the yield per period must be more than −100%");
78
+ }
79
+ /** { dirty, clean, accrued } at a yield: exact on a coupon date, otherwise the dirty and clean prices are intervals that contain them */
80
+ price(y, { digits = 12 } = {}) {
81
+ const x = this._x(y);
82
+ const dirty = times(power(x, this.first.negate(), digits + 4), this._core(x));
83
+ return { dirty, clean: minus(dirty, this.accrued), accrued: this.accrued };
84
+ }
85
+ /**
86
+ * The yield to maturity at a clean price. The price falls as the yield
87
+ * rises, so there is exactly one. A Rational when it is rational (on a
88
+ * coupon date), otherwise an interval proven to contain it.
89
+ */
90
+ yield(cleanPrice, { digits = 12 } = {}) {
91
+ const dirty = amount(cleanPrice).add(this.accrued);
92
+ if (dirty.numerator <= 0n) refuse("bad-price", "the price is positive");
93
+ const f = Q(this.frequency);
94
+ if (this.first.equals(ONE)) {
95
+ const n = this.periods;
96
+ const c = Array.from({ length: n + 1 }, (_, k) => (k === n ? dirty.negate() : k === 0 ? this.couponAmount.add(this.redemption) : this.couponAmount));
97
+ const found = rateRoots(c, { digits: digits + 2 });
98
+ if (found.length !== 1) refuse("no-yield", "no yield above −100% per period gives this price");
99
+ return times(found[0].rate, f);
100
+ }
101
+ const g = (y) => minus(this.price(y, { digits: digits + 6 }).dirty, dirty);
102
+ const sgn = (v) => (v instanceof RationalInterval ? (v.low.numerator > 0n ? 1 : v.high.numerator < 0n ? -1 : 0) : Math.sign(Number(v.numerator)));
103
+ let lo = f.multiply(Q(-1, 2));
104
+ let hi = ONE;
105
+ if (sgn(g(lo)) <= 0) refuse("no-yield", "the price is too high for any yield above −50% per period");
106
+ for (let k = 0; sgn(g(hi)) >= 0; k++) {
107
+ if (k > 40) refuse("no-yield", "the price is too low for any reasonable yield");
108
+ hi = hi.multiply(Q(2));
109
+ }
110
+ return monotoneZero(g, lo, hi, { digits });
111
+ }
112
+ /** At a yield: Macaulay duration (years), modified duration, convexity (years²), all exact, and the price change they predict per 1% of yield. */
113
+ duration(y) {
114
+ const x = this._x(y);
115
+ const f = Q(this.frequency);
116
+ let [p, d, c] = [ZERO, ZERO, ZERO];
117
+ this.cashflows.forEach((cf, k) => {
118
+ const pv = cf.amount.divide(x.pow(k)); // the common factor x^−first cancels in each ratio
119
+ p = p.add(pv);
120
+ d = d.add(pv.multiply(cf.years));
121
+ c = c.add(pv.multiply(cf.years).multiply(cf.years.add(ONE.divide(f))));
122
+ });
123
+ const macaulay = d.divide(p);
124
+ const modified = macaulay.divide(x);
125
+ return { macaulay, modified, convexity: c.divide(p).divide(x.multiply(x)), percentPerPoint: modified.negate() };
126
+ }
127
+ }
128
+ export const bond = (spec) => (spec instanceof Bond ? spec : new Bond(spec));
129
+
130
+ /**
131
+ * A curve of discount factors d_1, d_2, … for whole periods (`frequency`
132
+ * periods a year), with the spot and forward rates they imply.
133
+ */
134
+ export class YieldCurve {
135
+ constructor(discountFactors, frequency = 1) {
136
+ this.discountFactors = discountFactors.map(amount);
137
+ this.frequency = Number(frequency);
138
+ if (this.discountFactors.some((d) => d.numerator <= 0n)) refuse("bad-curve", "discount factors are positive");
139
+ }
140
+ get periods() {
141
+ return this.discountFactors.length;
142
+ }
143
+ discount(k) {
144
+ if (k === 0) return ONE;
145
+ return Number.isInteger(k) && k >= 1 && k <= this.periods ? this.discountFactors[k - 1] : refuse("off-curve", `the curve covers periods 1 to ${this.periods}`);
146
+ }
147
+ /** the spot rate for k periods, as a nominal annual rate compounded `frequency` times: d_k = (1 + s/f)^−k */
148
+ spot(k, { digits = 12 } = {}) {
149
+ const root = power(ONE.divide(this.discount(k)), Q(1, k), digits + 2);
150
+ return times(minus(root, ONE), Q(this.frequency));
151
+ }
152
+ /** the forward rate from period a to period b, nominal annual; exact when b = a + 1 */
153
+ forward(a, b = a + 1, { digits = 12 } = {}) {
154
+ if (!(b > a)) refuse("bad-forward", "the forward runs from an earlier period to a later one");
155
+ const root = power(this.discount(a).divide(this.discount(b)), Q(1, b - a), digits + 2);
156
+ return times(minus(root, ONE), Q(this.frequency));
157
+ }
158
+ /** the coupon rate at which a k-period bond is worth its face value, exactly */
159
+ parYield(k) {
160
+ let s = ZERO;
161
+ for (let j = 1; j <= k; j++) s = s.add(this.discount(j));
162
+ return ONE.subtract(this.discount(k)).divide(s).multiply(Q(this.frequency));
163
+ }
164
+ /** the price of a bond (whole periods, same frequency) off the curve, exactly */
165
+ price(spec) {
166
+ const b = spec instanceof Bond ? spec : bond({ frequency: this.frequency, ...spec });
167
+ if (b.frequency !== this.frequency || !b.first.equals(ONE)) refuse("off-curve", "the bond must pay on the curve's dates");
168
+ return sum(b.cashflows.map((cf, k) => cf.amount.multiply(this.discount(k + 1))));
169
+ }
170
+ get spots() {
171
+ return this.discountFactors.map((_, k) => this.spot(k + 1));
172
+ }
173
+ get forwards() {
174
+ return this.discountFactors.map((_, k) => this.forward(k, k + 1));
175
+ }
176
+ }
177
+ /**
178
+ * A curve from spot rates (nominal annual, compounded `frequency` times a
179
+ * year) for 1, 2, 3, … periods, or from discount factors.
180
+ */
181
+ export function yieldCurve({ spots, discountFactors, frequency = 1 } = {}) {
182
+ if (discountFactors) return new YieldCurve(discountFactors, frequency);
183
+ if (!Array.isArray(spots)) refuse("bad-curve", "give spots or discountFactors");
184
+ return new YieldCurve(spots.map((s, k) => ONE.divide(ONE.add(amount(s).divide(Q(frequency))).pow(k + 1))), frequency);
185
+ }
186
+ /**
187
+ * Bootstrapping: discount factors from the prices of bonds maturing in
188
+ * 1, 2, 3, … periods, one for each, each bond's earlier coupons valued
189
+ * with the factors already found. All exact.
190
+ */
191
+ export function bootstrap(bonds, { frequency } = {}) {
192
+ const list = bonds.map((b) => ({ price: amount(b.price), bond: bond({ frequency: frequency ?? b.frequency ?? 1, ...b }) })).sort((a, b) => a.bond.periods - b.bond.periods);
193
+ const f = list[0]?.bond.frequency ?? refuse("bad-curve", "give at least one bond");
194
+ const d = [];
195
+ list.forEach(({ price, bond: b }, k) => {
196
+ if (b.periods !== k + 1 || b.frequency !== f || !b.first.equals(ONE)) refuse("bad-curve", `bootstrapping needs one bond maturing at each of periods 1, 2, 3, … with the same coupon dates; bond ${k + 1} has ${b.periods} period(s)`);
197
+ const known = sum(d.map((x) => x.multiply(b.couponAmount)));
198
+ d.push(price.subtract(known).divide(b.couponAmount.add(b.redemption)));
199
+ });
200
+ return new YieldCurve(d, f);
201
+ }
202
+
203
+ /**
204
+ * Immunisation: split the money for a single liability between two bonds
205
+ * so that, at the going yield, the assets have the liability's present
206
+ * value and its duration. { presentValue, weights, amounts, units,
207
+ * durations, convexity, immunised, surplusAt(yield) }: surplusAt shows
208
+ * what is left over if the yield then moves.
209
+ */
210
+ export function immunise({ liability, yield: y, bonds } = {}) {
211
+ if (!Array.isArray(bonds) || bonds.length !== 2) refuse("bad-problem", "immunise takes two bonds");
212
+ const [a, b] = bonds.map(bond);
213
+ const f = a.frequency;
214
+ if (b.frequency !== f) refuse("bad-problem", "the two bonds pay with the same frequency");
215
+ const L = amount(liability.amount);
216
+ const T = amount(liability.time);
217
+ const n = T.multiply(Q(f));
218
+ if (n.denominator !== 1n) refuse("bad-problem", "the liability falls on a coupon date (time × frequency is whole)");
219
+ const x = ONE.add(amount(y).divide(Q(f)));
220
+ const pv = L.divide(x.pow(n.numerator));
221
+ const [da, db] = [a.duration(y), b.duration(y)];
222
+ if (da.macaulay.equals(db.macaulay)) refuse("bad-problem", "the two bonds have the same duration, so no mix can change it");
223
+ const wa = T.subtract(db.macaulay).divide(da.macaulay.subtract(db.macaulay));
224
+ const weights = [wa, ONE.subtract(wa)];
225
+ const prices = [a.price(y).dirty, b.price(y).dirty];
226
+ if (prices.some((p) => p instanceof RationalInterval)) refuse("bad-problem", "value the bonds on a coupon date (give periods, not dates)");
227
+ const amounts = weights.map((w) => w.multiply(pv));
228
+ const units = amounts.map((v, k) => v.divide(prices[k]));
229
+ const assets = weights[0].multiply(da.convexity).add(weights[1].multiply(db.convexity));
230
+ const owed = T.multiply(T.add(ONE.divide(Q(f)))).divide(x.multiply(x));
231
+ const surplusAt = (other) => {
232
+ const z = ONE.add(amount(other).divide(Q(f)));
233
+ return units[0].multiply(a.price(other).dirty).add(units[1].multiply(b.price(other).dirty)).subtract(L.divide(z.pow(n.numerator)));
234
+ };
235
+ return { presentValue: pv, weights, amounts, units, durations: [da.macaulay, db.macaulay], convexity: { assets, liability: owed }, immunised: weights.every((w) => w.numerator >= 0n) && assets.compareTo(owed) >= 0, short: weights.some((w) => w.numerator < 0n), surplusAt };
236
+ }
237
+ export { total };
@@ -0,0 +1,218 @@
1
+ // Cash flows: net present value, every internal rate of return, the
2
+ // modified rate, payback; inflation; depreciation; and taxes as brackets
3
+ // that the caller supplies.
4
+ import { Rational, RationalInterval } from "@ratmath/core";
5
+ import { zeros } from "@ratmath/analytic";
6
+ import { refuse, amount, ZERO, ONE, Q, rounder, power, date, dayCount } from "./money.js";
7
+ import { rateRoots, signChanges } from "./solve.js";
8
+
9
+ /** the sum of exact numbers and intervals: exact when every term is */
10
+ export function total(xs) {
11
+ let [lo, hi, exact] = [ZERO, ZERO, true];
12
+ for (const x of xs) {
13
+ if (x instanceof RationalInterval) {
14
+ [lo, hi, exact] = [lo.add(x.low), hi.add(x.high), false];
15
+ } else [lo, hi] = [lo.add(x), hi.add(x)];
16
+ }
17
+ return exact ? lo : new RationalInterval(lo, hi);
18
+ }
19
+ const times = (x, k) => {
20
+ if (!(x instanceof RationalInterval)) return x.multiply(k);
21
+ const [a, b] = [x.low.multiply(k), x.high.multiply(k)];
22
+ return a.compareTo(b) <= 0 ? new RationalInterval(a, b) : new RationalInterval(b, a);
23
+ };
24
+ /** flows as [{ t, amount }]: an array of amounts is taken at times 0, 1, 2, … */
25
+ const timed = (flows) => {
26
+ if (!Array.isArray(flows) || !flows.length) refuse("bad-flows", "give the cash flows as a list");
27
+ return flows.map((f, k) => (f !== null && typeof f === "object" && !(f instanceof Rational) && "amount" in f ? { t: amount(f.t ?? f.time ?? k), amount: amount(f.amount) } : { t: Q(k), amount: amount(f) }));
28
+ };
29
+ /** dated flows as times in years from the first date */
30
+ const dated = (flows, convention) => {
31
+ if (!Array.isArray(flows) || !flows.length) refuse("bad-flows", "give the cash flows as a list of { date, amount }");
32
+ const rows = flows.map((f) => ({ date: date(f.date), amount: amount(f.amount) })).sort((a, b) => a.date.compareTo(b.date));
33
+ return rows.map((f) => ({ ...f, t: dayCount(rows[0].date, f.date, convention).yearFraction }));
34
+ };
35
+
36
+ /**
37
+ * Net present value at a rate per period. `flows` is a list of amounts at
38
+ * times 0, 1, 2, … (money in positive, money out negative), or of
39
+ * { t, amount } at any exact times. Exact when the times are whole.
40
+ */
41
+ export function npv(rate, flows, { digits = 12 } = {}) {
42
+ const x = ONE.add(amount(rate));
43
+ if (x.numerator <= 0n) refuse("bad-rate", "the rate must be more than −100%");
44
+ return total(timed(flows).map((f) => times(power(x, f.t.negate(), digits + 4), f.amount)));
45
+ }
46
+ /** Net present value of dated flows at an annual rate, time measured from the first date by a day-count convention. */
47
+ export function xnpv(rate, flows, { dayCount: convention = "actual/365", digits = 12 } = {}) {
48
+ return npv(rate, dated(flows, convention), { digits });
49
+ }
50
+
51
+ /**
52
+ * Every internal rate of return of a list of amounts at times 0, 1, 2, …:
53
+ * each rate above −100% at which the net present value is zero.
54
+ * { rates: [{ rate, exact, text }], count, signChanges, rate (when there is
55
+ * exactly one, else null), note }. The count is proven, so "more than one"
56
+ * and "none" are answers too.
57
+ */
58
+ export function irr(flows, { digits = 12 } = {}) {
59
+ const f = timed(flows);
60
+ if (f.some((c) => c.t.denominator !== 1n || c.t.numerator < 0n)) refuse("bad-flows", "irr takes flows at whole periods; use xirr for dated flows");
61
+ const n = Number(f.reduce((m, c) => (c.t.compareTo(m) > 0 ? c.t : m), ZERO).numerator);
62
+ // Σ a_t (1 + r)^(−t) = 0, times (1 + r)^n
63
+ const coeffs = Array.from({ length: n + 1 }, () => ZERO);
64
+ for (const c of f) coeffs[n - Number(c.t.numerator)] = coeffs[n - Number(c.t.numerator)].add(c.amount);
65
+ const inOrder = coeffs.slice().reverse();
66
+ const changes = signChanges(inOrder);
67
+ const rates = rateRoots(coeffs, { digits });
68
+ const note = rates.length === 0 ? (changes === 0 ? "the flows never change sign, so no rate makes them balance" : "no rate above −100% makes these flows balance") : rates.length === 1 ? "one rate" : `${rates.length} rates make these flows balance; none of them is "the" return`;
69
+ return { rates, count: rates.length, signChanges: changes, rate: rates.length === 1 ? rates[0].rate : null, note };
70
+ }
71
+
72
+ const frac = (q) => (q.denominator === 1n ? `(${q.numerator})` : `(${q.numerator}/${q.denominator})`);
73
+ /**
74
+ * Every internal rate of return of dated flows, as an annual rate with time
75
+ * from the first date by a day-count convention. Searched on `range`
76
+ * (default −99% to 1000%); each rate is an interval proven to contain one.
77
+ */
78
+ export function xirr(flows, { dayCount: convention = "actual/365", range = ["-0.99", 10], digits = 10 } = {}) {
79
+ const f = dated(flows, convention).filter((c) => c.amount.numerator !== 0n);
80
+ const changes = signChanges(f.map((c) => c.amount));
81
+ if (changes === 0) return { rates: [], count: 0, signChanges: 0, rate: null, note: "the flows never change sign, so no rate makes them balance" };
82
+ const formula = f.map((c) => (c.t.numerator === 0n ? frac(c.amount) : `${frac(c.amount)}*(1+r)^(-${frac(c.t)})`)).join(" + ");
83
+ const found = zeros(formula, [amount(range[0]), amount(range[1])], { variable: "r", tolerance: 10 ** -Math.min(digits, 30) }).exact();
84
+ const rates = found.map((z) => {
85
+ if (z.kind === "everywhere") refuse("no-equation", "every rate works");
86
+ const exact = z.lo.equals(z.hi);
87
+ const value = exact ? z.lo : new RationalInterval(z.lo, z.hi);
88
+ return { rate: value, exact, text: exact ? z.lo.toString() : `${z.lo.toDecimal(digits)}…`, proven: z.unique !== false && z.kind !== "possible" };
89
+ });
90
+ return { rates, count: rates.length, signChanges: changes, rate: rates.length === 1 ? rates[0].rate : null, formula, note: changes === 1 ? "one change of sign, so at most one rate" : `${changes} changes of sign, so at most ${changes} rates` };
91
+ }
92
+
93
+ /**
94
+ * The modified internal rate of return: money out is financed at one rate
95
+ * and money in is reinvested at another, which gives a single answer:
96
+ * (FV of inflows / −PV of outflows)^(1/n) − 1.
97
+ */
98
+ export function mirr(flows, financeRate, reinvestRate, { digits = 12 } = {}) {
99
+ const a = flows.map(amount);
100
+ const n = a.length - 1;
101
+ const [fin, re] = [ONE.add(amount(financeRate)), ONE.add(amount(reinvestRate))];
102
+ let [out, into] = [ZERO, ZERO];
103
+ a.forEach((c, k) => {
104
+ if (c.numerator < 0n) out = out.add(c.divide(fin.pow(k)));
105
+ else into = into.add(c.multiply(re.pow(n - k)));
106
+ });
107
+ if (out.numerator === 0n || into.numerator === 0n) refuse("bad-flows", "the modified rate needs money going out and money coming in");
108
+ const root = power(into.divide(out.negate()), Q(1, n), digits);
109
+ return root instanceof RationalInterval ? new RationalInterval(root.low.subtract(ONE), root.high.subtract(ONE)) : root.subtract(ONE);
110
+ }
111
+
112
+ /**
113
+ * When the money comes back. { period: the first whole period at which the
114
+ * running total is no longer negative (null if never), fractional: the
115
+ * same with the last period split in proportion, cumulative }. With a rate
116
+ * the flows are discounted first.
117
+ */
118
+ export function payback(flows, { rate = 0 } = {}) {
119
+ const x = ONE.add(amount(rate));
120
+ const a = flows.map((c, k) => amount(c).divide(x.pow(k)));
121
+ const cumulative = [];
122
+ let run = ZERO;
123
+ let period = null;
124
+ let fractional = null;
125
+ a.forEach((c, k) => {
126
+ const before = run;
127
+ run = run.add(c);
128
+ cumulative.push(run);
129
+ if (period === null && run.numerator >= 0n && (k > 0 || a.length === 1)) {
130
+ period = k;
131
+ fractional = c.numerator === 0n || before.numerator >= 0n ? Q(k) : Q(k - 1).add(before.negate().divide(c));
132
+ }
133
+ });
134
+ return { period, fractional, cumulative };
135
+ }
136
+
137
+ /** What a nominal amount `periods` from now is worth in today's money: amount/(1 + inflation)^periods. */
138
+ export const realValue = (nominal, inflation, periods, opts = {}) => times(power(ONE.add(amount(inflation)), amount(periods).negate(), opts.digits), amount(nominal));
139
+ /** What today's amount becomes after `periods` of inflation: amount·(1 + inflation)^periods. */
140
+ export const nominalValue = (real, inflation, periods, opts = {}) => times(power(ONE.add(amount(inflation)), amount(periods), opts.digits), amount(real));
141
+
142
+ export const DEPRECIATION = Object.freeze(["straight-line", "declining-balance", "sum-of-years-digits", "units-of-production"]);
143
+ /**
144
+ * A depreciation schedule: [{ period, depreciation, accumulated, bookValue }].
145
+ * Methods: "straight-line"; "declining-balance" (rate factor/life on the
146
+ * book value, default factor 2, never below salvage, and with
147
+ * switchToStraightLine it changes over when that writes off more);
148
+ * "sum-of-years-digits"; "units-of-production" (units: use in each period,
149
+ * totalUnits: the whole life's use, default their sum).
150
+ */
151
+ export function depreciation({ cost, salvage = 0, life, method = "straight-line", factor = 2, switchToStraightLine = false, units, totalUnits, rounding = false } = {}) {
152
+ const [C, S] = [amount(cost), amount(salvage)];
153
+ const r = rounder(rounding);
154
+ const base = C.subtract(S);
155
+ if (base.numerator < 0n) refuse("bad-asset", "salvage is at most the cost");
156
+ const n = method === "units-of-production" ? (Array.isArray(units) ? units.length : refuse("bad-asset", "give the units used in each period")) : life;
157
+ if (!Number.isInteger(n) || n < 1) refuse("bad-asset", "the life is a whole number of periods, at least 1");
158
+ const rows = [];
159
+ let book = C;
160
+ const allUnits = method === "units-of-production" ? amount(totalUnits ?? units.map(amount).reduce((a, b) => a.add(b), ZERO)) : null;
161
+ for (let k = 1; k <= n; k++) {
162
+ const room = book.subtract(S);
163
+ let d;
164
+ if (method === "straight-line") d = base.divide(Q(n));
165
+ else if (method === "sum-of-years-digits") d = base.multiply(Q(n - k + 1)).divide(Q((n * (n + 1)) / 2));
166
+ else if (method === "units-of-production") d = base.multiply(amount(units[k - 1])).divide(allUnits);
167
+ else if (method === "declining-balance") {
168
+ d = book.multiply(amount(factor)).divide(Q(n));
169
+ const line = room.divide(Q(n - k + 1));
170
+ if (switchToStraightLine && line.compareTo(d) > 0) d = line;
171
+ } else refuse("bad-method", `the method is one of ${DEPRECIATION.join(", ")}`);
172
+ d = r(d);
173
+ if (d.compareTo(room) > 0 || (k === n && method !== "declining-balance" && method !== "units-of-production")) d = room; // the last period takes what is left, so the total is exact
174
+ book = book.subtract(d);
175
+ rows.push({ period: k, depreciation: d, accumulated: C.subtract(book), bookValue: book });
176
+ }
177
+ return rows;
178
+ }
179
+
180
+ /**
181
+ * A tax, or any charge, given as brackets: [{ upTo, rate }, …] in
182
+ * increasing order, the last with no upTo. No jurisdiction's table is
183
+ * built in; you supply the numbers. Returns { on(income), brackets }: on()
184
+ * gives { tax, marginalRate, averageRate, parts }.
185
+ */
186
+ export function taxSchedule(brackets, { rounding = false } = {}) {
187
+ if (!Array.isArray(brackets) || !brackets.length) refuse("bad-brackets", "give the brackets as a list of { upTo, rate }");
188
+ const r = rounder(rounding);
189
+ const rows = brackets.map((b, k) => ({ upTo: b.upTo === undefined || b.upTo === null || b.upTo === Infinity ? null : amount(b.upTo), rate: amount(b.rate), k }));
190
+ rows.forEach((b, k) => {
191
+ if (b.upTo === null && k !== rows.length - 1) refuse("bad-brackets", "only the last bracket is open-ended");
192
+ if (k > 0 && b.upTo !== null && b.upTo.compareTo(rows[k - 1].upTo) <= 0) refuse("bad-brackets", "the brackets go up");
193
+ });
194
+ if (rows[rows.length - 1].upTo !== null) refuse("bad-brackets", "the last bracket has no upTo, so every income is covered");
195
+ return {
196
+ brackets: rows.map(({ upTo, rate }) => ({ upTo, rate })),
197
+ on(income) {
198
+ const y = amount(income);
199
+ let from = ZERO;
200
+ let tax = ZERO;
201
+ let marginalRate = rows[0].rate;
202
+ const parts = [];
203
+ for (const b of rows) {
204
+ if (y.compareTo(from) <= 0) break;
205
+ const top = b.upTo === null || y.compareTo(b.upTo) < 0 ? y : b.upTo;
206
+ const slice = top.subtract(from);
207
+ const part = slice.multiply(b.rate);
208
+ parts.push({ from, to: top, rate: b.rate, tax: part });
209
+ tax = tax.add(part);
210
+ marginalRate = b.rate;
211
+ if (b.upTo === null) break;
212
+ from = b.upTo;
213
+ }
214
+ tax = r(tax);
215
+ return { tax, marginalRate, averageRate: y.numerator > 0n ? tax.divide(y) : ZERO, parts, afterTax: y.subtract(tax) };
216
+ },
217
+ };
218
+ }