@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/options.js
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
// Options: payoffs and strategies (exact, with their break-even prices),
|
|
2
|
+
// put–call parity, the binomial tree (exact for rational up, down and rate
|
|
3
|
+
// factors, European or American), and Black–Scholes values and
|
|
4
|
+
// sensitivities as certified enclosures, with the implied volatility found
|
|
5
|
+
// by certified bisection (the price increases with volatility).
|
|
6
|
+
import { Rational, RationalInterval } from "@ratmath/core";
|
|
7
|
+
import { enclose } from "@ratmath/analytic";
|
|
8
|
+
import { refuse, amount, ZERO, ONE, Q, round } from "./money.js";
|
|
9
|
+
|
|
10
|
+
const isIv = (x) => x instanceof RationalInterval;
|
|
11
|
+
const I = (x) => (isIv(x) ? x : new RationalInterval(amount(x), amount(x)));
|
|
12
|
+
const add = (a, b) => I(a).add(I(b));
|
|
13
|
+
const sub = (a, b) => I(a).subtract(I(b));
|
|
14
|
+
const mul = (a, b) => I(a).multiply(I(b));
|
|
15
|
+
const div = (a, b) => I(a).divide(I(b));
|
|
16
|
+
const tight = (iv) => (iv.low.equals(iv.high) ? iv.low : iv);
|
|
17
|
+
const max0 = (x) => (x.numerator < 0n ? ZERO : x);
|
|
18
|
+
|
|
19
|
+
// ---- payoffs ------------------------------------------------------------------
|
|
20
|
+
|
|
21
|
+
const LEG_TYPES = new Set(["call", "put", "stock", "bond"]);
|
|
22
|
+
/**
|
|
23
|
+
* A strategy: legs { type: "call" | "put" | "stock" | "bond", strike (for an
|
|
24
|
+
* option; the face for a bond), premium (what one unit cost; default 0),
|
|
25
|
+
* quantity (negative for a short position; default 1) }. Returns
|
|
26
|
+
* { payoff(S), profit(S), kinks, breakEvens, maxProfit, maxLoss } with every
|
|
27
|
+
* value exact; max values are null when unbounded.
|
|
28
|
+
*/
|
|
29
|
+
export function strategy(legs) {
|
|
30
|
+
const L = legs.map((l) => {
|
|
31
|
+
if (!LEG_TYPES.has(l.type)) refuse("bad-leg", `a leg is a call, put, stock or bond, not ${l.type}`);
|
|
32
|
+
return { type: l.type, strike: l.strike === undefined ? null : amount(l.strike), premium: amount(l.premium ?? 0), quantity: amount(l.quantity ?? 1) };
|
|
33
|
+
});
|
|
34
|
+
for (const l of L) if ((l.type === "call" || l.type === "put" || l.type === "bond") && l.strike === null) refuse("bad-leg", `a ${l.type} needs a strike`);
|
|
35
|
+
const one = (l, S) => (l.type === "call" ? max0(S.subtract(l.strike)) : l.type === "put" ? max0(l.strike.subtract(S)) : l.type === "stock" ? S : l.strike);
|
|
36
|
+
const payoff = (s) => {
|
|
37
|
+
const S = amount(s);
|
|
38
|
+
return L.reduce((acc, l) => acc.add(l.quantity.multiply(one(l, S))), ZERO);
|
|
39
|
+
};
|
|
40
|
+
const cost = L.reduce((acc, l) => acc.add(l.quantity.multiply(l.premium)), ZERO);
|
|
41
|
+
const profit = (s) => payoff(s).subtract(cost);
|
|
42
|
+
const kinks = [...new Set(L.filter((l) => l.type === "call" || l.type === "put").map((l) => l.strike.toString()))].map(amount).sort((a, b) => a.compareTo(b));
|
|
43
|
+
// profit is linear between kinks: find each zero exactly
|
|
44
|
+
const pts = [ZERO, ...kinks.filter((k) => k.numerator > 0n)];
|
|
45
|
+
const breakEvens = [];
|
|
46
|
+
const slopeAfter = (x) => profit(x.add(ONE)).subtract(profit(x));
|
|
47
|
+
for (let i = 0; i < pts.length; i++) {
|
|
48
|
+
const a = pts[i];
|
|
49
|
+
const pa = profit(a);
|
|
50
|
+
if (pa.numerator === 0n && !breakEvens.some((z) => z.equals(a))) breakEvens.push(a);
|
|
51
|
+
const b = pts[i + 1] ?? null;
|
|
52
|
+
const slope = b ? profit(b).subtract(pa).divide(b.subtract(a)) : slopeAfter(a);
|
|
53
|
+
if (slope.numerator === 0n) continue;
|
|
54
|
+
const z = a.subtract(pa.divide(slope));
|
|
55
|
+
if (z.compareTo(a) > 0 && (b === null || z.compareTo(b) < 0)) breakEvens.push(z);
|
|
56
|
+
}
|
|
57
|
+
const values = pts.map(profit);
|
|
58
|
+
const lastSlope = slopeAfter(pts[pts.length - 1]);
|
|
59
|
+
const maxProfit = lastSlope.numerator > 0n ? null : values.reduce((m, v) => (v.compareTo(m) > 0 ? v : m));
|
|
60
|
+
const minV = values.reduce((m, v) => (v.compareTo(m) < 0 ? v : m));
|
|
61
|
+
const maxLoss = lastSlope.numerator < 0n ? null : minV.numerator < 0n ? minV.negate() : ZERO;
|
|
62
|
+
return { legs: L, cost, payoff, profit, kinks, breakEvens: breakEvens.sort((a, b) => a.compareTo(b)), maxProfit, maxLoss };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ---- discounting ----------------------------------------------------------------
|
|
66
|
+
|
|
67
|
+
/** the discount factor over `time` years: (1 + r)^−t for whole t (exact), e^{−rt} for continuous (certified) */
|
|
68
|
+
function discount(rate, time, compounding, bits) {
|
|
69
|
+
const r = amount(rate);
|
|
70
|
+
const t = amount(time);
|
|
71
|
+
if (compounding === "continuous") return tight(enclose.exp(I(r.multiply(t).negate()), bits));
|
|
72
|
+
if (compounding !== "annual") refuse("bad-argument", 'compounding is "continuous" or "annual"');
|
|
73
|
+
if (t.denominator !== 1n) refuse("bad-argument", "annual compounding here takes a whole number of years");
|
|
74
|
+
return ONE.divide(ONE.add(r).pow(t.numerator));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Put–call parity C − P = S − K·DF for European options on a stock without
|
|
79
|
+
* dividends. Give all but one of call, put, spot and strike to get the
|
|
80
|
+
* missing one; give all four to get the `gap` (zero when parity holds, so a
|
|
81
|
+
* nonzero gap is an arbitrage).
|
|
82
|
+
*/
|
|
83
|
+
export function parity({ call, put, spot, strike, rate, time, compounding = "continuous", bits = 80 }) {
|
|
84
|
+
const df = discount(rate, time, compounding, bits);
|
|
85
|
+
const pv = mul(amount(strike ?? 0), df);
|
|
86
|
+
const missing = ["call", "put", "spot", "strike"].filter((k) => ({ call, put, spot, strike })[k] === undefined);
|
|
87
|
+
if (missing.length > 1) refuse("bad-argument", "give at least three of call, put, spot and strike");
|
|
88
|
+
// a price may be an enclosure, such as the call blackScholes returns
|
|
89
|
+
const [C, P, S] = [call, put, spot].map((x) => (x === undefined ? null : isIv(x) ? tight(x) : amount(x)));
|
|
90
|
+
if (missing[0] === "call") return { call: tight(add(P, sub(S, pv))) };
|
|
91
|
+
if (missing[0] === "put") return { put: tight(sub(C, sub(S, pv))) };
|
|
92
|
+
if (missing[0] === "spot") return { spot: tight(add(sub(C, P), pv)) };
|
|
93
|
+
if (missing[0] === "strike") return { strike: tight(div(sub(S, sub(C, P)), df)) };
|
|
94
|
+
const gap = tight(sub(sub(C, P), sub(S, pv)));
|
|
95
|
+
const holds = isIv(gap) ? gap.containsZero() ? null : false : gap.numerator === 0n;
|
|
96
|
+
return { gap, holds };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ---- binomial tree ----------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Price an option on a recombining binomial tree, exactly.
|
|
103
|
+
* { spot, strike, steps, type: "call" | "put", style: "european" | "american",
|
|
104
|
+
* up, down, growth }: each step the price is multiplied by `up` or `down`
|
|
105
|
+
* and money grows by `growth` (1 + the rate per step). The risk-neutral
|
|
106
|
+
* probability is p = (growth − down)/(up − down), which needs
|
|
107
|
+
* down < growth < up (otherwise the tree has an arbitrage).
|
|
108
|
+
* Or give { volatility, time, rate } for the Cox–Ross–Rubinstein tree:
|
|
109
|
+
* up = e^{σ√Δt}, down = 1/up, growth = e^{rΔt}, rounded to `places` decimal
|
|
110
|
+
* places (default 8) and then used exactly; `rounded: true` says so.
|
|
111
|
+
* The exact tree's fractions grow with each step (100 steps take about a
|
|
112
|
+
* second, 200 about twenty); `float: true` runs the same induction in
|
|
113
|
+
* floating point for a quick preview, marked `approximate`.
|
|
114
|
+
*/
|
|
115
|
+
export function binomialTree({ spot, strike, steps, type = "call", style = "european", up, down, growth, volatility, time, rate, places = 8, keepTree = false, float = false }) {
|
|
116
|
+
const S = amount(spot);
|
|
117
|
+
const K = amount(strike);
|
|
118
|
+
if (!Number.isInteger(steps) || steps < 1 || steps > 100000) refuse("bad-argument", "steps is a whole number from 1 to 100000");
|
|
119
|
+
if (!float && steps > 2000) refuse("too-large", "an exact tree is limited to 2000 steps (its fractions grow with every step); use float: true for a quick preview");
|
|
120
|
+
if (type !== "call" && type !== "put") refuse("bad-argument", 'type is "call" or "put"');
|
|
121
|
+
if (style !== "european" && style !== "american") refuse("bad-argument", 'style is "european" or "american"');
|
|
122
|
+
let rounded = false;
|
|
123
|
+
if (up === undefined) {
|
|
124
|
+
if (volatility === undefined || time === undefined || rate === undefined) refuse("bad-argument", "give up, down and growth, or volatility, time and rate");
|
|
125
|
+
const dt = amount(time).divide(Q(steps));
|
|
126
|
+
const sig = amount(volatility);
|
|
127
|
+
const u = enclose.exp(enclose.sqrt(I(sig.multiply(sig).multiply(dt)), 96), 96);
|
|
128
|
+
up = round(u.low, { places });
|
|
129
|
+
down = ONE.divide(up);
|
|
130
|
+
growth = round(enclose.exp(I(amount(rate).multiply(dt)), 96).low, { places });
|
|
131
|
+
rounded = true;
|
|
132
|
+
}
|
|
133
|
+
const [u, d, g] = [amount(up), amount(down ?? ONE.divide(amount(up))), amount(growth)];
|
|
134
|
+
if (!(d.compareTo(g) < 0 && g.compareTo(u) < 0)) refuse("arbitrage", `the tree needs down < growth < up; here ${d}, ${g}, ${u}`);
|
|
135
|
+
const p = g.subtract(d).divide(u.subtract(d));
|
|
136
|
+
if (float) return floatTree({ S: S.toNumber(), K: K.toNumber(), u: u.toNumber(), d: d.toNumber(), g: g.toNumber(), p: p.toNumber(), steps, type, style, rounded });
|
|
137
|
+
const q = ONE.subtract(p);
|
|
138
|
+
const pay = (s) => (type === "call" ? max0(s.subtract(K)) : max0(K.subtract(s)));
|
|
139
|
+
// price after j ups and i − j downs; powers are computed once
|
|
140
|
+
const upPow = [ONE];
|
|
141
|
+
const downPow = [ONE];
|
|
142
|
+
for (let k = 1; k <= steps; k++) {
|
|
143
|
+
upPow.push(upPow[k - 1].multiply(u));
|
|
144
|
+
downPow.push(downPow[k - 1].multiply(d));
|
|
145
|
+
}
|
|
146
|
+
const priceAt = (i, j) => S.multiply(upPow[j]).multiply(downPow[i - j]);
|
|
147
|
+
let V = Array.from({ length: steps + 1 }, (_, j) => pay(priceAt(steps, j)));
|
|
148
|
+
const tree = keepTree ? [V] : null;
|
|
149
|
+
const exercise = [];
|
|
150
|
+
let delta = null;
|
|
151
|
+
for (let i = steps - 1; i >= 0; i--) {
|
|
152
|
+
const next = new Array(i + 1);
|
|
153
|
+
for (let j = 0; j <= i; j++) {
|
|
154
|
+
let v = p.multiply(V[j + 1]).add(q.multiply(V[j])).divide(g);
|
|
155
|
+
if (style === "american") {
|
|
156
|
+
const now = pay(priceAt(i, j));
|
|
157
|
+
if (now.compareTo(v) > 0) {
|
|
158
|
+
v = now;
|
|
159
|
+
exercise.push({ step: i, ups: j, price: priceAt(i, j) });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
next[j] = v;
|
|
163
|
+
}
|
|
164
|
+
if (i === 0) delta = V[1].subtract(V[0]).divide(priceAt(1, 1).subtract(priceAt(1, 0)));
|
|
165
|
+
V = next;
|
|
166
|
+
if (keepTree) tree.unshift(V);
|
|
167
|
+
}
|
|
168
|
+
return { price: V[0], probability: p, up: u, down: d, growth: g, delta, rounded, earlyExercise: style === "american" ? exercise : null, tree };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** the same backward induction in floating point: fast, and labelled approximate */
|
|
172
|
+
function floatTree({ S, K, u, d, g, p, steps, type, style, rounded }) {
|
|
173
|
+
const pay = (x) => Math.max(0, type === "call" ? x - K : K - x);
|
|
174
|
+
let V = Float64Array.from({ length: steps + 1 }, (_, j) => pay(S * u ** j * d ** (steps - j)));
|
|
175
|
+
let delta = null;
|
|
176
|
+
for (let i = steps - 1; i >= 0; i--) {
|
|
177
|
+
if (i === 0) delta = (V[1] - V[0]) / (S * u - S * d);
|
|
178
|
+
for (let j = 0; j <= i; j++) {
|
|
179
|
+
let v = (p * V[j + 1] + (1 - p) * V[j]) / g;
|
|
180
|
+
if (style === "american") v = Math.max(v, pay(S * u ** j * d ** (i - j)));
|
|
181
|
+
V[j] = v;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return { price: V[0], probability: p, up: u, down: d, growth: g, delta, rounded, approximate: true, earlyExercise: null, tree: null };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// ---- Black–Scholes ----------------------------------------------------------------
|
|
188
|
+
|
|
189
|
+
const KEPT = new Map();
|
|
190
|
+
const constant = (name, bits, make) => {
|
|
191
|
+
const k = `${name}|${bits}`;
|
|
192
|
+
if (!KEPT.has(k)) KEPT.set(k, make());
|
|
193
|
+
return KEPT.get(k);
|
|
194
|
+
};
|
|
195
|
+
const sqrt2 = (bits) => constant("sqrt2", bits, () => enclose.sqrt(I(Q(2)), bits));
|
|
196
|
+
const sqrt2pi = (bits) => constant("sqrt2pi", bits, () => enclose.sqrt(mul(Q(8), enclose.atan(I(ONE), bits)), bits));
|
|
197
|
+
/** the standard normal distribution function, enclosed: (1 + erf(x/√2))/2 */
|
|
198
|
+
export const normalCdf = (x, bits = 80) => div(add(ONE, enclose.erf(div(I(x), sqrt2(bits)), bits)), Q(2));
|
|
199
|
+
/** the standard normal density, enclosed */
|
|
200
|
+
export const normalPdf = (x, bits = 80) => {
|
|
201
|
+
const v = I(x);
|
|
202
|
+
// x² over an interval that may contain zero
|
|
203
|
+
const hi = v.low.abs().compareTo(v.high.abs()) > 0 ? v.low.abs() : v.high.abs();
|
|
204
|
+
const lo = v.containsZero() ? ZERO : v.low.abs().compareTo(v.high.abs()) < 0 ? v.low.abs() : v.high.abs();
|
|
205
|
+
const sq = new RationalInterval(lo.multiply(lo), hi.multiply(hi));
|
|
206
|
+
return div(enclose.exp(div(sq, Q(-2)), bits), sqrt2pi(bits));
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* European option values under Black–Scholes with continuous compounding:
|
|
211
|
+
* { spot, strike, rate, volatility, time, dividendYield = 0 }. Every output
|
|
212
|
+
* is an enclosure proven to contain the true value (or an exact rational
|
|
213
|
+
* when it happens to be one): call, put, d1, d2 and the sensitivities
|
|
214
|
+
* delta, gamma, vega, theta (per year) and rho for each.
|
|
215
|
+
*/
|
|
216
|
+
export function blackScholes({ spot, strike, rate, volatility, time, dividendYield = 0, bits = 80 }) {
|
|
217
|
+
const [S, K, r, sig, T, y] = [spot, strike, rate, volatility, time, dividendYield].map(amount);
|
|
218
|
+
if (S.numerator <= 0n || K.numerator <= 0n) refuse("domain", "spot and strike are positive");
|
|
219
|
+
if (sig.numerator <= 0n || T.numerator <= 0n) refuse("domain", "volatility and time are positive");
|
|
220
|
+
const b = bits + 16;
|
|
221
|
+
const sqT = enclose.sqrt(I(T), b);
|
|
222
|
+
const sd = mul(sig, sqT);
|
|
223
|
+
const lnSK = enclose.log(I(S.divide(K)), b);
|
|
224
|
+
const d1 = div(add(lnSK, r.subtract(y).add(sig.multiply(sig).divide(Q(2))).multiply(T)), sd);
|
|
225
|
+
const d2 = sub(d1, sd);
|
|
226
|
+
const Nd1 = normalCdf(d1, b);
|
|
227
|
+
const Nd2 = normalCdf(d2, b);
|
|
228
|
+
const Nm1 = sub(ONE, Nd1);
|
|
229
|
+
const Nm2 = sub(ONE, Nd2);
|
|
230
|
+
const dfr = enclose.exp(I(r.multiply(T).negate()), b);
|
|
231
|
+
const dfy = y.numerator === 0n ? I(ONE) : enclose.exp(I(y.multiply(T).negate()), b);
|
|
232
|
+
const SY = mul(S, dfy);
|
|
233
|
+
const KR = mul(K, dfr);
|
|
234
|
+
const pdf = normalPdf(d1, b);
|
|
235
|
+
const gamma = div(mul(dfy, pdf), mul(S, sd));
|
|
236
|
+
const vega = mul(mul(SY, pdf), sqT);
|
|
237
|
+
const common = div(mul(mul(SY, pdf), sig), mul(Q(2), sqT)).negate();
|
|
238
|
+
const out = {
|
|
239
|
+
call: sub(mul(SY, Nd1), mul(KR, Nd2)),
|
|
240
|
+
put: sub(mul(KR, Nm2), mul(SY, Nm1)),
|
|
241
|
+
d1,
|
|
242
|
+
d2,
|
|
243
|
+
delta: { call: mul(dfy, Nd1), put: mul(dfy, Nd1).subtract(dfy) },
|
|
244
|
+
gamma,
|
|
245
|
+
vega,
|
|
246
|
+
theta: {
|
|
247
|
+
call: add(sub(common, mul(mul(r, KR), Nd2)), mul(mul(y, SY), Nd1)),
|
|
248
|
+
put: sub(add(common, mul(mul(r, KR), Nm2)), mul(mul(y, SY), Nm1)),
|
|
249
|
+
},
|
|
250
|
+
rho: { call: mul(mul(K, T), mul(dfr, Nd2)), put: mul(mul(K, T), mul(dfr, Nm2)).negate() },
|
|
251
|
+
};
|
|
252
|
+
return out;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* The volatility at which Black–Scholes gives a stated price, enclosed to
|
|
257
|
+
* `digits` digits. The price rises with volatility, so certified bisection
|
|
258
|
+
* keeps an interval [lo, hi] with BS(lo) < price < BS(hi), proven at each
|
|
259
|
+
* step. Refused when the price lies outside what any volatility can give.
|
|
260
|
+
*/
|
|
261
|
+
export function impliedVolatility({ price, type = "call", spot, strike, rate, time, dividendYield = 0, digits = 8, bits = 64 }) {
|
|
262
|
+
const P = amount(price);
|
|
263
|
+
const at = (s) => blackScholes({ spot, strike, rate, time, dividendYield, volatility: s, bits })[type];
|
|
264
|
+
let lo = Q(1, 10000);
|
|
265
|
+
let hi = Q(5);
|
|
266
|
+
if (at(lo).high.compareTo(P) >= 0) refuse("out-of-range", `the price ${P} is at or below what a volatility of 0.01% gives`);
|
|
267
|
+
for (let k = 0; at(hi).low.compareTo(P) <= 0; k++) {
|
|
268
|
+
if (k > 4) refuse("out-of-range", `the price ${P} is above what any volatility gives`);
|
|
269
|
+
hi = hi.multiply(Q(2));
|
|
270
|
+
}
|
|
271
|
+
const tol = new Rational(1n, 10n ** BigInt(digits));
|
|
272
|
+
while (hi.subtract(lo).compareTo(tol) > 0) {
|
|
273
|
+
const mid = lo.add(hi).divide(Q(2));
|
|
274
|
+
const v = at(mid);
|
|
275
|
+
if (v.high.compareTo(P) < 0) lo = mid;
|
|
276
|
+
else if (v.low.compareTo(P) > 0) hi = mid;
|
|
277
|
+
else return refuse("precision", `the value at ${mid} could not be separated from the price at ${bits} bits; raise bits`);
|
|
278
|
+
}
|
|
279
|
+
return new RationalInterval(lo, hi);
|
|
280
|
+
}
|
package/src/plan.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// What this package is still planned to contain, phase by phase, from the
|
|
2
|
+
// RatMath library roadmap. Phases 1 to 6 are built; a phase is removed from
|
|
3
|
+
// this list when it ships, and the list goes away when it is empty.
|
|
4
|
+
|
|
5
|
+
export const plan = Object.freeze([
|
|
6
|
+
{
|
|
7
|
+
"phase": 7,
|
|
8
|
+
"contents": "Pictures",
|
|
9
|
+
"estimate": "500 in graphics"
|
|
10
|
+
}
|
|
11
|
+
].map(Object.freeze));
|
package/src/portfolio.js
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
// Portfolios: returns from prices, expected return and risk of a mix, the
|
|
2
|
+
// efficient frontier and the capital asset pricing model. With rational
|
|
3
|
+
// data every answer here is exact except a standard deviation or a Sharpe
|
|
4
|
+
// ratio, which are square roots and come back as certified enclosures.
|
|
5
|
+
//
|
|
6
|
+
// The frontier with short sales allowed has a closed form (Merton 1972).
|
|
7
|
+
// Without short sales it is a small quadratic program; it is solved exactly
|
|
8
|
+
// by trying each set of assets that may be held and keeping the one whose
|
|
9
|
+
// optimality (Karush–Kuhn–Tucker) conditions hold, which for a convex
|
|
10
|
+
// problem proves the answer is the minimum.
|
|
11
|
+
import { Rational, RationalInterval } from "@ratmath/core";
|
|
12
|
+
import { mean as meanOf, covariance as covOf, variance as varOf } from "@ratmath/stats";
|
|
13
|
+
import { enclose } from "@ratmath/analytic";
|
|
14
|
+
import { refuse, amount, ZERO, ONE, Q } from "./money.js";
|
|
15
|
+
|
|
16
|
+
const point = (q) => new RationalInterval(q, q);
|
|
17
|
+
const sqrtQ = (q, bits = 80) => {
|
|
18
|
+
if (q.numerator < 0n) refuse("domain", "a negative variance");
|
|
19
|
+
const r = enclose.sqrt(point(q), bits);
|
|
20
|
+
return r.low.equals(r.high) ? r.low : r;
|
|
21
|
+
};
|
|
22
|
+
const dot = (a, b) => a.reduce((s, x, i) => s.add(x.multiply(b[i])), ZERO);
|
|
23
|
+
const matVec = (M, v) => M.map((row) => dot(row, v));
|
|
24
|
+
|
|
25
|
+
/** Solve M x = b exactly (Gauss–Jordan over the rationals); null when M is singular. */
|
|
26
|
+
export function solveExact(M, b) {
|
|
27
|
+
const n = M.length;
|
|
28
|
+
const A = M.map((row, i) => [...row, b[i]]);
|
|
29
|
+
for (let c = 0; c < n; c++) {
|
|
30
|
+
const p = A.findIndex((row, r) => r >= c && row[c].numerator !== 0n);
|
|
31
|
+
if (p < 0) return null;
|
|
32
|
+
[A[c], A[p]] = [A[p], A[c]];
|
|
33
|
+
const inv = ONE.divide(A[c][c]);
|
|
34
|
+
for (let j = c; j <= n; j++) A[c][j] = A[c][j].multiply(inv);
|
|
35
|
+
for (let r = 0; r < n; r++) {
|
|
36
|
+
if (r === c || A[r][c].numerator === 0n) continue;
|
|
37
|
+
const f = A[r][c];
|
|
38
|
+
for (let j = c; j <= n; j++) A[r][j] = A[r][j].subtract(f.multiply(A[c][j]));
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return A.map((row) => row[n]);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Simple returns p[k+1]/p[k] − 1 from a list of prices; exact. */
|
|
45
|
+
export function returnsFrom(prices) {
|
|
46
|
+
const p = prices.map(amount);
|
|
47
|
+
if (p.length < 2) refuse("bad-data", "returns need at least two prices");
|
|
48
|
+
if (p.some((x) => x.numerator <= 0n)) refuse("bad-data", "prices are positive");
|
|
49
|
+
return p.slice(1).map((x, k) => x.divide(p[k]).subtract(ONE));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const matrixOf = (cov, n) => {
|
|
53
|
+
const S = cov.map((row) => row.map(amount));
|
|
54
|
+
if (S.length !== n || S.some((row) => row.length !== n)) refuse("bad-data", `the covariance matrix is ${n} by ${n}`);
|
|
55
|
+
for (let i = 0; i < n; i++) for (let j = 0; j < i; j++) if (!S[i][j].equals(S[j][i])) refuse("bad-data", "the covariance matrix is symmetric");
|
|
56
|
+
return S;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export class Portfolio {
|
|
60
|
+
/**
|
|
61
|
+
* { names, means, covariance } or { names, returns: [[asset 1's returns], …] }
|
|
62
|
+
* (sample means and sample covariances, exact). `riskFree` is optional.
|
|
63
|
+
*/
|
|
64
|
+
constructor({ names, means, covariance, returns, riskFree = null }) {
|
|
65
|
+
if (returns) {
|
|
66
|
+
const R = returns.map((r) => r.map(amount));
|
|
67
|
+
if (R.length < 1 || R.some((r) => r.length !== R[0].length || r.length < 2)) refuse("bad-data", "each asset has the same number of returns, at least two");
|
|
68
|
+
means = R.map((r) => meanOf(r));
|
|
69
|
+
covariance = R.map((a) => R.map((b) => covOf(a, b)));
|
|
70
|
+
this.returns = R;
|
|
71
|
+
}
|
|
72
|
+
if (!means || !covariance) refuse("bad-data", "a portfolio needs means and a covariance matrix, or returns");
|
|
73
|
+
this.means = means.map(amount);
|
|
74
|
+
this.n = this.means.length;
|
|
75
|
+
this.covariance = matrixOf(covariance, this.n);
|
|
76
|
+
this.names = names ?? this.means.map((_, i) => `asset ${i + 1}`);
|
|
77
|
+
this.riskFree = riskFree === null ? null : amount(riskFree);
|
|
78
|
+
this._inv = null;
|
|
79
|
+
}
|
|
80
|
+
_weights(w) {
|
|
81
|
+
const x = w.map(amount);
|
|
82
|
+
if (x.length !== this.n) refuse("bad-weights", `give ${this.n} weights`);
|
|
83
|
+
return x;
|
|
84
|
+
}
|
|
85
|
+
/** Expected return wᵀμ, exact. */
|
|
86
|
+
expectedReturn(w) {
|
|
87
|
+
return dot(this._weights(w), this.means);
|
|
88
|
+
}
|
|
89
|
+
/** Variance wᵀΣw, exact. */
|
|
90
|
+
variance(w) {
|
|
91
|
+
const x = this._weights(w);
|
|
92
|
+
return dot(x, matVec(this.covariance, x));
|
|
93
|
+
}
|
|
94
|
+
/** Standard deviation, certified. */
|
|
95
|
+
risk(w, { bits = 80 } = {}) {
|
|
96
|
+
return sqrtQ(this.variance(w), bits);
|
|
97
|
+
}
|
|
98
|
+
/** Σ⁻¹1 and Σ⁻¹μ, and the frontier constants A = 1ᵀΣ⁻¹1, B = 1ᵀΣ⁻¹μ, C = μᵀΣ⁻¹μ, D = AC − B². */
|
|
99
|
+
constants() {
|
|
100
|
+
if (this._inv) return this._inv;
|
|
101
|
+
const ones = this.means.map(() => ONE);
|
|
102
|
+
const a = solveExact(this.covariance, ones);
|
|
103
|
+
const b = solveExact(this.covariance, this.means);
|
|
104
|
+
if (!a || !b) refuse("singular", "the covariance matrix is singular: some mix of the assets has no risk");
|
|
105
|
+
const A = dot(ones, a);
|
|
106
|
+
const B = dot(ones, b);
|
|
107
|
+
const C = dot(this.means, b);
|
|
108
|
+
const D = A.multiply(C).subtract(B.multiply(B));
|
|
109
|
+
this._inv = { invOnes: a, invMeans: b, A, B, C, D };
|
|
110
|
+
return this._inv;
|
|
111
|
+
}
|
|
112
|
+
/** The portfolio of least variance: w = Σ⁻¹1 / A. */
|
|
113
|
+
minimumVariance() {
|
|
114
|
+
const { invOnes, A, B } = this.constants();
|
|
115
|
+
const w = invOnes.map((x) => x.divide(A));
|
|
116
|
+
return this._report(w, { expectedReturn: B.divide(A), variance: ONE.divide(A) });
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* The least-variance portfolio with expected return `target`, short sales
|
|
120
|
+
* allowed: w = Σ⁻¹(λ1 + γμ) with λ = (C − B·m)/D, γ = (A·m − B)/D, and
|
|
121
|
+
* variance (A·m² − 2B·m + C)/D. Exact.
|
|
122
|
+
*/
|
|
123
|
+
frontier(target) {
|
|
124
|
+
const m = amount(target);
|
|
125
|
+
const { invOnes, invMeans, A, B, C, D } = this.constants();
|
|
126
|
+
if (D.numerator === 0n) refuse("degenerate", "every asset has the same expected return: the frontier is a single point");
|
|
127
|
+
const lam = C.subtract(B.multiply(m)).divide(D);
|
|
128
|
+
const gam = A.multiply(m).subtract(B).divide(D);
|
|
129
|
+
const w = invOnes.map((x, i) => lam.multiply(x).add(gam.multiply(invMeans[i])));
|
|
130
|
+
const v = A.multiply(m).multiply(m).subtract(Q(2).multiply(B).multiply(m)).add(C).divide(D);
|
|
131
|
+
return this._report(w, { expectedReturn: m, variance: v });
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* The same with no short sales (every weight ≥ 0), for up to 12 assets.
|
|
135
|
+
* Each support set S is tried: the equality-constrained problem on S is
|
|
136
|
+
* solved exactly, and the answer is kept when its weights are ≥ 0 and the
|
|
137
|
+
* multipliers say no asset left out would lower the variance. Those are the
|
|
138
|
+
* KKT conditions of a convex problem, so the answer is the minimum.
|
|
139
|
+
*/
|
|
140
|
+
frontierLongOnly(target) {
|
|
141
|
+
const m = amount(target);
|
|
142
|
+
const n = this.n;
|
|
143
|
+
if (n > 12) refuse("too-large", "the long-only frontier tries every set of assets; 12 assets at most");
|
|
144
|
+
const lo = this.means.reduce((a, b) => (b.compareTo(a) < 0 ? b : a));
|
|
145
|
+
const hi = this.means.reduce((a, b) => (b.compareTo(a) > 0 ? b : a));
|
|
146
|
+
if (m.compareTo(lo) < 0 || m.compareTo(hi) > 0) refuse("infeasible", `with no short sales the expected return lies between ${lo} and ${hi}`);
|
|
147
|
+
const S2 = this.covariance.map((row) => row.map((x) => x.multiply(Q(2))));
|
|
148
|
+
let best = null;
|
|
149
|
+
for (let mask = 1; mask < 1 << n; mask++) {
|
|
150
|
+
const idx = [];
|
|
151
|
+
for (let i = 0; i < n; i++) if (mask & (1 << i)) idx.push(i);
|
|
152
|
+
// [2Σ_SS −1 −μ_S] [w] [0]
|
|
153
|
+
// [1ᵀ 0 0 ] [λ] = [1]
|
|
154
|
+
// [μ_Sᵀ 0 0 ] [γ] [m]
|
|
155
|
+
const k = idx.length;
|
|
156
|
+
const M = [];
|
|
157
|
+
for (const i of idx) M.push([...idx.map((j) => S2[i][j]), ONE.negate(), this.means[i].negate()]);
|
|
158
|
+
M.push([...idx.map(() => ONE), ZERO, ZERO]);
|
|
159
|
+
M.push([...idx.map((j) => this.means[j]), ZERO, ZERO]);
|
|
160
|
+
const rhs = [...idx.map(() => ZERO), ONE, m];
|
|
161
|
+
let sol = solveExact(M, rhs);
|
|
162
|
+
let gammaFree = false;
|
|
163
|
+
if (!sol) {
|
|
164
|
+
// the return constraint may be implied (all means in S equal); drop γ
|
|
165
|
+
const M2 = M.slice(0, k + 1).map((row) => row.slice(0, k + 1));
|
|
166
|
+
if (!idx.every((j) => this.means[j].equals(m))) continue;
|
|
167
|
+
const s2 = solveExact(M2, rhs.slice(0, k + 1));
|
|
168
|
+
if (!s2) continue;
|
|
169
|
+
sol = [...s2, ZERO];
|
|
170
|
+
gammaFree = true;
|
|
171
|
+
}
|
|
172
|
+
const wS = sol.slice(0, k);
|
|
173
|
+
if (wS.some((x) => x.numerator < 0n)) continue;
|
|
174
|
+
const [lam, gam] = [sol[k], sol[k + 1]];
|
|
175
|
+
const w = new Array(n).fill(ZERO);
|
|
176
|
+
idx.forEach((j, t) => (w[j] = wS[t]));
|
|
177
|
+
// stationarity for the assets left out: 2(Σw)_j − λ − γμ_j ≥ 0
|
|
178
|
+
const g = matVec(S2, w);
|
|
179
|
+
const ok = gammaFree ? null : idx.length === n || g.every((x, j) => mask & (1 << j) || x.subtract(lam).subtract(gam.multiply(this.means[j])).numerator >= 0n);
|
|
180
|
+
if (ok === false) continue;
|
|
181
|
+
const v = this.variance(w);
|
|
182
|
+
if (ok === true) return this._report(w, { expectedReturn: m, variance: v, support: idx.filter((j) => w[j].numerator !== 0n).map((j) => this.names[j]), certificate: { lambda: lam, gamma: gam } });
|
|
183
|
+
if (!best || v.compareTo(best.v) < 0) best = { w, v, idx };
|
|
184
|
+
}
|
|
185
|
+
if (best) return this._report(best.w, { expectedReturn: m, variance: best.v, support: best.idx.filter((j) => best.w[j].numerator !== 0n).map((j) => this.names[j]), certificate: null });
|
|
186
|
+
refuse("infeasible", "no long-only portfolio has that expected return");
|
|
187
|
+
}
|
|
188
|
+
/** The tangency portfolio for a risk-free rate: w ∝ Σ⁻¹(μ − r·1), and its Sharpe ratio (certified). */
|
|
189
|
+
tangency(riskFree = this.riskFree) {
|
|
190
|
+
if (riskFree === null) refuse("bad-argument", "the tangency portfolio needs a risk-free rate");
|
|
191
|
+
const r = amount(riskFree);
|
|
192
|
+
const excess = this.means.map((x) => x.subtract(r));
|
|
193
|
+
const z = solveExact(this.covariance, excess);
|
|
194
|
+
if (!z) refuse("singular", "the covariance matrix is singular");
|
|
195
|
+
const s = z.reduce((a, b) => a.add(b), ZERO);
|
|
196
|
+
if (s.numerator === 0n) refuse("degenerate", "no tangency portfolio: the risk-free rate equals the minimum-variance portfolio's return");
|
|
197
|
+
const w = z.map((x) => x.divide(s));
|
|
198
|
+
const sharpe2 = dot(excess, z);
|
|
199
|
+
return this._report(w, { sharpeSquared: sharpe2, sharpe: sqrtQ(sharpe2), riskFree: r });
|
|
200
|
+
}
|
|
201
|
+
_report(w, extra) {
|
|
202
|
+
const out = { weights: Object.fromEntries(this.names.map((nm, i) => [nm, w[i]])), w, expectedReturn: this.expectedReturn(w), variance: this.variance(w), ...extra };
|
|
203
|
+
out.risk = sqrtQ(out.variance);
|
|
204
|
+
return out;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
export const portfolio = (spec) => new Portfolio(spec);
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* The capital asset pricing model from returns: β = cov(asset, market) /
|
|
211
|
+
* var(market), α = mean(asset) − (r + β·(mean(market) − r)), and the
|
|
212
|
+
* required return r + β·(E[market] − r). Exact.
|
|
213
|
+
*/
|
|
214
|
+
export function capm({ asset, market, riskFree = 0, marketReturn = null }) {
|
|
215
|
+
const a = asset.map(amount);
|
|
216
|
+
const mk = market.map(amount);
|
|
217
|
+
if (a.length !== mk.length || a.length < 2) refuse("bad-data", "asset and market returns are paired, at least two of each");
|
|
218
|
+
const r = amount(riskFree);
|
|
219
|
+
const vm = varOf(mk);
|
|
220
|
+
if (vm.numerator === 0n) refuse("bad-data", "the market's returns do not vary");
|
|
221
|
+
const beta = covOf(a, mk).divide(vm);
|
|
222
|
+
const em = marketReturn === null ? meanOf(mk) : amount(marketReturn);
|
|
223
|
+
const required = r.add(beta.multiply(em.subtract(r)));
|
|
224
|
+
const alpha = meanOf(a).subtract(r.add(beta.multiply(meanOf(mk).subtract(r))));
|
|
225
|
+
return { beta, alpha, required, marketPremium: em.subtract(r), riskFree: r };
|
|
226
|
+
}
|