@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/life.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// Life contingencies: a life table and the present values built on it. With
|
|
2
|
+
// a rational table and a rational interest rate every value is exact, so the
|
|
3
|
+
// classical identities (A = 1 − d·ä, a reserve that starts at zero) hold
|
|
4
|
+
// exactly rather than to rounding, and the tests check them that way.
|
|
5
|
+
//
|
|
6
|
+
// No published table is built in: the caller supplies the numbers, or uses
|
|
7
|
+
// de Moivre's law (a straight-line l_x) for teaching.
|
|
8
|
+
import { refuse, amount, ZERO, ONE, Q } from "./money.js";
|
|
9
|
+
|
|
10
|
+
export class LifeTable {
|
|
11
|
+
/**
|
|
12
|
+
* { l: [l at startAge, l at startAge + 1, …] } or { q: [q at startAge, …],
|
|
13
|
+
* radix = 100000 }, with startAge (default 0). The table closes: everyone
|
|
14
|
+
* alive at the last age dies within the year.
|
|
15
|
+
*/
|
|
16
|
+
constructor({ l, q, radix = 100000, startAge = 0 } = {}) {
|
|
17
|
+
if (!Number.isInteger(startAge) || startAge < 0) refuse("bad-table", "startAge is a whole number");
|
|
18
|
+
let L;
|
|
19
|
+
if (l) {
|
|
20
|
+
L = l.map(amount);
|
|
21
|
+
if (!L.length || L[0].numerator <= 0n) refuse("bad-table", "l starts with a positive number of lives");
|
|
22
|
+
for (let k = 1; k < L.length; k++) if (L[k].compareTo(L[k - 1]) > 0 || L[k].numerator < 0n) refuse("bad-table", "l never increases and is not negative");
|
|
23
|
+
} else if (q) {
|
|
24
|
+
const Qs = q.map(amount);
|
|
25
|
+
if (Qs.some((x) => x.numerator < 0n || x.compareTo(ONE) > 0)) refuse("bad-table", "each q is a probability");
|
|
26
|
+
L = [amount(radix)];
|
|
27
|
+
for (const x of Qs) L.push(L[L.length - 1].multiply(ONE.subtract(x)));
|
|
28
|
+
} else refuse("bad-table", "a life table needs l or q");
|
|
29
|
+
while (L.length > 1 && L[L.length - 1].numerator === 0n && L[L.length - 2].numerator === 0n) L.pop();
|
|
30
|
+
if (L[L.length - 1].numerator !== 0n) L.push(ZERO);
|
|
31
|
+
this.startAge = startAge;
|
|
32
|
+
this.lives = L;
|
|
33
|
+
this.lastAge = startAge + L.length - 2;
|
|
34
|
+
}
|
|
35
|
+
_age(x) {
|
|
36
|
+
if (!Number.isInteger(x)) refuse("bad-age", "ages are whole numbers");
|
|
37
|
+
if (x < this.startAge) refuse("bad-age", `the table starts at age ${this.startAge}`);
|
|
38
|
+
return x - this.startAge;
|
|
39
|
+
}
|
|
40
|
+
/** lives at age x (0 past the end) */
|
|
41
|
+
l(x) {
|
|
42
|
+
const k = this._age(x);
|
|
43
|
+
return k < this.lives.length ? this.lives[k] : ZERO;
|
|
44
|
+
}
|
|
45
|
+
/** deaths between x and x + 1 */
|
|
46
|
+
d(x) {
|
|
47
|
+
return this.l(x).subtract(this.l(x + 1));
|
|
48
|
+
}
|
|
49
|
+
/** probability that a life aged x survives t more years, tPx */
|
|
50
|
+
p(x, t = 1) {
|
|
51
|
+
const lx = this.l(x);
|
|
52
|
+
if (lx.numerator === 0n) refuse("bad-age", `no one in the table is alive at ${x}`);
|
|
53
|
+
return this.l(x + t).divide(lx);
|
|
54
|
+
}
|
|
55
|
+
/** probability that a life aged x dies within t years, tQx */
|
|
56
|
+
q(x, t = 1) {
|
|
57
|
+
return ONE.subtract(this.p(x, t));
|
|
58
|
+
}
|
|
59
|
+
/** probability of surviving u years and then dying within the next t: u|tQx */
|
|
60
|
+
deferredQ(x, u, t = 1) {
|
|
61
|
+
return this.l(x + u).subtract(this.l(x + u + t)).divide(this.l(x));
|
|
62
|
+
}
|
|
63
|
+
/** curtate expectation of life e_x = Σ_{k≥1} kPx (whole years lived) */
|
|
64
|
+
curtateExpectation(x) {
|
|
65
|
+
let s = ZERO;
|
|
66
|
+
for (let k = 1; x + k <= this.lastAge + 1; k++) s = s.add(this.p(x, k));
|
|
67
|
+
return s;
|
|
68
|
+
}
|
|
69
|
+
/** complete expectation under a uniform distribution of deaths within each year: e_x + 1/2 */
|
|
70
|
+
completeExpectation(x) {
|
|
71
|
+
return this.curtateExpectation(x).add(Q(1, 2));
|
|
72
|
+
}
|
|
73
|
+
/** rows { age, l, d, q, p, e } for printing */
|
|
74
|
+
rows() {
|
|
75
|
+
const out = [];
|
|
76
|
+
for (let x = this.startAge; x <= this.lastAge; x++) out.push({ age: x, l: this.l(x), d: this.d(x), q: this.q(x), p: this.p(x), e: this.curtateExpectation(x) });
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
export const lifeTable = (spec) => new LifeTable(spec);
|
|
81
|
+
/** de Moivre's law: l_x = ω − x, so deaths are uniform up to the limiting age ω. */
|
|
82
|
+
export const deMoivre = (omega, { startAge = 0 } = {}) => {
|
|
83
|
+
if (!Number.isInteger(omega) || omega <= startAge) refuse("bad-table", "ω is a whole number above the start age");
|
|
84
|
+
return new LifeTable({ l: Array.from({ length: omega - startAge + 1 }, (_, k) => omega - startAge - k), startAge });
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const vOf = (rate) => {
|
|
88
|
+
const i = amount(rate);
|
|
89
|
+
if (i.compareTo(ONE.negate()) <= 0) refuse("bad-rate", "the rate is above −100%");
|
|
90
|
+
return ONE.divide(ONE.add(i));
|
|
91
|
+
};
|
|
92
|
+
const horizon = (table, x, term) => (term === null || term === undefined ? table.lastAge + 1 - x : term);
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Life annuity of 1 a year for a life aged x: due (payments at the start of
|
|
96
|
+
* each year, ä) or immediate (at the end, a), for `term` years (default for
|
|
97
|
+
* life), after `deferred` years. Exact: Σ v^k · kPx over the payment times.
|
|
98
|
+
*/
|
|
99
|
+
export function lifeAnnuity(table, { age, rate, term = null, due = true, deferred = 0 }) {
|
|
100
|
+
const v = vOf(rate);
|
|
101
|
+
const n = horizon(table, age + deferred, term);
|
|
102
|
+
let s = ZERO;
|
|
103
|
+
for (let j = 0; j < n; j++) {
|
|
104
|
+
const k = deferred + j + (due ? 0 : 1);
|
|
105
|
+
s = s.add(v.pow(BigInt(k)).multiply(table.p(age, k)));
|
|
106
|
+
}
|
|
107
|
+
return s;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Life insurance of 1 paid at the end of the year of death, for a life aged
|
|
111
|
+
* x: whole life (term null) or for `term` years, after `deferred` years.
|
|
112
|
+
* Exact: Σ v^{k+1} · k|qx.
|
|
113
|
+
*/
|
|
114
|
+
export function lifeInsurance(table, { age, rate, term = null, deferred = 0 }) {
|
|
115
|
+
const v = vOf(rate);
|
|
116
|
+
const n = horizon(table, age + deferred, term);
|
|
117
|
+
let s = ZERO;
|
|
118
|
+
for (let j = 0; j < n; j++) {
|
|
119
|
+
const k = deferred + j;
|
|
120
|
+
s = s.add(v.pow(BigInt(k + 1)).multiply(table.deferredQ(age, k)));
|
|
121
|
+
}
|
|
122
|
+
return s;
|
|
123
|
+
}
|
|
124
|
+
/** pure endowment nEx = v^n · nPx: 1 paid at time n if the life is alive */
|
|
125
|
+
export const pureEndowment = (table, { age, rate, term }) => vOf(rate).pow(BigInt(term)).multiply(table.p(age, term));
|
|
126
|
+
/** endowment insurance: term insurance plus the pure endowment */
|
|
127
|
+
export const endowment = (table, { age, rate, term }) => lifeInsurance(table, { age, rate, term }).add(pureEndowment(table, { age, rate, term }));
|
|
128
|
+
|
|
129
|
+
const KINDS = new Set(["whole life", "term", "endowment"]);
|
|
130
|
+
const benefitValue = (table, kind, age, rate, term) => (kind === "whole life" ? lifeInsurance(table, { age, rate }) : kind === "term" ? lifeInsurance(table, { age, rate, term }) : endowment(table, { age, rate, term }));
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The level annual net premium (paid at the start of each year while alive,
|
|
134
|
+
* for `payments` years) for a benefit: { kind: "whole life" | "term" |
|
|
135
|
+
* "endowment", benefit = 1, age, rate, term, payments }. Exact, by the
|
|
136
|
+
* equivalence principle: premium · ä = benefit · A.
|
|
137
|
+
*/
|
|
138
|
+
export function netPremium(table, { kind = "whole life", benefit = 1, age, rate, term = null, payments = null }) {
|
|
139
|
+
if (!KINDS.has(kind)) refuse("bad-argument", 'kind is "whole life", "term" or "endowment"');
|
|
140
|
+
if (kind !== "whole life" && (term === null || term < 1)) refuse("bad-argument", `a ${kind} policy needs a term`);
|
|
141
|
+
const A = benefitValue(table, kind, age, rate, term);
|
|
142
|
+
const ann = lifeAnnuity(table, { age, rate, term: payments ?? term });
|
|
143
|
+
return amount(benefit).multiply(A).divide(ann);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* The prospective net reserve after t years: the value then of the benefit
|
|
147
|
+
* still to come less the value of the premiums still to come. Zero at t = 0
|
|
148
|
+
* by construction of the net premium.
|
|
149
|
+
*/
|
|
150
|
+
export function reserve(table, { kind = "whole life", benefit = 1, age, rate, term = null, payments = null, time }) {
|
|
151
|
+
const P = netPremium(table, { kind, benefit, age, rate, term, payments });
|
|
152
|
+
const x = age + time;
|
|
153
|
+
const left = term === null ? null : term - time;
|
|
154
|
+
if (left !== null && left < 0) refuse("bad-argument", "the time is past the term");
|
|
155
|
+
const A = kind === "whole life" ? lifeInsurance(table, { age: x, rate }) : left === 0 ? (kind === "endowment" ? ONE : ZERO) : benefitValue(table, kind, x, rate, left);
|
|
156
|
+
const pay = payments ?? term;
|
|
157
|
+
const payLeft = pay === null ? null : Math.max(0, pay - time);
|
|
158
|
+
const ann = payLeft === 0 ? ZERO : lifeAnnuity(table, { age: x, rate, term: payLeft });
|
|
159
|
+
return amount(benefit).multiply(A).subtract(P.multiply(ann));
|
|
160
|
+
}
|
package/src/loans.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
// Loans: amortisation schedules under a stated rounding rule, with extra
|
|
2
|
+
// payments, interest-only periods, balloons and changes of rate; comparing
|
|
3
|
+
// and refinancing; revolving credit. Every row is exact to the cent and the
|
|
4
|
+
// last payment is whatever clears the balance, shown as such.
|
|
5
|
+
import { Rational, RationalInterval } from "@ratmath/core";
|
|
6
|
+
import { refuse, amount, ZERO, ONE, Q, rounder, power, format } from "./money.js";
|
|
7
|
+
import { tvm } from "./tvm.js";
|
|
8
|
+
|
|
9
|
+
const sum = (xs) => xs.reduce((a, b) => a.add(b), ZERO);
|
|
10
|
+
const pos = (x) => x.numerator > 0n;
|
|
11
|
+
const min = (a, b) => (a.compareTo(b) <= 0 ? a : b);
|
|
12
|
+
const wholeNumber = (n, what) => (Number.isInteger(n) && n >= 0 ? n : refuse("bad-periods", `${what} is a whole number that is not negative`));
|
|
13
|
+
|
|
14
|
+
/** the level payment that takes a balance to `balloon` in n periods at a periodic rate, exactly */
|
|
15
|
+
export function levelPayment(balance, periodicRate, periods, balloon = 0) {
|
|
16
|
+
const [B, i, F] = [amount(balance), amount(periodicRate), amount(balloon)];
|
|
17
|
+
const n = wholeNumber(periods, "the number of payments");
|
|
18
|
+
if (n === 0) refuse("bad-periods", "a loan has at least one payment");
|
|
19
|
+
if (i.numerator === 0n) return B.subtract(F).divide(Q(n));
|
|
20
|
+
const v = ONE.divide(ONE.add(i).pow(n));
|
|
21
|
+
return B.subtract(F.multiply(v)).multiply(i).divide(ONE.subtract(v));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* A loan and its schedule.
|
|
26
|
+
* loan({ principal: 250000, rate: "6%", periods: 360 })
|
|
27
|
+
* `rate` is the nominal annual rate; the rate per period is rate/periodsPerYear.
|
|
28
|
+
* Options: payment (fix it yourself; then periods may be left out),
|
|
29
|
+
* rounding ({ places, mode }, a number of places, or false for none),
|
|
30
|
+
* extra (an amount every period, { period: amount }, or (period, balance) => amount),
|
|
31
|
+
* interestOnly (a number of opening periods), balloon (left owing and paid
|
|
32
|
+
* with the last payment), rateChanges ([{ from: period, rate }]; the payment
|
|
33
|
+
* is worked out again from that period unless you fixed it).
|
|
34
|
+
*/
|
|
35
|
+
export function loan({ principal, rate, periods, periodsPerYear = 12, payment, rounding, extra = 0, interestOnly = 0, balloon = 0, rateChanges = [] } = {}) {
|
|
36
|
+
const P = amount(principal);
|
|
37
|
+
const F = amount(balloon);
|
|
38
|
+
const m = amount(periodsPerYear);
|
|
39
|
+
const r = rounder(rounding);
|
|
40
|
+
if (!pos(P)) refuse("bad-loan", "the principal is positive");
|
|
41
|
+
if (periods === undefined && payment === undefined) refuse("bad-loan", "give the number of periods, the payment, or both");
|
|
42
|
+
const n = periods === undefined ? null : wholeNumber(periods, "the number of periods");
|
|
43
|
+
wholeNumber(interestOnly, "interestOnly");
|
|
44
|
+
if (n !== null && interestOnly >= n) refuse("bad-loan", "the interest-only periods must end before the loan does");
|
|
45
|
+
const changes = new Map(rateChanges.map((c) => [wholeNumber(c.from, "a rate change's period"), amount(c.rate).divide(m)]));
|
|
46
|
+
const extraAt = typeof extra === "function" ? (k, b) => amount(extra(k, b) ?? 0) : extra !== null && typeof extra === "object" && !(extra instanceof Rational) ? (k) => amount(extra[k] ?? 0) : () => amount(extra);
|
|
47
|
+
const fixed = payment === undefined ? null : r(amount(payment));
|
|
48
|
+
let i = amount(rate).divide(m);
|
|
49
|
+
let balance = P;
|
|
50
|
+
let level = fixed;
|
|
51
|
+
let regular = null;
|
|
52
|
+
const exactPayment = n !== null && interestOnly === 0 ? levelPayment(P, i, n, F) : null;
|
|
53
|
+
const schedule = [];
|
|
54
|
+
if (n === null && pos(F)) refuse("bad-loan", "a balloon needs the number of periods");
|
|
55
|
+
const cap = n ?? 1200;
|
|
56
|
+
for (let k = 1; k <= cap && pos(balance); k++) {
|
|
57
|
+
let recompute = level === null;
|
|
58
|
+
if (changes.has(k)) {
|
|
59
|
+
i = changes.get(k);
|
|
60
|
+
recompute = recompute || fixed === null;
|
|
61
|
+
}
|
|
62
|
+
if (k === interestOnly + 1 && fixed === null) recompute = true;
|
|
63
|
+
const interest = r(balance.multiply(i));
|
|
64
|
+
const owing = balance.subtract(F);
|
|
65
|
+
let final = n !== null && k === n;
|
|
66
|
+
let pay = interest;
|
|
67
|
+
let towards = ZERO;
|
|
68
|
+
if (k > interestOnly) {
|
|
69
|
+
if (recompute) level = r(levelPayment(balance, i, n - k + 1, F));
|
|
70
|
+
regular ??= level;
|
|
71
|
+
towards = level.subtract(interest);
|
|
72
|
+
if (!pos(towards) && !final) refuse("negative-amortisation", `in period ${k} the payment ${format(level)} does not cover the interest ${format(interest)}`);
|
|
73
|
+
if (final || towards.compareTo(owing) >= 0) {
|
|
74
|
+
towards = owing;
|
|
75
|
+
final = true;
|
|
76
|
+
}
|
|
77
|
+
pay = interest.add(towards);
|
|
78
|
+
}
|
|
79
|
+
const room = owing.subtract(towards);
|
|
80
|
+
const wanted = final ? ZERO : r(extraAt(k, balance));
|
|
81
|
+
if (wanted.numerator < 0n) refuse("bad-extra", "an extra payment cannot be negative");
|
|
82
|
+
const more = min(wanted, room);
|
|
83
|
+
if (!final && pos(more) && more.equals(room)) final = true;
|
|
84
|
+
balance = balance.subtract(towards).subtract(more);
|
|
85
|
+
const row = { period: k, rate: i, payment: pay, interest, principal: towards, extra: more, balance };
|
|
86
|
+
if (final) {
|
|
87
|
+
if (pos(balance)) row.balloon = balance;
|
|
88
|
+
balance = ZERO;
|
|
89
|
+
row.balance = ZERO;
|
|
90
|
+
}
|
|
91
|
+
schedule.push(row);
|
|
92
|
+
}
|
|
93
|
+
if (pos(balance)) refuse("not-repaid", `the loan is not repaid after ${cap} periods`);
|
|
94
|
+
const totals = {
|
|
95
|
+
payments: sum(schedule.map((s) => s.payment.add(s.extra).add(s.balloon ?? ZERO))),
|
|
96
|
+
interest: sum(schedule.map((s) => s.interest)),
|
|
97
|
+
principal: sum(schedule.map((s) => s.principal.add(s.extra).add(s.balloon ?? ZERO))),
|
|
98
|
+
extra: sum(schedule.map((s) => s.extra)),
|
|
99
|
+
};
|
|
100
|
+
const lastRow = schedule[schedule.length - 1];
|
|
101
|
+
return { principal: P, periodsPerYear: m, payment: regular ?? fixed ?? schedule[0].payment, exactPayment, schedule, periods: schedule.length, finalPayment: lastRow.payment, balloon: lastRow.balloon ?? ZERO, totals };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const asLoan = (x) => (x && x.schedule ? x : loan(x));
|
|
105
|
+
/** Two loans side by side: payment, number of payments, interest and total paid, and the differences (b − a). */
|
|
106
|
+
export function compareLoans(a, b) {
|
|
107
|
+
const [A, B] = [asLoan(a), asLoan(b)];
|
|
108
|
+
const row = (l) => ({ payment: l.payment, periods: l.periods, interest: l.totals.interest, total: l.totals.payments });
|
|
109
|
+
return { a: row(A), b: row(B), difference: { payment: B.payment.subtract(A.payment), periods: B.periods - A.periods, interest: B.totals.interest.subtract(A.totals.interest), total: B.totals.payments.subtract(A.totals.payments) } };
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Refinancing: keep the current loan (its balance, rate and remaining
|
|
113
|
+
* periods) or replace it with a new one that has costs. `costs` are paid
|
|
114
|
+
* up front unless rollIn is true, when they are added to the new principal.
|
|
115
|
+
* breakEven is the first period at which the payments saved add up to the costs.
|
|
116
|
+
*/
|
|
117
|
+
export function refinance(current, proposed, { costs = 0, rollIn = false, rounding } = {}) {
|
|
118
|
+
const C = amount(costs);
|
|
119
|
+
const balance = amount(current.balance ?? current.principal);
|
|
120
|
+
const keep = loan({ ...current, principal: balance, rounding: current.rounding ?? rounding });
|
|
121
|
+
const next = loan({ periodsPerYear: current.periodsPerYear, ...proposed, principal: rollIn ? balance.add(C) : balance, rounding: proposed.rounding ?? rounding });
|
|
122
|
+
const upFront = rollIn ? ZERO : C;
|
|
123
|
+
let saved = upFront.negate();
|
|
124
|
+
let breakEven = null;
|
|
125
|
+
const horizon = Math.max(keep.periods, next.periods);
|
|
126
|
+
for (let k = 1; k <= horizon; k++) {
|
|
127
|
+
const paid = (l) => (k <= l.periods ? l.schedule[k - 1].payment.add(l.schedule[k - 1].extra).add(l.schedule[k - 1].balloon ?? ZERO) : ZERO);
|
|
128
|
+
saved = saved.add(paid(keep)).subtract(paid(next));
|
|
129
|
+
if (breakEven === null && saved.numerator >= 0n && k <= next.periods) breakEven = k;
|
|
130
|
+
}
|
|
131
|
+
return { current: keep, proposed: next, costs: C, paymentChange: next.payment.subtract(keep.payment), interestSaved: keep.totals.interest.subtract(next.totals.interest), totalSaved: saved, breakEven, worthIt: saved.numerator > 0n };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Revolving credit: interest on the balance each period, then a payment
|
|
136
|
+
* that is a fixed amount or { percent, minimum } of the balance, then any
|
|
137
|
+
* new purchases. Runs until the balance is cleared.
|
|
138
|
+
*/
|
|
139
|
+
export function revolving({ balance, rate, periodsPerYear = 12, payment, purchases = 0, rounding, maxPeriods = 1200 } = {}) {
|
|
140
|
+
const r = rounder(rounding);
|
|
141
|
+
const i = amount(rate).divide(amount(periodsPerYear));
|
|
142
|
+
let B = amount(balance);
|
|
143
|
+
const buy = typeof purchases === "function" ? (k) => amount(purchases(k) ?? 0) : () => amount(purchases);
|
|
144
|
+
const due = (b) => {
|
|
145
|
+
if (payment !== null && typeof payment === "object" && !(payment instanceof Rational)) {
|
|
146
|
+
const pct = r(b.multiply(amount(payment.percent ?? 0)));
|
|
147
|
+
const floor = amount(payment.minimum ?? 0);
|
|
148
|
+
return pct.compareTo(floor) >= 0 ? pct : floor;
|
|
149
|
+
}
|
|
150
|
+
return r(amount(payment));
|
|
151
|
+
};
|
|
152
|
+
const schedule = [];
|
|
153
|
+
for (let k = 1; pos(B); k++) {
|
|
154
|
+
if (k > maxPeriods) refuse("not-repaid", `the balance is not cleared after ${maxPeriods} periods; the payment barely covers the interest`);
|
|
155
|
+
const interest = r(B.multiply(i));
|
|
156
|
+
const owed = B.add(interest);
|
|
157
|
+
const pay = min(due(owed), owed);
|
|
158
|
+
const bought = buy(k);
|
|
159
|
+
const next = owed.subtract(pay).add(bought);
|
|
160
|
+
if (!pos(pay.subtract(interest).subtract(bought)) && k > 1 && next.compareTo(schedule[schedule.length - 1].balance) >= 0 && typeof purchases !== "function" && !(payment !== null && typeof payment === "object")) refuse("never-repaid", `a payment of ${format(pay)} does not cover the interest of ${format(interest)}${pos(bought) ? " and the new purchases" : ""}, so the balance never falls`);
|
|
161
|
+
schedule.push({ period: k, interest, payment: pay, purchases: bought, balance: next });
|
|
162
|
+
B = next;
|
|
163
|
+
}
|
|
164
|
+
return { schedule, periods: schedule.length, totals: { payments: sum(schedule.map((s) => s.payment)), interest: sum(schedule.map((s) => s.interest)) } };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The rate a borrower really pays once fees are counted: the borrower
|
|
169
|
+
* receives principal − fees and makes the payments. { periodic, nominal
|
|
170
|
+
* (the APR: periodic × periodsPerYear), effective }, each exact or enclosed.
|
|
171
|
+
*/
|
|
172
|
+
export function loanAPR({ principal, fees = 0, payment, periods, periodsPerYear = 12, balloon = 0, digits = 12 } = {}) {
|
|
173
|
+
const m = amount(periodsPerYear);
|
|
174
|
+
const solved = tvm({ pv: amount(principal).subtract(amount(fees)), pmt: amount(payment).negate(), fv: amount(balloon).negate(), n: periods, digits: digits + 2 });
|
|
175
|
+
if (solved.count !== 1) refuse("no-rate", `expected one rate, found ${solved.count}`);
|
|
176
|
+
const p = solved.rates[0].rate;
|
|
177
|
+
const times = (x, k) => (x instanceof RationalInterval ? new RationalInterval(x.low.multiply(k), x.high.multiply(k)) : x.multiply(k));
|
|
178
|
+
let effective;
|
|
179
|
+
if (p instanceof RationalInterval) {
|
|
180
|
+
const e = (q) => power(ONE.add(q), m, digits + 2);
|
|
181
|
+
const [lo, hi] = [e(p.low), e(p.high)];
|
|
182
|
+
effective = new RationalInterval((lo instanceof RationalInterval ? lo.low : lo).subtract(ONE), (hi instanceof RationalInterval ? hi.high : hi).subtract(ONE));
|
|
183
|
+
} else {
|
|
184
|
+
const e = power(ONE.add(p), m, digits);
|
|
185
|
+
effective = e instanceof RationalInterval ? new RationalInterval(e.low.subtract(ONE), e.high.subtract(ONE)) : e.subtract(ONE);
|
|
186
|
+
}
|
|
187
|
+
return { periodic: p, nominal: times(p, m), effective, exact: solved.rates[0].exact };
|
|
188
|
+
}
|
package/src/money.js
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
// Money as exact rationals. An amount is a Core Rational; nothing is rounded
|
|
2
|
+
// unless a rounding rule is named, and then the rule says how. Also here:
|
|
3
|
+
// calendar dates and day-count conventions, and the certified power that
|
|
4
|
+
// the rest of the package uses when an exponent is not a whole number.
|
|
5
|
+
import { Rational, RationalInterval, ROUNDING_MODES, isRoundingMode, rounding } from "@ratmath/core";
|
|
6
|
+
import { enclose } from "@ratmath/analytic";
|
|
7
|
+
|
|
8
|
+
export class FinanceError extends Error {
|
|
9
|
+
constructor(code, message) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = "FinanceError";
|
|
12
|
+
this.code = code;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export const refuse = (code, message) => {
|
|
16
|
+
throw new FinanceError(code, message);
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export const ZERO = new Rational(0n);
|
|
20
|
+
export const ONE = new Rational(1n);
|
|
21
|
+
export const Q = (n, d = 1) => new Rational(BigInt(n), BigInt(d));
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* An exact amount or rate from a whole number, a bigint, a Rational or a
|
|
25
|
+
* string: "1234.56", "1,234.56", "$1,234.56", "7/8", "4.5%" (= 9/200),
|
|
26
|
+
* "-250". A JavaScript number that is not whole is refused, since 0.1 is
|
|
27
|
+
* not one tenth.
|
|
28
|
+
*/
|
|
29
|
+
export function amount(x) {
|
|
30
|
+
if (x instanceof Rational) return x;
|
|
31
|
+
if (typeof x === "bigint") return new Rational(x);
|
|
32
|
+
if (typeof x === "number") {
|
|
33
|
+
if (Number.isSafeInteger(x)) return new Rational(BigInt(x));
|
|
34
|
+
refuse("inexact", `${x} is a floating-point number; write it as a string ("${x}") so its exact value is the one you typed`);
|
|
35
|
+
}
|
|
36
|
+
if (typeof x === "string") {
|
|
37
|
+
let s = x.trim().replace(/[\s,_]/g, "").replace(/^([-+]?)[$€£¥]/, "$1").replace(/−/g, "-");
|
|
38
|
+
const percent = s.endsWith("%");
|
|
39
|
+
if (percent) s = s.slice(0, -1);
|
|
40
|
+
let q = null;
|
|
41
|
+
const dec = /^([-+]?)(\d*)\.?(\d*)$/.exec(s);
|
|
42
|
+
if (dec && (dec[2] || dec[3])) q = new Rational(BigInt((dec[1] === "-" ? "-" : "") + (dec[2] || "0") + dec[3]), 10n ** BigInt(dec[3].length));
|
|
43
|
+
const frac = /^([-+]?\d+)\/(\d+)$/.exec(s);
|
|
44
|
+
if (frac && BigInt(frac[2]) !== 0n) q = new Rational(BigInt(frac[1]), BigInt(frac[2]));
|
|
45
|
+
if (q) return percent ? q.divide(Q(100)) : q;
|
|
46
|
+
}
|
|
47
|
+
if (x && typeof x === "object" && x.isDual) return x;
|
|
48
|
+
refuse("bad-number", `cannot read ${String(x)} as an exact amount`);
|
|
49
|
+
}
|
|
50
|
+
/** A rate: the same reading as `amount`, so "5%" and "0.05" are both 1/20. */
|
|
51
|
+
export const rate = amount;
|
|
52
|
+
|
|
53
|
+
// Finance's own names for the directed rules, on top of every name Core knows.
|
|
54
|
+
const ALIASES = { up: "away-from-zero", down: "toward-zero" };
|
|
55
|
+
/**
|
|
56
|
+
* The rule money is rounded by when none is named: half-even (banker's
|
|
57
|
+
* rounding), the usual default in accounting and financial software because
|
|
58
|
+
* ties do not drift totals upward. One constant, so the default can be
|
|
59
|
+
* changed in one place; pass `mode` to use another rule.
|
|
60
|
+
*/
|
|
61
|
+
export const MONEY_ROUNDING = "half-even";
|
|
62
|
+
const rounders = new Map();
|
|
63
|
+
/**
|
|
64
|
+
* A Core rounder for a mode: a name from Core's ROUNDING_MODES, "up" or
|
|
65
|
+
* "down" (away from and towards zero), a rounder made by Core's
|
|
66
|
+
* `rounding(...)`, or your own function given { value, floor, ceil, fraction }
|
|
67
|
+
* and returning floor or ceil.
|
|
68
|
+
*/
|
|
69
|
+
export function moneyRounder(mode = MONEY_ROUNDING) {
|
|
70
|
+
if (typeof mode === "function") return typeof mode.mode === "undefined" ? rounding(mode) : mode;
|
|
71
|
+
const name = ALIASES[mode] ?? mode;
|
|
72
|
+
if (!isRoundingMode(name)) refuse("bad-rounding", `the rounding mode is one of ${[...ROUNDING_MODES, ...Object.keys(ALIASES)].join(", ")}, or a function`);
|
|
73
|
+
if (!rounders.has(name)) rounders.set(name, rounding(name));
|
|
74
|
+
return rounders.get(name);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Round to a number of decimal places under a rule (MONEY_ROUNDING, so
|
|
78
|
+
* half-even, unless one is named). half-up sends a tie away from zero (the
|
|
79
|
+
* commercial rule, and what many tax and currency-conversion rules require)
|
|
80
|
+
* and half-down towards it; up and down are away from and towards zero;
|
|
81
|
+
* floor and ceil are towards −∞ and +∞. Every Core rounding mode and a
|
|
82
|
+
* custom function also work: see `moneyRounder`.
|
|
83
|
+
*/
|
|
84
|
+
export function round(x, { places = 2, mode = MONEY_ROUNDING } = {}) {
|
|
85
|
+
const r = moneyRounder(mode);
|
|
86
|
+
if (!Number.isInteger(places) || places < -30 || places > 60) refuse("bad-rounding", "places is a whole number from -30 to 60");
|
|
87
|
+
return r(amount(x), places);
|
|
88
|
+
}
|
|
89
|
+
/** rounding rule from an option: false or "none" for no rounding, a number of places, or { places, mode } */
|
|
90
|
+
export function rounder(rule) {
|
|
91
|
+
if (rule === false || rule === null || rule === "none") return (x) => x;
|
|
92
|
+
const r = rule === undefined || rule === true ? {} : typeof rule === "number" ? { places: rule } : typeof rule === "string" || typeof rule === "function" ? { mode: rule } : rule;
|
|
93
|
+
round(ZERO, r);
|
|
94
|
+
return (x) => round(x, r);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** "1,234.50" from an exact amount: rounded for display only, by the rule given */
|
|
98
|
+
export function format(x, { places = 2, mode = MONEY_ROUNDING, currency = "", separator = ",", percent = false } = {}) {
|
|
99
|
+
let q = amount(x);
|
|
100
|
+
if (percent) q = q.multiply(Q(100));
|
|
101
|
+
const r = round(q, { places, mode });
|
|
102
|
+
const neg = r.numerator < 0n;
|
|
103
|
+
const scaled = (neg ? -r.numerator : r.numerator) * 10n ** BigInt(Math.max(places, 0)) / r.denominator;
|
|
104
|
+
let digits = scaled.toString().padStart(Math.max(places, 0) + 1, "0");
|
|
105
|
+
const whole = places > 0 ? digits.slice(0, -places) : digits;
|
|
106
|
+
const part = places > 0 ? "." + digits.slice(-places) : "";
|
|
107
|
+
const grouped = separator ? whole.replace(/\B(?=(\d{3})+(?!\d))/g, separator) : whole;
|
|
108
|
+
return `${neg ? "-" : ""}${currency}${grouped}${part}${percent ? "%" : ""}`;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Split a total into parts in proportion to weights so that the rounded
|
|
113
|
+
* parts add up to the total exactly: each part is rounded down and the
|
|
114
|
+
* units left over go to the parts with the largest remainders.
|
|
115
|
+
*/
|
|
116
|
+
export function allocate(total, weights, { places = 2 } = {}) {
|
|
117
|
+
const t = amount(total);
|
|
118
|
+
const w = weights.map(amount);
|
|
119
|
+
const sum = w.reduce((a, b) => a.add(b), ZERO);
|
|
120
|
+
if (w.some((x) => x.numerator < 0n) || sum.numerator === 0n) refuse("bad-weights", "weights are non-negative and not all zero");
|
|
121
|
+
const unit = Q(1n, 10n ** BigInt(places));
|
|
122
|
+
if (!round(t, { places, mode: "down" }).equals(t)) refuse("bad-total", `the total has more than ${places} decimal places`);
|
|
123
|
+
const exact = w.map((x) => t.multiply(x).divide(sum));
|
|
124
|
+
const parts = exact.map((x) => round(x, { places, mode: "floor" }));
|
|
125
|
+
let left = t.subtract(parts.reduce((a, b) => a.add(b), ZERO)).divide(unit).numerator;
|
|
126
|
+
const order = exact.map((x, i) => [x.subtract(parts[i]), i]).sort((a, b) => b[0].compareTo(a[0]) || a[1] - b[1]);
|
|
127
|
+
for (let k = 0; left > 0n; k++, left -= 1n) parts[order[k % order.length][1]] = parts[order[k % order.length][1]].add(unit);
|
|
128
|
+
return parts;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ---- certified powers ----------------------------------------------------------
|
|
132
|
+
|
|
133
|
+
const iroot = (n, k) => {
|
|
134
|
+
// the exact k-th root of a non-negative bigint, or null
|
|
135
|
+
if (n < 2n) return n;
|
|
136
|
+
let lo = 1n;
|
|
137
|
+
let hi = 1n << BigInt(Math.ceil(n.toString(2).length / k) + 1);
|
|
138
|
+
while (lo < hi) {
|
|
139
|
+
const mid = (lo + hi + 1n) >> 1n;
|
|
140
|
+
if (mid ** BigInt(k) <= n) lo = mid;
|
|
141
|
+
else hi = mid - 1n;
|
|
142
|
+
}
|
|
143
|
+
return lo ** BigInt(k) === n ? lo : null;
|
|
144
|
+
};
|
|
145
|
+
const point = (q) => new RationalInterval(q, q);
|
|
146
|
+
const bitsFor = (digits) => Math.ceil(digits * 3.33) + 40;
|
|
147
|
+
/** e^x enclosed for a rational or an interval */
|
|
148
|
+
export const exp = (x, digits = 12) => enclose.exp(x instanceof RationalInterval ? x : point(amount(x)), bitsFor(digits));
|
|
149
|
+
/** ln x enclosed */
|
|
150
|
+
export const ln = (x, digits = 12) => enclose.log(x instanceof RationalInterval ? x : point(amount(x)), bitsFor(digits));
|
|
151
|
+
/**
|
|
152
|
+
* base^exponent for a positive rational base. Exact (a Rational) when the
|
|
153
|
+
* exponent is whole or the root comes out rational; otherwise an interval
|
|
154
|
+
* proven to contain the value, narrow to about `digits` digits.
|
|
155
|
+
*/
|
|
156
|
+
export function power(base, exponent, digits = 12) {
|
|
157
|
+
const b = amount(base);
|
|
158
|
+
const e = amount(exponent);
|
|
159
|
+
if (e.denominator === 1n) {
|
|
160
|
+
if (b.numerator === 0n && e.numerator <= 0n) refuse("division", "zero to a power that is not positive");
|
|
161
|
+
return e.numerator >= 0n ? b.pow(e.numerator) : ONE.divide(b.pow(-e.numerator));
|
|
162
|
+
}
|
|
163
|
+
if (b.numerator <= 0n) refuse("domain", "a fractional power needs a positive base");
|
|
164
|
+
if (e.denominator < 4096n) {
|
|
165
|
+
const k = Number(e.denominator);
|
|
166
|
+
const [n, d] = [iroot(b.numerator, k), iroot(b.denominator, k)];
|
|
167
|
+
if (n !== null && d !== null) return power(new Rational(n, d), new Rational(e.numerator), digits);
|
|
168
|
+
}
|
|
169
|
+
const bits = bitsFor(digits) + Math.max(0, e.toNumber() > 0 ? Math.ceil(Math.log2(1 + Math.abs(e.toNumber() * Math.log(b.toNumber())))) * 2 : 0);
|
|
170
|
+
const l = enclose.log(point(b), bits);
|
|
171
|
+
const [u, v] = [l.low.multiply(e), l.high.multiply(e)];
|
|
172
|
+
return enclose.exp(u.compareTo(v) <= 0 ? new RationalInterval(u, v) : new RationalInterval(v, u), bits);
|
|
173
|
+
}
|
|
174
|
+
/** the low and high ends of an exact number or an interval */
|
|
175
|
+
export const ends = (x) => (x instanceof RationalInterval ? [x.low, x.high] : [x, x]);
|
|
176
|
+
/**
|
|
177
|
+
* An exact number or an interval as a decimal with `places` places. For an
|
|
178
|
+
* interval both ends are rounded: when they agree, that is the correctly
|
|
179
|
+
* rounded value, proven; when a rounding boundary falls inside it, the two
|
|
180
|
+
* ends are shown.
|
|
181
|
+
*/
|
|
182
|
+
export function show(x, places = 6) {
|
|
183
|
+
if (!(x instanceof RationalInterval)) return format(x, { places, separator: "" });
|
|
184
|
+
const [a, b] = [format(x.low, { places, separator: "" }), format(x.high, { places, separator: "" })];
|
|
185
|
+
return a === b ? a : `[${format(x.low, { places, mode: "floor", separator: "" })}, ${format(x.high, { places, mode: "ceil", separator: "" })}]`;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// ---- dates and day counts ------------------------------------------------------
|
|
189
|
+
|
|
190
|
+
// days from 1970-01-01 in the proleptic Gregorian calendar (Howard Hinnant's algorithm)
|
|
191
|
+
const toDays = (y, m, d) => {
|
|
192
|
+
y -= m <= 2 ? 1 : 0;
|
|
193
|
+
const era = Math.floor(y / 400);
|
|
194
|
+
const yoe = y - era * 400;
|
|
195
|
+
const doy = Math.floor((153 * (m + (m > 2 ? -3 : 9)) + 2) / 5) + d - 1;
|
|
196
|
+
return era * 146097 + yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy - 719468;
|
|
197
|
+
};
|
|
198
|
+
const fromDays = (z) => {
|
|
199
|
+
z += 719468;
|
|
200
|
+
const era = Math.floor(z / 146097);
|
|
201
|
+
const doe = z - era * 146097;
|
|
202
|
+
const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);
|
|
203
|
+
const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
|
|
204
|
+
const mp = Math.floor((5 * doy + 2) / 153);
|
|
205
|
+
const d = doy - Math.floor((153 * mp + 2) / 5) + 1;
|
|
206
|
+
const m = mp < 10 ? mp + 3 : mp - 9;
|
|
207
|
+
return [yoe + era * 400 + (m <= 2 ? 1 : 0), m, d];
|
|
208
|
+
};
|
|
209
|
+
export const isLeap = (y) => (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
|
|
210
|
+
const monthLength = (y, m) => [31, isLeap(y) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1];
|
|
211
|
+
|
|
212
|
+
/** A calendar date, with no time of day and no time zone. */
|
|
213
|
+
export class CalendarDate {
|
|
214
|
+
constructor(year, month, day) {
|
|
215
|
+
if (![year, month, day].every(Number.isInteger) || month < 1 || month > 12 || day < 1 || day > monthLength(year, month)) refuse("bad-date", `${year}-${month}-${day} is not a date`);
|
|
216
|
+
Object.assign(this, { year, month, day });
|
|
217
|
+
}
|
|
218
|
+
get serial() {
|
|
219
|
+
return toDays(this.year, this.month, this.day);
|
|
220
|
+
}
|
|
221
|
+
get isEndOfMonth() {
|
|
222
|
+
return this.day === monthLength(this.year, this.month);
|
|
223
|
+
}
|
|
224
|
+
addDays(n) {
|
|
225
|
+
return new CalendarDate(...fromDays(this.serial + n));
|
|
226
|
+
}
|
|
227
|
+
/** n months later; a day past the end of the month becomes its last day, and with endOfMonth a month-end stays a month-end */
|
|
228
|
+
addMonths(n, { endOfMonth = false } = {}) {
|
|
229
|
+
const k = this.year * 12 + (this.month - 1) + n;
|
|
230
|
+
const [y, m] = [Math.floor(k / 12), (((k % 12) + 12) % 12) + 1];
|
|
231
|
+
const last = monthLength(y, m);
|
|
232
|
+
return new CalendarDate(y, m, endOfMonth && this.isEndOfMonth ? last : Math.min(this.day, last));
|
|
233
|
+
}
|
|
234
|
+
compareTo(o) {
|
|
235
|
+
return this.serial - date(o).serial;
|
|
236
|
+
}
|
|
237
|
+
equals(o) {
|
|
238
|
+
return this.compareTo(o) === 0;
|
|
239
|
+
}
|
|
240
|
+
toString() {
|
|
241
|
+
return `${String(this.year).padStart(4, "0")}-${String(this.month).padStart(2, "0")}-${String(this.day).padStart(2, "0")}`;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
/** A date from "2027-03-15", "2027-03" (the first of the month), [y, m, d] or a CalendarDate. */
|
|
245
|
+
export function date(x) {
|
|
246
|
+
if (x instanceof CalendarDate) return x;
|
|
247
|
+
if (Array.isArray(x)) return new CalendarDate(...x);
|
|
248
|
+
const m = typeof x === "string" && /^(\d{4})-(\d{1,2})(?:-(\d{1,2}))?$/.exec(x.trim());
|
|
249
|
+
if (!m) refuse("bad-date", `write a date as "2027-03-15", not ${String(x)}`);
|
|
250
|
+
return new CalendarDate(Number(m[1]), Number(m[2]), m[3] ? Number(m[3]) : 1);
|
|
251
|
+
}
|
|
252
|
+
export const daysBetween = (a, b) => date(b).serial - date(a).serial;
|
|
253
|
+
|
|
254
|
+
export const DAY_COUNTS = Object.freeze(["30/360", "30E/360", "actual/360", "actual/365", "actual/actual"]);
|
|
255
|
+
/**
|
|
256
|
+
* Days and the fraction of a year between two dates under a convention:
|
|
257
|
+
* "30/360" (US bond basis), "30E/360" (Eurobond), "actual/360",
|
|
258
|
+
* "actual/365" (fixed) or "actual/actual" (ISDA: each day counts 1/365 or
|
|
259
|
+
* 1/366 according to the year it falls in). { days, yearFraction }, exact.
|
|
260
|
+
*/
|
|
261
|
+
export function dayCount(from, to, convention = "actual/actual") {
|
|
262
|
+
const [a, b] = [date(from), date(to)];
|
|
263
|
+
const actual = b.serial - a.serial;
|
|
264
|
+
const thirty = (d1, d2) => 360 * (b.year - a.year) + 30 * (b.month - a.month) + (d2 - d1);
|
|
265
|
+
switch (convention) {
|
|
266
|
+
case "30/360": {
|
|
267
|
+
const d1 = a.day === 31 ? 30 : a.day;
|
|
268
|
+
const d2 = b.day === 31 && d1 === 30 ? 30 : b.day;
|
|
269
|
+
const days = thirty(d1, d2);
|
|
270
|
+
return { days, yearFraction: Q(days, 360) };
|
|
271
|
+
}
|
|
272
|
+
case "30E/360": {
|
|
273
|
+
const days = thirty(Math.min(a.day, 30), Math.min(b.day, 30));
|
|
274
|
+
return { days, yearFraction: Q(days, 360) };
|
|
275
|
+
}
|
|
276
|
+
case "actual/360":
|
|
277
|
+
return { days: actual, yearFraction: Q(actual, 360) };
|
|
278
|
+
case "actual/365":
|
|
279
|
+
return { days: actual, yearFraction: Q(actual, 365) };
|
|
280
|
+
case "actual/actual": {
|
|
281
|
+
if (actual < 0) {
|
|
282
|
+
const r = dayCount(b, a, convention);
|
|
283
|
+
return { days: actual, yearFraction: r.yearFraction.negate() };
|
|
284
|
+
}
|
|
285
|
+
let f = ZERO;
|
|
286
|
+
for (let y = a.year; y <= b.year; y++) {
|
|
287
|
+
const lo = Math.max(a.serial, toDays(y, 1, 1));
|
|
288
|
+
const hi = Math.min(b.serial, toDays(y + 1, 1, 1));
|
|
289
|
+
if (hi > lo) f = f.add(Q(hi - lo, isLeap(y) ? 366 : 365));
|
|
290
|
+
}
|
|
291
|
+
return { days: actual, yearFraction: f };
|
|
292
|
+
}
|
|
293
|
+
default:
|
|
294
|
+
refuse("bad-convention", `the day count is one of ${DAY_COUNTS.join(", ")}`);
|
|
295
|
+
}
|
|
296
|
+
}
|