@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/index.d.ts
ADDED
|
@@ -0,0 +1,590 @@
|
|
|
1
|
+
// Type declarations for @ratmath/finance.
|
|
2
|
+
import type { Rational, RationalInterval } from "@ratmath/core";
|
|
3
|
+
|
|
4
|
+
export interface PlannedPhase {
|
|
5
|
+
phase: number;
|
|
6
|
+
contents: string;
|
|
7
|
+
/** Rough size in source lines, as text. */
|
|
8
|
+
estimate: string;
|
|
9
|
+
}
|
|
10
|
+
/** The phases still to come. */
|
|
11
|
+
export const plan: readonly PlannedPhase[];
|
|
12
|
+
|
|
13
|
+
export class FinanceError extends Error {
|
|
14
|
+
code: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** An exact amount or rate: a whole number, a bigint, a Rational, or a string such as "1234.56", "$1,234.56", "7/8" or "4.5%". A JavaScript number that is not whole is refused. */
|
|
18
|
+
export type Amount = Rational | bigint | number | string;
|
|
19
|
+
/** Exact when it can be, otherwise an interval proven to contain the value. */
|
|
20
|
+
export type Certified = Rational | RationalInterval;
|
|
21
|
+
/** Finance's names plus every Core rounding mode name, or a Core rounder or your own function returning floor or ceil. */
|
|
22
|
+
export type RoundingMode =
|
|
23
|
+
| "half-even" | "half-up" | "half-down" | "half-odd" | "half-ceil" | "half-floor"
|
|
24
|
+
| "up" | "down" | "floor" | "ceil" | "toward-zero" | "away-from-zero"
|
|
25
|
+
| ((info: { value: Rational; floor: any; ceil: any; fraction: Rational }) => any);
|
|
26
|
+
export interface RoundingRule {
|
|
27
|
+
places?: number;
|
|
28
|
+
mode?: RoundingMode;
|
|
29
|
+
}
|
|
30
|
+
/** A rule, a number of places, a mode, or false / "none" for no rounding. */
|
|
31
|
+
export type Rounding = RoundingRule | number | RoundingMode | boolean | "none" | null;
|
|
32
|
+
export interface Digits {
|
|
33
|
+
/** How many digits an interval result should be good to (default 12). */
|
|
34
|
+
digits?: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// ---- money, rounding, dates ----------------------------------------------------
|
|
38
|
+
|
|
39
|
+
export function amount(x: Amount): Rational;
|
|
40
|
+
export function rate(x: Amount): Rational;
|
|
41
|
+
/** The mode money rounds by when none is named: "half-even" (banker's rounding). */
|
|
42
|
+
export const MONEY_ROUNDING: "half-even";
|
|
43
|
+
/** A Core rounder for a mode (default MONEY_ROUNDING); "up" and "down" mean away from and towards zero. */
|
|
44
|
+
export function moneyRounder(mode?: RoundingMode): ((x: any, places?: number) => any) & { mode: unknown };
|
|
45
|
+
export function round(x: Amount, rule?: RoundingRule): Rational;
|
|
46
|
+
export function format(x: Amount, options?: RoundingRule & { currency?: string; separator?: string; percent?: boolean }): string;
|
|
47
|
+
/** A decimal with `places` places; an interval prints as one number when both ends round to it. */
|
|
48
|
+
export function show(x: Certified, places?: number): string;
|
|
49
|
+
/** Shares in proportion to the weights that add up to the total exactly. */
|
|
50
|
+
export function allocate(total: Amount, weights: Amount[], options?: { places?: number }): Rational[];
|
|
51
|
+
export function power(base: Amount, exponent: Amount, digits?: number): Certified;
|
|
52
|
+
export function exp(x: Amount | RationalInterval, digits?: number): RationalInterval;
|
|
53
|
+
export function ln(x: Amount | RationalInterval, digits?: number): RationalInterval;
|
|
54
|
+
|
|
55
|
+
export class CalendarDate {
|
|
56
|
+
constructor(year: number, month: number, day: number);
|
|
57
|
+
year: number;
|
|
58
|
+
month: number;
|
|
59
|
+
day: number;
|
|
60
|
+
/** Days from 1970-01-01. */
|
|
61
|
+
readonly serial: number;
|
|
62
|
+
readonly isEndOfMonth: boolean;
|
|
63
|
+
addDays(n: number): CalendarDate;
|
|
64
|
+
addMonths(n: number, options?: { endOfMonth?: boolean }): CalendarDate;
|
|
65
|
+
compareTo(o: DateLike): number;
|
|
66
|
+
equals(o: DateLike): boolean;
|
|
67
|
+
toString(): string;
|
|
68
|
+
}
|
|
69
|
+
/** "2027-03-15", "2027-03" (the first of the month), [y, m, d] or a CalendarDate. */
|
|
70
|
+
export type DateLike = CalendarDate | string | [number, number, number];
|
|
71
|
+
export function date(x: DateLike): CalendarDate;
|
|
72
|
+
export function daysBetween(a: DateLike, b: DateLike): number;
|
|
73
|
+
export function isLeap(year: number): boolean;
|
|
74
|
+
export type DayCount = "30/360" | "30E/360" | "actual/360" | "actual/365" | "actual/actual";
|
|
75
|
+
export const DAY_COUNTS: readonly DayCount[];
|
|
76
|
+
export function dayCount(from: DateLike, to: DateLike, convention?: DayCount): { days: number; yearFraction: Rational };
|
|
77
|
+
|
|
78
|
+
// ---- time value ----------------------------------------------------------------
|
|
79
|
+
|
|
80
|
+
export function simpleInterest(principal: Amount, rate: Amount, time: Amount): { interest: Rational; total: Rational };
|
|
81
|
+
export function compound(principal: Amount, rate: Amount, years: Amount, options?: Digits & { periodsPerYear?: Amount | "continuous" }): Certified;
|
|
82
|
+
export function effectiveRate(nominal: Amount, periodsPerYear?: Amount | "continuous", options?: Digits): Certified;
|
|
83
|
+
export function nominalRate(effective: Amount, periodsPerYear?: Amount | "continuous", options?: Digits): Certified;
|
|
84
|
+
export function equivalentRate(nominal: Amount, from: Amount, to: Amount, options?: Digits): Certified;
|
|
85
|
+
export function realRate(nominal: Amount, inflation: Amount): Rational;
|
|
86
|
+
export function discountFactor(rate: Amount, periods: Amount, options?: Digits): Certified;
|
|
87
|
+
export function futureValue(pv: Amount, rate: Amount, periods: Amount, options?: Digits): Certified;
|
|
88
|
+
export function presentValue(fv: Amount, rate: Amount, periods: Amount, options?: Digits): Certified;
|
|
89
|
+
export interface AnnuitySpec {
|
|
90
|
+
payment?: Amount;
|
|
91
|
+
rate: Amount;
|
|
92
|
+
periods: Amount;
|
|
93
|
+
/** Payments at the start of each period. */
|
|
94
|
+
due?: boolean;
|
|
95
|
+
/** Each payment is (1 + growth) times the one before. */
|
|
96
|
+
growth?: Amount;
|
|
97
|
+
/** Periods before the annuity starts. */
|
|
98
|
+
deferred?: Amount;
|
|
99
|
+
}
|
|
100
|
+
export function annuity(spec: AnnuitySpec): { presentValue: Rational; futureValue: Rational; total: Rational; payments: number };
|
|
101
|
+
export function perpetuity(spec: Omit<AnnuitySpec, "periods">): Rational;
|
|
102
|
+
|
|
103
|
+
export interface SolvedRate {
|
|
104
|
+
/** A Rational when the root is rational, otherwise an interval that contains exactly one root. */
|
|
105
|
+
rate: Certified;
|
|
106
|
+
exact: boolean;
|
|
107
|
+
text: string;
|
|
108
|
+
multiplicity: number;
|
|
109
|
+
}
|
|
110
|
+
/** Every rate r > −1 with Σ coefficients[k]·(1 + r)^k = 0, in increasing order. */
|
|
111
|
+
export function rateRoots(coefficients: Rational[], options?: Digits & { limit?: number }): SolvedRate[];
|
|
112
|
+
export interface TvmProblem extends Digits {
|
|
113
|
+
pv?: Amount;
|
|
114
|
+
fv?: Amount;
|
|
115
|
+
pmt?: Amount;
|
|
116
|
+
rate?: Amount;
|
|
117
|
+
n?: Amount;
|
|
118
|
+
due?: boolean;
|
|
119
|
+
}
|
|
120
|
+
export type TvmAnswer =
|
|
121
|
+
| { solved: "pv"; pv: Rational; exact: true }
|
|
122
|
+
| { solved: "fv"; fv: Rational; exact: true }
|
|
123
|
+
| { solved: "pmt"; pmt: Rational; exact: true }
|
|
124
|
+
| { solved: "n"; n: Certified; exact: boolean; /** The whole number of periods needed. */ whole: number }
|
|
125
|
+
| { solved: "rate"; rates: SolvedRate[]; /** The rate when there is exactly one. */ rate: Certified | null; count: number };
|
|
126
|
+
/** pv + pmt·a + fv·(1 + rate)^−n = 0, money received positive: leave out exactly one of pv, fv, pmt, rate, n. */
|
|
127
|
+
export function tvm(problem: TvmProblem): TvmAnswer;
|
|
128
|
+
|
|
129
|
+
// ---- loans ---------------------------------------------------------------------
|
|
130
|
+
|
|
131
|
+
export interface LoanSpec {
|
|
132
|
+
principal: Amount;
|
|
133
|
+
/** Nominal annual rate; the rate per period is rate/periodsPerYear. */
|
|
134
|
+
rate: Amount;
|
|
135
|
+
periods?: number;
|
|
136
|
+
periodsPerYear?: Amount;
|
|
137
|
+
/** Fix the payment; then periods may be left out. */
|
|
138
|
+
payment?: Amount;
|
|
139
|
+
rounding?: Rounding;
|
|
140
|
+
extra?: Amount | Record<number, Amount> | ((period: number, balance: Rational) => Amount | undefined);
|
|
141
|
+
interestOnly?: number;
|
|
142
|
+
balloon?: Amount;
|
|
143
|
+
rateChanges?: { from: number; rate: Amount }[];
|
|
144
|
+
}
|
|
145
|
+
export interface LoanRow {
|
|
146
|
+
period: number;
|
|
147
|
+
/** The rate per period. */
|
|
148
|
+
rate: Rational;
|
|
149
|
+
payment: Rational;
|
|
150
|
+
interest: Rational;
|
|
151
|
+
principal: Rational;
|
|
152
|
+
extra: Rational;
|
|
153
|
+
balance: Rational;
|
|
154
|
+
balloon?: Rational;
|
|
155
|
+
}
|
|
156
|
+
export interface Loan {
|
|
157
|
+
principal: Rational;
|
|
158
|
+
periodsPerYear: Rational;
|
|
159
|
+
/** The regular (rounded) payment. */
|
|
160
|
+
payment: Rational;
|
|
161
|
+
/** The level payment before rounding, when the loan is a plain one. */
|
|
162
|
+
exactPayment: Rational | null;
|
|
163
|
+
schedule: LoanRow[];
|
|
164
|
+
periods: number;
|
|
165
|
+
finalPayment: Rational;
|
|
166
|
+
balloon: Rational;
|
|
167
|
+
totals: { payments: Rational; interest: Rational; principal: Rational; extra: Rational };
|
|
168
|
+
}
|
|
169
|
+
export function loan(spec: LoanSpec): Loan;
|
|
170
|
+
export function levelPayment(balance: Amount, periodicRate: Amount, periods: number, balloon?: Amount): Rational;
|
|
171
|
+
export interface LoanSummary {
|
|
172
|
+
payment: Rational;
|
|
173
|
+
periods: number;
|
|
174
|
+
interest: Rational;
|
|
175
|
+
total: Rational;
|
|
176
|
+
}
|
|
177
|
+
export function compareLoans(a: Loan | LoanSpec, b: Loan | LoanSpec): { a: LoanSummary; b: LoanSummary; difference: LoanSummary };
|
|
178
|
+
export function refinance(
|
|
179
|
+
current: Omit<LoanSpec, "principal"> & { balance: Amount },
|
|
180
|
+
proposed: Omit<LoanSpec, "principal">,
|
|
181
|
+
options?: { costs?: Amount; rollIn?: boolean; rounding?: Rounding },
|
|
182
|
+
): { current: Loan; proposed: Loan; costs: Rational; paymentChange: Rational; interestSaved: Rational; totalSaved: Rational; breakEven: number | null; worthIt: boolean };
|
|
183
|
+
export function revolving(spec: {
|
|
184
|
+
balance: Amount;
|
|
185
|
+
rate: Amount;
|
|
186
|
+
periodsPerYear?: Amount;
|
|
187
|
+
payment: Amount | { percent?: Amount; minimum?: Amount };
|
|
188
|
+
purchases?: Amount | ((period: number) => Amount | undefined);
|
|
189
|
+
rounding?: Rounding;
|
|
190
|
+
maxPeriods?: number;
|
|
191
|
+
}): { schedule: { period: number; interest: Rational; payment: Rational; purchases: Rational; balance: Rational }[]; periods: number; totals: { payments: Rational; interest: Rational } };
|
|
192
|
+
export function loanAPR(spec: Digits & { principal: Amount; fees?: Amount; payment: Amount; periods: number; periodsPerYear?: Amount; balloon?: Amount }): { periodic: Certified; nominal: Certified; effective: Certified; exact: boolean };
|
|
193
|
+
|
|
194
|
+
// ---- cash flows ----------------------------------------------------------------
|
|
195
|
+
|
|
196
|
+
/** Amounts at times 0, 1, 2, …, or { t, amount } at any exact times. */
|
|
197
|
+
export type Flows = Amount[] | { t?: Amount; amount: Amount }[];
|
|
198
|
+
export type DatedFlows = { date: DateLike; amount: Amount }[];
|
|
199
|
+
export function npv(rate: Amount, flows: Flows, options?: Digits): Certified;
|
|
200
|
+
export function xnpv(rate: Amount, flows: DatedFlows, options?: Digits & { dayCount?: DayCount }): Certified;
|
|
201
|
+
export interface RatesOfReturn {
|
|
202
|
+
rates: SolvedRate[];
|
|
203
|
+
count: number;
|
|
204
|
+
signChanges: number;
|
|
205
|
+
/** The rate when there is exactly one, else null. */
|
|
206
|
+
rate: Certified | null;
|
|
207
|
+
note: string;
|
|
208
|
+
}
|
|
209
|
+
/** Every internal rate of return above −100%, with a proven count. */
|
|
210
|
+
export function irr(flows: Flows, options?: Digits): RatesOfReturn;
|
|
211
|
+
export function xirr(flows: DatedFlows, options?: Digits & { dayCount?: DayCount; range?: [Amount, Amount] }): Omit<RatesOfReturn, "rates"> & { rates: { rate: Certified; exact: boolean; text: string; proven: boolean }[]; formula?: string };
|
|
212
|
+
export function mirr(flows: Amount[], financeRate: Amount, reinvestRate: Amount, options?: Digits): Certified;
|
|
213
|
+
export function payback(flows: Amount[], options?: { rate?: Amount }): { period: number | null; fractional: Rational | null; cumulative: Rational[] };
|
|
214
|
+
export function realValue(nominal: Amount, inflation: Amount, periods: Amount, options?: Digits): Certified;
|
|
215
|
+
export function nominalValue(real: Amount, inflation: Amount, periods: Amount, options?: Digits): Certified;
|
|
216
|
+
export type DepreciationMethod = "straight-line" | "declining-balance" | "sum-of-years-digits" | "units-of-production";
|
|
217
|
+
export const DEPRECIATION: readonly DepreciationMethod[];
|
|
218
|
+
export function depreciation(spec: {
|
|
219
|
+
cost: Amount;
|
|
220
|
+
salvage?: Amount;
|
|
221
|
+
life?: number;
|
|
222
|
+
method?: DepreciationMethod;
|
|
223
|
+
/** Declining balance: the rate is factor/life (default 2). */
|
|
224
|
+
factor?: Amount;
|
|
225
|
+
switchToStraightLine?: boolean;
|
|
226
|
+
units?: Amount[];
|
|
227
|
+
totalUnits?: Amount;
|
|
228
|
+
rounding?: Rounding;
|
|
229
|
+
}): { period: number; depreciation: Rational; accumulated: Rational; bookValue: Rational }[];
|
|
230
|
+
export interface TaxResult {
|
|
231
|
+
tax: Rational;
|
|
232
|
+
marginalRate: Rational;
|
|
233
|
+
averageRate: Rational;
|
|
234
|
+
parts: { from: Rational; to: Rational; rate: Rational; tax: Rational }[];
|
|
235
|
+
afterTax: Rational;
|
|
236
|
+
}
|
|
237
|
+
/** Brackets in increasing order, the last with no upTo. No jurisdiction's table is built in. */
|
|
238
|
+
export function taxSchedule(brackets: { upTo?: Amount | null; rate: Amount }[], options?: { rounding?: Rounding }): { brackets: { upTo: Rational | null; rate: Rational }[]; on(income: Amount): TaxResult };
|
|
239
|
+
|
|
240
|
+
// ---- bonds and curves ----------------------------------------------------------
|
|
241
|
+
|
|
242
|
+
export interface BondSpec {
|
|
243
|
+
face?: Amount;
|
|
244
|
+
/** Annual coupon rate. */
|
|
245
|
+
coupon?: Amount;
|
|
246
|
+
/** Coupons a year: 1, 2, 3, 4, 6 or 12 (default 2). */
|
|
247
|
+
frequency?: number;
|
|
248
|
+
redemption?: Amount;
|
|
249
|
+
/** Whole coupon periods left, valued on a coupon date. */
|
|
250
|
+
periods?: number;
|
|
251
|
+
settlement?: DateLike;
|
|
252
|
+
maturity?: DateLike;
|
|
253
|
+
dayCount?: DayCount;
|
|
254
|
+
}
|
|
255
|
+
export class Bond {
|
|
256
|
+
constructor(spec: BondSpec);
|
|
257
|
+
face: Rational;
|
|
258
|
+
coupon: Rational;
|
|
259
|
+
frequency: number;
|
|
260
|
+
redemption: Rational;
|
|
261
|
+
couponAmount: Rational;
|
|
262
|
+
periods: number;
|
|
263
|
+
accrued: Rational;
|
|
264
|
+
accruedDays: number;
|
|
265
|
+
/** The fraction of a coupon period until the next coupon (1 on a coupon date). */
|
|
266
|
+
first: Rational;
|
|
267
|
+
settlement?: CalendarDate;
|
|
268
|
+
maturity?: CalendarDate;
|
|
269
|
+
readonly cashflows: { t: Rational; years: Rational; amount: Rational; date?: CalendarDate }[];
|
|
270
|
+
/** At a nominal annual yield compounded `frequency` times. Exact on a coupon date. */
|
|
271
|
+
price(yieldRate: Amount, options?: Digits): { dirty: Certified; clean: Certified; accrued: Rational };
|
|
272
|
+
/** The one yield that gives this clean price. */
|
|
273
|
+
yield(cleanPrice: Amount, options?: Digits): Certified;
|
|
274
|
+
duration(yieldRate: Amount): { macaulay: Rational; modified: Rational; convexity: Rational; percentPerPoint: Rational };
|
|
275
|
+
}
|
|
276
|
+
export function bond(spec: BondSpec | Bond): Bond;
|
|
277
|
+
export class YieldCurve {
|
|
278
|
+
constructor(discountFactors: Amount[], frequency?: number);
|
|
279
|
+
discountFactors: Rational[];
|
|
280
|
+
frequency: number;
|
|
281
|
+
readonly periods: number;
|
|
282
|
+
discount(k: number): Rational;
|
|
283
|
+
/** Nominal annual, compounded `frequency` times. */
|
|
284
|
+
spot(k: number, options?: Digits): Certified;
|
|
285
|
+
/** Exact when b = a + 1. */
|
|
286
|
+
forward(a: number, b?: number, options?: Digits): Certified;
|
|
287
|
+
parYield(k: number): Rational;
|
|
288
|
+
price(spec: BondSpec | Bond): Rational;
|
|
289
|
+
readonly spots: Certified[];
|
|
290
|
+
readonly forwards: Certified[];
|
|
291
|
+
}
|
|
292
|
+
export function yieldCurve(spec: { spots?: Amount[]; discountFactors?: Amount[]; frequency?: number }): YieldCurve;
|
|
293
|
+
/** One bond maturing at each of periods 1, 2, 3, …, each with its price. */
|
|
294
|
+
export function bootstrap(bonds: (BondSpec & { price: Amount })[], options?: { frequency?: number }): YieldCurve;
|
|
295
|
+
export function immunise(problem: { liability: { amount: Amount; time: Amount }; yield: Amount; bonds: [BondSpec | Bond, BondSpec | Bond] }): {
|
|
296
|
+
presentValue: Rational;
|
|
297
|
+
weights: [Rational, Rational];
|
|
298
|
+
amounts: [Rational, Rational];
|
|
299
|
+
units: [Rational, Rational];
|
|
300
|
+
durations: [Rational, Rational];
|
|
301
|
+
convexity: { assets: Rational; liability: Rational };
|
|
302
|
+
/** Both weights are non-negative and the assets are at least as convex as the liability. */
|
|
303
|
+
immunised: boolean;
|
|
304
|
+
short: boolean;
|
|
305
|
+
/** Assets less liability if the yield moves to this value. */
|
|
306
|
+
surplusAt(yieldRate: Amount): Rational;
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
// ---- scenarios -----------------------------------------------------------------
|
|
310
|
+
|
|
311
|
+
/** A value with its derivative in one chosen input, as handed to a sensitivity `build` function. */
|
|
312
|
+
export class Dual {
|
|
313
|
+
constructor(v: Rational, d?: Rational);
|
|
314
|
+
v: Rational;
|
|
315
|
+
d: Rational;
|
|
316
|
+
add(o: Amount | Dual): Dual;
|
|
317
|
+
subtract(o: Amount | Dual): Dual;
|
|
318
|
+
multiply(o: Amount | Dual): Dual;
|
|
319
|
+
divide(o: Amount | Dual): Dual;
|
|
320
|
+
negate(): Dual;
|
|
321
|
+
pow(n: number): Dual;
|
|
322
|
+
compareTo(o: Amount | Dual): number;
|
|
323
|
+
toString(): string;
|
|
324
|
+
}
|
|
325
|
+
type Input = Amount | Dual;
|
|
326
|
+
/** A period number, or a month such as "2028-06" when the scenario has a start. */
|
|
327
|
+
export type When = number | string;
|
|
328
|
+
export interface AccountSpec {
|
|
329
|
+
name: string;
|
|
330
|
+
balance?: Input;
|
|
331
|
+
/** Annual rate, applied each period as rate/periodsPerYear; a negative balance is charged the same way. */
|
|
332
|
+
rate?: Input;
|
|
333
|
+
rateChanges?: { from: When; rate: Input }[];
|
|
334
|
+
/** One annual rate per period, overriding the others while it lasts (what a simulation writes in). */
|
|
335
|
+
rates?: Input[];
|
|
336
|
+
}
|
|
337
|
+
export interface FlowSpec {
|
|
338
|
+
name?: string;
|
|
339
|
+
amount: Input;
|
|
340
|
+
to?: string;
|
|
341
|
+
from?: string;
|
|
342
|
+
start?: When;
|
|
343
|
+
end?: When;
|
|
344
|
+
/** One period only. */
|
|
345
|
+
at?: When;
|
|
346
|
+
every?: number;
|
|
347
|
+
/** Applied once a year from the flow's start. */
|
|
348
|
+
growth?: Input;
|
|
349
|
+
/** One multiplier per period (a zero skips that period): how inflation and random events are written in. */
|
|
350
|
+
index?: Input[];
|
|
351
|
+
/** Stop when the `to` account is no longer in debt. */
|
|
352
|
+
until?: "paid";
|
|
353
|
+
/** Where the money goes once that happens. */
|
|
354
|
+
then?: string;
|
|
355
|
+
}
|
|
356
|
+
export interface ScenarioSpec {
|
|
357
|
+
name?: string;
|
|
358
|
+
periods: number;
|
|
359
|
+
periodsPerYear?: number;
|
|
360
|
+
/** The first period's month, such as "2027-01". */
|
|
361
|
+
start?: DateLike;
|
|
362
|
+
accounts: AccountSpec[];
|
|
363
|
+
flows?: FlowSpec[];
|
|
364
|
+
rounding?: Rounding;
|
|
365
|
+
}
|
|
366
|
+
export interface ProjectionRow {
|
|
367
|
+
period: number;
|
|
368
|
+
date: string | null;
|
|
369
|
+
balances: Record<string, Rational>;
|
|
370
|
+
interest: Record<string, Rational>;
|
|
371
|
+
flows: Record<string, Rational>;
|
|
372
|
+
netWorth: Rational;
|
|
373
|
+
}
|
|
374
|
+
export interface Projection {
|
|
375
|
+
name?: string;
|
|
376
|
+
opening: ProjectionRow;
|
|
377
|
+
rows: ProjectionRow[];
|
|
378
|
+
final: Record<string, Rational>;
|
|
379
|
+
netWorth: Rational;
|
|
380
|
+
minimum: Record<string, { balance: Rational; period: number }>;
|
|
381
|
+
firstNegative: { account: string; period: number; date: string | null } | null;
|
|
382
|
+
totals: { interest: Record<string, Rational>; flows: Record<string, Rational> };
|
|
383
|
+
accounts: string[];
|
|
384
|
+
}
|
|
385
|
+
export class Scenario {
|
|
386
|
+
constructor(spec: ScenarioSpec);
|
|
387
|
+
periods: number;
|
|
388
|
+
periodsPerYear: number;
|
|
389
|
+
/** Each period: interest on the opening balances, then the flows in order. */
|
|
390
|
+
project(): Projection;
|
|
391
|
+
}
|
|
392
|
+
export function scenario(spec: ScenarioSpec | Scenario): Scenario;
|
|
393
|
+
export function compare(
|
|
394
|
+
scenarios: Record<string, ScenarioSpec | Scenario>,
|
|
395
|
+
options?: { measure?: (p: Projection) => Rational },
|
|
396
|
+
): {
|
|
397
|
+
rows: { name: string; outcome: Rational; netWorth: Rational; difference: Rational; firstNegative: Projection["firstNegative"]; lowest: { account: string; balance: Rational; period: number } }[];
|
|
398
|
+
best: string;
|
|
399
|
+
series: Record<string, Rational[]>;
|
|
400
|
+
crossovers: { period: number; ahead: string; behind: string }[];
|
|
401
|
+
};
|
|
402
|
+
/** The exact derivative of the outcome in each input, most influential first. The scenario must be unrounded. */
|
|
403
|
+
export function sensitivity<K extends string>(
|
|
404
|
+
build: (inputs: Record<K, Dual>) => ScenarioSpec | Scenario,
|
|
405
|
+
inputs: Record<K, Amount>,
|
|
406
|
+
options?: { measure?: (p: Projection) => Rational | Dual },
|
|
407
|
+
): { base: Rational; rows: { input: K; value: Rational; derivative: Rational; perPercent: Rational; elasticity: Rational | null }[]; most: K | null };
|
|
408
|
+
|
|
409
|
+
// ---- uncertain inputs and repeated runs (phase 5) --------------------------------
|
|
410
|
+
|
|
411
|
+
/** Anything with sample(rng): a distribution from @ratmath/stats, or your own. */
|
|
412
|
+
export interface Sampler { sample(rng: unknown): number | bigint | Rational }
|
|
413
|
+
export class Process {
|
|
414
|
+
name: string;
|
|
415
|
+
kind: string;
|
|
416
|
+
/** Growth factors, one per period (1 + the return or interest for that period). */
|
|
417
|
+
path(rng: unknown, periods: number, periodsPerYear?: number): Rational[];
|
|
418
|
+
/** The same path as annual nominal rates per period, the form a scenario account takes. */
|
|
419
|
+
rates(rng: unknown, periods: number, periodsPerYear?: number): Rational[];
|
|
420
|
+
}
|
|
421
|
+
export const processes: {
|
|
422
|
+
fixed(rate: Amount): Process;
|
|
423
|
+
independent(dist: Sampler): Process;
|
|
424
|
+
/** Annual returns from a finite list with exact weights: small cases can be enumerated exactly. */
|
|
425
|
+
choice(values: Amount[], weights?: Amount[]): Process;
|
|
426
|
+
sequence(returns: Amount[]): Process;
|
|
427
|
+
resample(history: Amount[], options?: { block?: number }): Process;
|
|
428
|
+
gbm(spec: { drift: Amount; volatility: Amount }): Process;
|
|
429
|
+
walk(spec: { start: Amount; step: Sampler; min?: Amount; max?: Amount }): Process;
|
|
430
|
+
meanReverting(spec: { start: Amount; mean: Amount; speed: Amount; volatility: Amount; floor?: Amount | null }): Process;
|
|
431
|
+
};
|
|
432
|
+
export interface RandomEvent {
|
|
433
|
+
name: string;
|
|
434
|
+
/** Per year by default, or per period with per: "period". */
|
|
435
|
+
probability: Amount;
|
|
436
|
+
per?: "year" | "period";
|
|
437
|
+
amount: Amount | Sampler;
|
|
438
|
+
from?: string;
|
|
439
|
+
to?: string;
|
|
440
|
+
once?: boolean;
|
|
441
|
+
start?: number;
|
|
442
|
+
end?: number;
|
|
443
|
+
/** Grow the amount with inflation. */
|
|
444
|
+
indexed?: boolean;
|
|
445
|
+
}
|
|
446
|
+
export interface SimulatedRate {
|
|
447
|
+
kind: "simulated";
|
|
448
|
+
rate: Rational;
|
|
449
|
+
hits: number;
|
|
450
|
+
runs: number;
|
|
451
|
+
seed: unknown;
|
|
452
|
+
interval: { low: Rational; high: Rational; level: Rational };
|
|
453
|
+
compare(value: Amount): "below" | "inside" | "above";
|
|
454
|
+
}
|
|
455
|
+
export class Simulation {
|
|
456
|
+
kind: "simulated";
|
|
457
|
+
name?: string;
|
|
458
|
+
seed: unknown;
|
|
459
|
+
runs: number;
|
|
460
|
+
rounding: Rounding;
|
|
461
|
+
/** One outcome per run, in run order. */
|
|
462
|
+
outcomes: Rational[];
|
|
463
|
+
sorted: Rational[];
|
|
464
|
+
mean: Rational;
|
|
465
|
+
standardError: Certified | null;
|
|
466
|
+
percentiles: Record<string, Rational>;
|
|
467
|
+
/** How often an account that started at or above zero went below it, with an exact interval. */
|
|
468
|
+
ruin: SimulatedRate;
|
|
469
|
+
ruinTimes: number[];
|
|
470
|
+
/** Percentiles of the tracked quantity at each period. */
|
|
471
|
+
bands: Array<{ period: number } & Record<string, Rational>>;
|
|
472
|
+
/** Outcomes in today's money, when there is inflation. */
|
|
473
|
+
real: { outcomes: Rational[]; mean: Rational; median: Rational } | null;
|
|
474
|
+
quantile(p: Amount): Rational;
|
|
475
|
+
}
|
|
476
|
+
export function simulate(
|
|
477
|
+
spec: ScenarioSpec,
|
|
478
|
+
options?: {
|
|
479
|
+
returns?: Record<string, Process>;
|
|
480
|
+
inflation?: Process | null;
|
|
481
|
+
indexed?: string[];
|
|
482
|
+
events?: RandomEvent[];
|
|
483
|
+
runs?: number;
|
|
484
|
+
seed?: unknown;
|
|
485
|
+
rounding?: Rounding;
|
|
486
|
+
measure?: (p: Projection) => Rational;
|
|
487
|
+
ruin?: (p: Projection) => boolean;
|
|
488
|
+
level?: Amount;
|
|
489
|
+
percentiles?: Amount[];
|
|
490
|
+
track?: string;
|
|
491
|
+
name?: string;
|
|
492
|
+
},
|
|
493
|
+
): Simulation;
|
|
494
|
+
export function sequenceRisk(
|
|
495
|
+
spec: ScenarioSpec,
|
|
496
|
+
options: { account: string; returns: Amount[]; shuffles?: number; seed?: unknown; measure?: (p: Projection) => Rational },
|
|
497
|
+
): { rows: { order: string; returns: Rational[]; outcome: Rational; firstNegative: Projection["firstNegative"] }[]; best: string; worst: string; spread: Rational; orderMatters: boolean };
|
|
498
|
+
|
|
499
|
+
// ---- portfolios, options, life contingencies (phase 6) ----------------------------
|
|
500
|
+
|
|
501
|
+
export interface PortfolioResult {
|
|
502
|
+
weights: Record<string, Rational>;
|
|
503
|
+
w: Rational[];
|
|
504
|
+
expectedReturn: Rational;
|
|
505
|
+
variance: Rational;
|
|
506
|
+
risk: Certified;
|
|
507
|
+
}
|
|
508
|
+
export class Portfolio {
|
|
509
|
+
constructor(spec: { names?: string[]; means?: Amount[]; covariance?: Amount[][]; returns?: Amount[][]; riskFree?: Amount | null });
|
|
510
|
+
names: string[];
|
|
511
|
+
means: Rational[];
|
|
512
|
+
covariance: Rational[][];
|
|
513
|
+
expectedReturn(w: Amount[]): Rational;
|
|
514
|
+
variance(w: Amount[]): Rational;
|
|
515
|
+
risk(w: Amount[], options?: { bits?: number }): Certified;
|
|
516
|
+
constants(): { invOnes: Rational[]; invMeans: Rational[]; A: Rational; B: Rational; C: Rational; D: Rational };
|
|
517
|
+
minimumVariance(): PortfolioResult;
|
|
518
|
+
/** Short sales allowed; exact closed form. */
|
|
519
|
+
frontier(target: Amount): PortfolioResult;
|
|
520
|
+
/** No short sales, up to 12 assets; `certificate` holds the KKT multipliers that prove the minimum. */
|
|
521
|
+
frontierLongOnly(target: Amount): PortfolioResult & { support: string[]; certificate: { lambda: Rational; gamma: Rational } | null };
|
|
522
|
+
tangency(riskFree?: Amount): PortfolioResult & { sharpeSquared: Rational; sharpe: Certified; riskFree: Rational };
|
|
523
|
+
}
|
|
524
|
+
export function portfolio(spec: ConstructorParameters<typeof Portfolio>[0]): Portfolio;
|
|
525
|
+
export function returnsFrom(prices: Amount[]): Rational[];
|
|
526
|
+
export function capm(spec: { asset: Amount[]; market: Amount[]; riskFree?: Amount; marketReturn?: Amount | null }): { beta: Rational; alpha: Rational; required: Rational; marketPremium: Rational; riskFree: Rational };
|
|
527
|
+
export function solveExact(M: Rational[][], b: Rational[]): Rational[] | null;
|
|
528
|
+
|
|
529
|
+
export interface Leg { type: "call" | "put" | "stock" | "bond"; strike?: Amount; premium?: Amount; quantity?: Amount }
|
|
530
|
+
export function strategy(legs: Leg[]): {
|
|
531
|
+
legs: Leg[];
|
|
532
|
+
cost: Rational;
|
|
533
|
+
payoff(spot: Amount): Rational;
|
|
534
|
+
profit(spot: Amount): Rational;
|
|
535
|
+
kinks: Rational[];
|
|
536
|
+
breakEvens: Rational[];
|
|
537
|
+
maxProfit: Rational | null;
|
|
538
|
+
maxLoss: Rational | null;
|
|
539
|
+
};
|
|
540
|
+
export function parity(spec: { call?: Amount | RationalInterval; put?: Amount | RationalInterval; spot?: Amount | RationalInterval; strike?: Amount; rate: Amount; time: Amount; compounding?: "continuous" | "annual"; bits?: number }): {
|
|
541
|
+
call?: Certified; put?: Certified; spot?: Certified; strike?: Certified; gap?: Certified; holds?: boolean | null;
|
|
542
|
+
};
|
|
543
|
+
export function binomialTree(spec: {
|
|
544
|
+
spot: Amount; strike: Amount; steps: number; type?: "call" | "put"; style?: "european" | "american";
|
|
545
|
+
up?: Amount; down?: Amount; growth?: Amount; volatility?: Amount; time?: Amount; rate?: Amount; places?: number; keepTree?: boolean; float?: boolean;
|
|
546
|
+
}): {
|
|
547
|
+
/** A number when float is true. */
|
|
548
|
+
price: Rational | number;
|
|
549
|
+
probability: Rational | number;
|
|
550
|
+
up: Rational | number; down: Rational | number; growth: Rational | number;
|
|
551
|
+
delta: Rational | number;
|
|
552
|
+
rounded: boolean;
|
|
553
|
+
approximate?: true;
|
|
554
|
+
earlyExercise: { step: number; ups: number; price: Rational }[] | null;
|
|
555
|
+
tree: Rational[][] | null;
|
|
556
|
+
};
|
|
557
|
+
export function normalCdf(x: Amount | RationalInterval, bits?: number): RationalInterval;
|
|
558
|
+
export function normalPdf(x: Amount | RationalInterval, bits?: number): RationalInterval;
|
|
559
|
+
export function blackScholes(spec: { spot: Amount; strike: Amount; rate: Amount; volatility: Amount; time: Amount; dividendYield?: Amount; bits?: number }): {
|
|
560
|
+
call: RationalInterval; put: RationalInterval; d1: RationalInterval; d2: RationalInterval;
|
|
561
|
+
delta: { call: RationalInterval; put: RationalInterval };
|
|
562
|
+
gamma: RationalInterval; vega: RationalInterval;
|
|
563
|
+
theta: { call: RationalInterval; put: RationalInterval };
|
|
564
|
+
rho: { call: RationalInterval; put: RationalInterval };
|
|
565
|
+
};
|
|
566
|
+
export function impliedVolatility(spec: { price: Amount; type?: "call" | "put"; spot: Amount; strike: Amount; rate: Amount; time: Amount; dividendYield?: Amount; digits?: number; bits?: number }): RationalInterval;
|
|
567
|
+
|
|
568
|
+
export class LifeTable {
|
|
569
|
+
constructor(spec: { l?: Amount[]; q?: Amount[]; radix?: Amount; startAge?: number });
|
|
570
|
+
startAge: number;
|
|
571
|
+
lastAge: number;
|
|
572
|
+
lives: Rational[];
|
|
573
|
+
l(x: number): Rational;
|
|
574
|
+
d(x: number): Rational;
|
|
575
|
+
p(x: number, t?: number): Rational;
|
|
576
|
+
q(x: number, t?: number): Rational;
|
|
577
|
+
deferredQ(x: number, u: number, t?: number): Rational;
|
|
578
|
+
curtateExpectation(x: number): Rational;
|
|
579
|
+
completeExpectation(x: number): Rational;
|
|
580
|
+
rows(): { age: number; l: Rational; d: Rational; q: Rational; p: Rational; e: Rational }[];
|
|
581
|
+
}
|
|
582
|
+
export function lifeTable(spec: ConstructorParameters<typeof LifeTable>[0]): LifeTable;
|
|
583
|
+
export function deMoivre(omega: number, options?: { startAge?: number }): LifeTable;
|
|
584
|
+
export function lifeAnnuity(table: LifeTable, spec: { age: number; rate: Amount; term?: number | null; due?: boolean; deferred?: number }): Rational;
|
|
585
|
+
export function lifeInsurance(table: LifeTable, spec: { age: number; rate: Amount; term?: number | null; deferred?: number }): Rational;
|
|
586
|
+
export function pureEndowment(table: LifeTable, spec: { age: number; rate: Amount; term: number }): Rational;
|
|
587
|
+
export function endowment(table: LifeTable, spec: { age: number; rate: Amount; term: number }): Rational;
|
|
588
|
+
type PolicyKind = "whole life" | "term" | "endowment";
|
|
589
|
+
export function netPremium(table: LifeTable, spec: { kind?: PolicyKind; benefit?: Amount; age: number; rate: Amount; term?: number | null; payments?: number | null }): Rational;
|
|
590
|
+
export function reserve(table: LifeTable, spec: { kind?: PolicyKind; benefit?: Amount; age: number; rate: Amount; term?: number | null; payments?: number | null; time: number }): Rational;
|
package/index.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// @ratmath/finance: the mathematics of finance with exact money.
|
|
2
|
+
//
|
|
3
|
+
// Amounts are rationals and are rounded only where a rule says so; rates
|
|
4
|
+
// found by solving are proven, and every one of them is reported; a
|
|
5
|
+
// scenario is projected exactly, so comparisons and sensitivities are exact.
|
|
6
|
+
|
|
7
|
+
export { plan } from "./src/plan.js";
|
|
8
|
+
export { FinanceError, amount, rate, MONEY_ROUNDING, moneyRounder, round, format, allocate, power, exp, ln, show, CalendarDate, date, daysBetween, dayCount, isLeap, DAY_COUNTS } from "./src/money.js";
|
|
9
|
+
export { simpleInterest, compound, effectiveRate, nominalRate, equivalentRate, realRate, discountFactor, futureValue, presentValue, annuity, perpetuity, tvm } from "./src/tvm.js";
|
|
10
|
+
export { rateRoots } from "./src/solve.js";
|
|
11
|
+
export { loan, levelPayment, compareLoans, refinance, revolving, loanAPR } from "./src/loans.js";
|
|
12
|
+
export { npv, xnpv, irr, xirr, mirr, payback, realValue, nominalValue, depreciation, DEPRECIATION, taxSchedule } from "./src/cashflow.js";
|
|
13
|
+
export { Bond, bond, YieldCurve, yieldCurve, bootstrap, immunise } from "./src/bonds.js";
|
|
14
|
+
export { Scenario, scenario, compare, sensitivity, Dual } from "./src/scenario.js";
|
|
15
|
+
export { Process, processes, simulate, Simulation, sequenceRisk } from "./src/uncertain.js";
|
|
16
|
+
export { Portfolio, portfolio, returnsFrom, capm, solveExact } from "./src/portfolio.js";
|
|
17
|
+
export { strategy, parity, binomialTree, blackScholes, impliedVolatility, normalCdf, normalPdf } from "./src/options.js";
|
|
18
|
+
export { LifeTable, lifeTable, deMoivre, lifeAnnuity, lifeInsurance, pureEndowment, endowment, netPremium, reserve } from "./src/life.js";
|