@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/CHANGELOG.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
- Docs: the browser bundle is rebuilt against Core 0.12 (the checked-in one
|
|
6
|
+
still rounded 65 to 60 at the tens and returned a bare BigInt from
|
|
7
|
+
`floor()`), is built without identifier minification (Bun renames classes
|
|
8
|
+
even with `keepNames`, which broke `new Rational(q.floor())` and
|
|
9
|
+
`q.add(q.floor())` in the browser), and the docs build now runs every code
|
|
10
|
+
box against the emitted bundle after a mixed Integer/Rational check. Found
|
|
11
|
+
by the external QA review.
|
|
12
|
+
|
|
13
|
+
- Money rounding is built on Core 0.12's `rounding()`: `round`, `format` and
|
|
14
|
+
every `rounding` option now also take any Core mode name (`half-odd`,
|
|
15
|
+
`toward-zero`, ...), a Core rounder, or your own function given
|
|
16
|
+
`{ value, floor, ceil, fraction }`. The default stays half-even (banker's
|
|
17
|
+
rounding, usual in accounting software) and lives in one exported constant,
|
|
18
|
+
`MONEY_ROUNDING`; `moneyRounder(mode)` returns the Core rounder for a mode.
|
|
19
|
+
Core's own default is half-up; finance keeps half-even on purpose.
|
|
20
|
+
- Requires Core 0.12: the `@ratmath/core` peer range is now `>=0.12.0` (Core 0.12 returns Integers from `floor`/`ceil`/`trunc`/`round` and rounds half up by default).
|
|
21
|
+
- `parity` takes enclosed prices: the call (or put) that `blackScholes`
|
|
22
|
+
returns goes straight in, and the missing price comes back enclosed. It used
|
|
23
|
+
to refuse with "cannot read … as an exact amount". Found by the Course Test
|
|
24
|
+
(ratmath/shelf#7).
|
|
25
|
+
- `@ratmath/core` is now a peer dependency (`>=0.10.0 <0.12.0`): the package
|
|
26
|
+
uses the program's own copy of Core instead of bringing its own, so Core 0.11
|
|
27
|
+
works and there is never a second copy whose `Rational` is not the same class.
|
|
28
|
+
|
|
29
|
+
## 0.2.0
|
|
30
|
+
|
|
31
|
+
- Uncertain inputs and repeated runs (roadmap phase 5): `processes` turn a
|
|
32
|
+
seeded stream into a path of growth factors (fixed, independent draws from
|
|
33
|
+
a `@ratmath/stats` distribution, a weighted choice, a given sequence,
|
|
34
|
+
block resampling of supplied history, geometric Brownian motion, a random
|
|
35
|
+
walk and a mean-reverting rate); `simulate` writes the paths, inflation
|
|
36
|
+
indexing and random one-off events into a scenario and projects it many
|
|
37
|
+
times, reporting the chance of ruin with an exact interval, percentiles,
|
|
38
|
+
bands over time and real values; `sequenceRisk` shows the effect of the
|
|
39
|
+
order of good and bad years (none, exactly, without flows). Scenarios gain
|
|
40
|
+
per-period `rates` on accounts and an `index` on flows.
|
|
41
|
+
- Portfolios, options and life contingencies (phase 6): `portfolio` with the
|
|
42
|
+
efficient frontier in closed form, the long-only frontier with a KKT
|
|
43
|
+
certificate, the tangency portfolio and its Sharpe ratio; `capm`;
|
|
44
|
+
`strategy` payoffs with exact break-even prices; `parity`; `binomialTree`
|
|
45
|
+
(exact European and American prices, Cox–Ross–Rubinstein from a
|
|
46
|
+
volatility, a floating-point preview); `blackScholes` with every
|
|
47
|
+
sensitivity enclosed and `impliedVolatility` by certified bisection; life
|
|
48
|
+
tables (`lifeTable`, `deMoivre`), `lifeAnnuity`, `lifeInsurance`,
|
|
49
|
+
`pureEndowment`, `endowment`, `netPremium` and `reserve`, all exact.
|
|
50
|
+
- Depends on `@ratmath/stats` (and through it `@ratmath/discrete`), vendored.
|
|
51
|
+
|
|
52
|
+
## 0.1.0
|
|
53
|
+
|
|
54
|
+
- Money and time value (roadmap phase 1): exact `amount`s, `round` with seven
|
|
55
|
+
named rules, `format`, `allocate`; calendar dates and five day-count
|
|
56
|
+
conventions; simple, compound and continuous interest; equivalent rates;
|
|
57
|
+
present and future value; level, growing, due and deferred annuities;
|
|
58
|
+
perpetuities; `tvm`, which solves for whichever of the five quantities is
|
|
59
|
+
left out.
|
|
60
|
+
- Loans and cash flows (phase 2): `loan` schedules to the cent with extra
|
|
61
|
+
payments, interest-only periods, balloons and rate changes; `compareLoans`,
|
|
62
|
+
`refinance`, `loanAPR`, `revolving`; `npv` and `xnpv`; `irr`, which returns
|
|
63
|
+
every internal rate of return with a proven count, and `xirr` for dated
|
|
64
|
+
flows; `mirr`, `payback`, inflation, `depreciation` by four methods and
|
|
65
|
+
`taxSchedule` from brackets the caller supplies.
|
|
66
|
+
- Bonds and rates (phase 3): `bond` with price, yield to maturity, accrued
|
|
67
|
+
interest, duration and convexity, on or between coupon dates; `bootstrap`
|
|
68
|
+
and `yieldCurve` with spot, forward and par rates; `immunise`.
|
|
69
|
+
- Scenarios (phase 4): `scenario` projects accounts and flows exactly;
|
|
70
|
+
`compare` sets scenarios side by side; `sensitivity` gives the exact
|
|
71
|
+
derivative of the outcome in each input.
|
|
72
|
+
- Docs: overview, explore, reference and eight topic pages.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 RatMath
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,94 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ratmath/finance
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The mathematics of finance for [RatMath](https://ratmath.com/), part of the
|
|
4
|
+
[RatMath Shelf](https://ratmath.com/shelf/). Docs: [ratmath.com/finance](https://ratmath.com/finance/).
|
|
5
|
+
|
|
6
|
+
Amounts are exact rationals. Rounding happens only where a named rule says
|
|
7
|
+
so, so a schedule adds up to the cent and its last payment is adjusted
|
|
8
|
+
visibly. A rate found by solving an equation is proven, and when a cash flow
|
|
9
|
+
has two rates of return, or none, that is the answer. A scenario is projected
|
|
10
|
+
exactly, so comparisons and sensitivities are exact too.
|
|
11
|
+
|
|
12
|
+
```js
|
|
13
|
+
import { loan, irr, bond, bootstrap, scenario, sensitivity, round, show } from "@ratmath/finance";
|
|
14
|
+
|
|
15
|
+
const l = loan({ principal: 250000, rate: "6%", periods: 360 });
|
|
16
|
+
show(l.payment, 2); // "1498.88"
|
|
17
|
+
show(l.finalPayment, 2); // "1495.22"
|
|
18
|
+
show(l.totals.interest, 2); // "289593.14"
|
|
19
|
+
|
|
20
|
+
irr([-1000, 2300, -1320]).rates.map((r) => r.text); // ["1/10", "1/5"]
|
|
21
|
+
irr([-1000, 2000, -1500]).count; // 0, proven
|
|
22
|
+
|
|
23
|
+
const b = bond({ coupon: "5%", periods: 20 });
|
|
24
|
+
show(b.price("6%").clean, 6); // "92.561263"
|
|
25
|
+
b.yield(100); // 1/20, exactly
|
|
26
|
+
|
|
27
|
+
scenario({
|
|
28
|
+
periods: 120,
|
|
29
|
+
accounts: [{ name: "savings", balance: 10000, rate: "4%" }],
|
|
30
|
+
flows: [{ amount: 500, to: "savings", growth: "2%" }],
|
|
31
|
+
}).project().netWorth; // an exact fraction
|
|
32
|
+
|
|
33
|
+
round("2.345"); // 2.34 (half-even); { mode: "half-up" } gives 2.35
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
No market data, no tax tables and no advice are built in. The caller supplies
|
|
37
|
+
the numbers.
|
|
38
|
+
|
|
39
|
+
## What is built
|
|
40
|
+
|
|
41
|
+
| Area | Functions |
|
|
42
|
+
|---|---|
|
|
43
|
+
| Money and rounding | `amount`, `round` (seven named modes), `format`, `show`, `allocate` |
|
|
44
|
+
| Dates | `date`, `daysBetween`, `dayCount` (30/360, 30E/360, actual/360, actual/365, actual/actual) |
|
|
45
|
+
| Time value | `simpleInterest`, `compound`, `effectiveRate`, `nominalRate`, `equivalentRate`, `realRate`, `presentValue`, `futureValue`, `annuity`, `perpetuity`, `tvm` (solves for the missing quantity) |
|
|
46
|
+
| Loans | `loan` (extra payments, interest-only, balloon, rate changes), `levelPayment`, `compareLoans`, `refinance`, `loanAPR`, `revolving` |
|
|
47
|
+
| Cash flows | `npv`, `xnpv`, `irr` (every rate), `xirr`, `mirr`, `payback`, `realValue`, `nominalValue`, `depreciation`, `taxSchedule` |
|
|
48
|
+
| Bonds and rates | `bond` (price, yield, accrued interest, duration, convexity), `bootstrap`, `yieldCurve` (spot, forward, par yield), `immunise` |
|
|
49
|
+
| Scenarios | `scenario` and `.project()`, `compare`, `sensitivity` (exact derivatives) |
|
|
50
|
+
| Uncertain inputs | `processes` (fixed, independent, choice, sequence, resample, gbm, walk, meanReverting), `simulate` (seeded runs: ruin with an exact interval, percentiles, bands, real values, random events), `sequenceRisk` |
|
|
51
|
+
| Portfolios | `portfolio` (frontier exactly, long-only with a KKT certificate, tangency), `capm`, `returnsFrom` |
|
|
52
|
+
| Options | `strategy` (exact break-evens), `parity`, `binomialTree` (exact, European or American), `blackScholes` and `impliedVolatility` (certified) |
|
|
53
|
+
| Life contingencies | `lifeTable`, `deMoivre`, `lifeAnnuity`, `lifeInsurance`, `pureEndowment`, `endowment`, `netPremium`, `reserve` |
|
|
54
|
+
|
|
55
|
+
Results are Core `Rational`s when exact, and `RationalInterval`s proven to
|
|
56
|
+
contain the value when a root or an exponential is involved. Simulated
|
|
57
|
+
results carry their seed and their sampling error.
|
|
58
|
+
|
|
59
|
+
## Still planned
|
|
60
|
+
|
|
61
|
+
| Phase | Contents |
|
|
62
|
+
|---|---|
|
|
63
|
+
| 7 | Pictures |
|
|
64
|
+
|
|
65
|
+
The plan is in the
|
|
66
|
+
[library roadmap](https://github.com/ratmath/ratmath/blob/main/docs/design/library-roadmap.md#12-a-finance-package-ratmathfinance),
|
|
67
|
+
and `plan` exports the list.
|
|
68
|
+
|
|
69
|
+
## Layout
|
|
70
|
+
|
|
71
|
+
- `index.js`, `src/`: the library. `money.js` (amounts, rounding, dates),
|
|
72
|
+
`solve.js` (rates as roots), `tvm.js`, `loans.js`, `cashflow.js`,
|
|
73
|
+
`bonds.js`, `scenario.js`, `uncertain.js`, `portfolio.js`, `options.js`,
|
|
74
|
+
`life.js`, `plan.js`.
|
|
75
|
+
- `vendor/analytic`, `vendor/algebraic`, `vendor/stats`, `vendor/discrete`:
|
|
76
|
+
git submodules, used as workspaces.
|
|
77
|
+
Clone with `--recurse-submodules`.
|
|
78
|
+
- `tests/`: `bun run test`.
|
|
79
|
+
- `docs/src/*.html`: the docs pages. `bun run docs:build` writes `docs/`,
|
|
80
|
+
typesets the mathematics and runs the code box at the end of every page.
|
|
81
|
+
`docs/*.html` and `docs/assets/finance.js` are build output.
|
|
82
|
+
- `docs/assets/runbox.js` and `scripts/docs-kit.js` are shared with the other
|
|
83
|
+
RatMath docs sites and should be kept in step with them.
|
|
84
|
+
|
|
85
|
+
## Development
|
|
86
|
+
|
|
87
|
+
```sh
|
|
88
|
+
git submodule update --init
|
|
89
|
+
bun install
|
|
90
|
+
bun run test
|
|
91
|
+
bun run docs:build
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
MIT licensed.
|
package/docs/llms.txt
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# @ratmath/finance
|
|
2
|
+
|
|
3
|
+
> The mathematics of finance for RatMath: exact money, time value, loans, bonds, scenarios, uncertain inputs and repeated runs, portfolios, options and life contingencies. Part of the RatMath Shelf; numbers come from @ratmath/core (a peer dependency). ESM: `import * as finance from "@ratmath/finance"`.
|
|
4
|
+
|
|
5
|
+
Built from 0.2.0, commit d4dcfe8. `file:line` is relative to the package root (also node_modules/@ratmath/finance/); on GitHub: https://github.com/ratmath/finance/blob/d4dcfe8/<file>#L<line>. Docs pages are under https://ratmath.com/finance/. Full types: index.d.ts.
|
|
6
|
+
|
|
7
|
+
Types: `type Amount = Rational | bigint | number | string`; `type Certified = Rational | RationalInterval`; `type Rounding = RoundingRule | number | RoundingMode | boolean | "none" | null`; `type DateLike = CalendarDate | string | [number, number, number]`; `type DayCount = "30/360" | "30E/360" | "actual/360" | "actual/365" | "actual/actual"`; `type Flows = Amount[] | { t?: Amount; amount: Amount }[]`; `type DatedFlows = { date: DateLike; amount: Amount }[]`; `type DepreciationMethod = "straight-line" | "declining-balance" | "sum-of-years-digits" | "units-of-production"`; `type When = number | string`
|
|
8
|
+
|
|
9
|
+
## Docs
|
|
10
|
+
|
|
11
|
+
- https://ratmath.com/finance/llms-full.txt: every page below as Markdown, each with a runnable example
|
|
12
|
+
- Pages: index (Overview), reference (Reference), explore (Explore), money (Money and rounding), dates (Dates and day counts), time-value (Time value of money), loans (Loans), cash-flows (Cash flows), bonds (Bonds), yield-curves (Yield curves), scenarios (Scenarios), uncertain (Uncertain inputs and repeated runs), portfolios (Portfolios), options (Options), life (Life contingencies)
|
|
13
|
+
|
|
14
|
+
## API
|
|
15
|
+
|
|
16
|
+
name(params) → result — meaning · file:line · docs page
|
|
17
|
+
|
|
18
|
+
- `plan: readonly PlannedPhase[]` · src/plan.js:5 · index
|
|
19
|
+
- `FinanceError class: code` · src/money.js:8
|
|
20
|
+
- `amount(x: Amount) → Rational` — An exact amount or rate from a whole number, a bigint, a Rational or a string: "1234.56", "1,234.56", "$1,234.56", "7/8", "4.5%" (= 9/200), "-250". · src/money.js:29 · money
|
|
21
|
+
- `rate(x: Amount) → Rational` — A rate: the same reading as `amount`, so "5%" and "0.05" are both 1/20. · src/money.js:51 · time-value
|
|
22
|
+
- `MONEY_ROUNDING: "half-even"` — The rule money is rounded by when none is named: half-even (banker's rounding), the usual default in accounting and financial software because ties do not… · src/money.js:61 · money
|
|
23
|
+
- `moneyRounder(mode?: RoundingMode) → ((x: any, places?: number) => any) & { mode: unknown }` — A Core rounder for a mode: a name from Core's ROUNDING_MODES, "up" or "down" (away from and towards zero), a rounder made by Core's `rounding(...)`, or your… · src/money.js:69 · reference
|
|
24
|
+
- `round(x: Amount, rule?: RoundingRule) → Rational` — Round to a number of decimal places under a rule (MONEY_ROUNDING, so half-even, unless one is named). half-up sends a tie away from zero (the commercial… · src/money.js:84 · money
|
|
25
|
+
- `format(x: Amount, options?: RoundingRule & { currency?: string; separator?: string; percent?: boolean }) → string` — "1,234.50" from an exact amount: rounded for display only, by the rule given · src/money.js:98 · money
|
|
26
|
+
- `allocate(total: Amount, weights: Amount[], options?: { places?: number }) → Rational[]` — Split a total into parts in proportion to weights so that the rounded parts add up to the total exactly: each part is rounded down and the units left over… · src/money.js:116 · money
|
|
27
|
+
- `power(base: Amount, exponent: Amount, digits?: number) → Certified` — base^exponent for a positive rational base. · src/money.js:156
|
|
28
|
+
- `exp(x: Amount | RationalInterval, digits?: number) → RationalInterval` — e^x enclosed for a rational or an interval · src/money.js:148
|
|
29
|
+
- `ln(x: Amount | RationalInterval, digits?: number) → RationalInterval` — ln x enclosed · src/money.js:150
|
|
30
|
+
- `show(x: Certified, places?: number) → string` — An exact number or an interval as a decimal with `places` places. · src/money.js:182 · money
|
|
31
|
+
- `CalendarDate class: year, month, day, serial, isEndOfMonth, addDays, addMonths, compareTo, equals, toString` — A calendar date, with no time of day and no time zone. · src/money.js:213 · dates
|
|
32
|
+
- `date(x: DateLike) → CalendarDate` — A date from "2027-03-15", "2027-03" (the first of the month), [y, m, d] or a CalendarDate. · src/money.js:245 · dates
|
|
33
|
+
- `daysBetween(a: DateLike, b: DateLike) → number` · src/money.js:252 · dates
|
|
34
|
+
- `dayCount(from: DateLike, to: DateLike, convention?: DayCount) → { days: number; yearFraction: Rational }` — Days and the fraction of a year between two dates under a convention: "30/360" (US bond basis), "30E/360" (Eurobond), "actual/360", "actual/365" (fixed) or… · src/money.js:261 · dates
|
|
35
|
+
- `isLeap(year: number) → boolean` · src/money.js:209
|
|
36
|
+
- `DAY_COUNTS: readonly DayCount[]` · src/money.js:254
|
|
37
|
+
- `simpleInterest(principal: Amount, rate: Amount, time: Amount) → { interest: Rational; total: Rational }` — Simple interest: principal·rate·time. { interest, total }. · src/tvm.js:20
|
|
38
|
+
- `compound(principal: Amount, rate: Amount, years: Amount, options?: Digits & { periodsPerYear?: Amount | "continuous" }) → Certified` — What a principal grows to in `years` at a nominal annual rate compounded periodsPerYear times a year, or "continuous". · src/tvm.js:29 · time-value
|
|
39
|
+
- `effectiveRate(nominal: Amount, periodsPerYear?: Amount | "continuous", options?: Digits) → Certified` — The effective annual rate of a nominal rate compounded m times a year (or "continuous"). · src/tvm.js:36 · time-value
|
|
40
|
+
- `nominalRate(effective: Amount, periodsPerYear?: Amount | "continuous", options?: Digits) → Certified` — The nominal annual rate, compounded m times a year (or "continuous"), that has a given effective annual rate. · src/tvm.js:43 · time-value
|
|
41
|
+
- `equivalentRate(nominal: Amount, from: Amount, to: Amount, options?: Digits) → Certified` — A nominal rate compounded `from` times a year restated as one compounded `to` times a year. · src/tvm.js:50 · time-value
|
|
42
|
+
- `realRate(nominal: Amount, inflation: Amount) → Rational` — The real rate behind a nominal rate and an inflation rate (Fisher, exactly): (1 + n)/(1 + π) − 1. · src/tvm.js:55 · time-value
|
|
43
|
+
- `discountFactor(rate: Amount, periods: Amount, options?: Digits) → Certified` — (1 + rate)^−periods · src/tvm.js:58
|
|
44
|
+
- `futureValue(pv: Amount, rate: Amount, periods: Amount, options?: Digits) → Certified` · src/tvm.js:59
|
|
45
|
+
- `presentValue(fv: Amount, rate: Amount, periods: Amount, options?: Digits) → Certified` · src/tvm.js:60
|
|
46
|
+
- `annuity(spec: AnnuitySpec) → { presentValue: Rational; futureValue: Rational; total: Rational; payments: number }` — A level or growing annuity: `periods` payments, the first of `payment`, each later one (1 + growth) times the one before; at the end of each period… · src/tvm.js:71 · time-value
|
|
47
|
+
- `perpetuity(spec: Omit<AnnuitySpec, "periods">) → Rational` — A perpetuity: payments for ever, level or growing at a rate below the interest rate. · src/tvm.js:85
|
|
48
|
+
- `tvm(problem: TvmProblem) → TvmAnswer` — The equation that ties together a present value, a level payment, a future value, a rate per period and a number of periods, pv + pmt·a + fv·(1 + rate)^−n =… · src/tvm.js:102 · time-value
|
|
49
|
+
- `rateRoots(coefficients: Rational[], options?: Digits & { limit?: number }) → SolvedRate[]` — Every rate r > −1 with Σ coeffs[k]·(1 + r)^k = 0, in increasing order: [{ rate, exact, text, multiplicity }]. · src/solve.js:52
|
|
50
|
+
- `loan(spec: LoanSpec) → Loan` — A loan and its schedule. loan({ principal: 250000, rate: "6%", periods: 360 }) `rate` is the nominal annual rate; the rate per period is rate/periodsPerYear. · src/loans.js:35 · loans
|
|
51
|
+
- `levelPayment(balance: Amount, periodicRate: Amount, periods: number, balloon?: Amount) → Rational` — the level payment that takes a balance to `balloon` in n periods at a periodic rate, exactly · src/loans.js:15
|
|
52
|
+
- `compareLoans(a: Loan | LoanSpec, b: Loan | LoanSpec) → { a: LoanSummary; b: LoanSummary; difference: LoanSummary }` — Two loans side by side: payment, number of payments, interest and total paid, and the differences (b − a). · src/loans.js:106 · loans
|
|
53
|
+
- `refinance( current: Omit<LoanSpec, "principal"> & { balance: Amount }, proposed: Omit<LoanSpec, "principal">, options?: { costs?: Amount; rollIn?: boolean; rounding?: Rounding }, ) → { current: Loan; proposed: Loan; costs: …` — Refinancing: keep the current loan (its balance, rate and remaining periods) or replace it with a new one that has costs. · src/loans.js:117 · loans
|
|
54
|
+
- `revolving(spec: { balance: Amount; rate: Amount; periodsPerYear?: Amount; payment: Amount | { percent?: Amount; minimum?: Amount }; purchases?: Amount | ((period: number) => Amount | undefined); rounding?: Rounding …` — Revolving credit: interest on the balance each period, then a payment that is a fixed amount or { percent, minimum } of the balance, then any new purchases. · src/loans.js:139 · loans
|
|
55
|
+
- `loanAPR(spec: Digits & { principal: Amount; fees?: Amount; payment: Amount; periods: number; periodsPerYear?: Amount; balloon?: Amount }) → { periodic: Certified; nominal: Certified; effective: Certified; exact: boolean }` — The rate a borrower really pays once fees are counted: the borrower receives principal − fees and makes the payments. { periodic, nominal (the APR: periodic… · src/loans.js:172 · loans
|
|
56
|
+
- `npv(rate: Amount, flows: Flows, options?: Digits) → Certified` — Net present value at a rate per period. · src/cashflow.js:41 · cash-flows
|
|
57
|
+
- `xnpv(rate: Amount, flows: DatedFlows, options?: Digits & { dayCount?: DayCount }) → Certified` — Net present value of dated flows at an annual rate, time measured from the first date by a day-count convention. · src/cashflow.js:47 · dates
|
|
58
|
+
- `irr(flows: Flows, options?: Digits) → RatesOfReturn` — Every internal rate of return of a list of amounts at times 0, 1, 2, …: each rate above −100% at which the net present value is zero. { rates: [{ rate,… · src/cashflow.js:58 · cash-flows
|
|
59
|
+
- `xirr(flows: DatedFlows, options?: Digits & { dayCount?: DayCount; range?: [Amount, Amount] }) → Omit<RatesOfReturn, "rates"> & { rates: { rate: Certified; exact: boolean; text: string; proven: boolean }[]; formula?: string }` — Every internal rate of return of dated flows, as an annual rate with time from the first date by a day-count convention. · src/cashflow.js:78 · dates
|
|
60
|
+
- `mirr(flows: Amount[], financeRate: Amount, reinvestRate: Amount, options?: Digits) → Certified` — The modified internal rate of return: money out is financed at one rate and money in is reinvested at another, which gives a single answer: (FV of inflows /… · src/cashflow.js:98 · cash-flows
|
|
61
|
+
- `payback(flows: Amount[], options?: { rate?: Amount }) → { period: number | null; fractional: Rational | null; cumulative: Rational[] }` — When the money comes back. { period: the first whole period at which the running total is no longer negative (null if never), fractional: the same with the… · src/cashflow.js:118 · cash-flows
|
|
62
|
+
- `realValue(nominal: Amount, inflation: Amount, periods: Amount, options?: Digits) → Certified` — What a nominal amount `periods` from now is worth in today's money: amount/(1 + inflation)^periods. · src/cashflow.js:138 · cash-flows
|
|
63
|
+
- `nominalValue(real: Amount, inflation: Amount, periods: Amount, options?: Digits) → Certified` — What today's amount becomes after `periods` of inflation: amount·(1 + inflation)^periods. · src/cashflow.js:140 · cash-flows
|
|
64
|
+
- `depreciation(spec: { cost: Amount; salvage?: Amount; life?: number; method?: DepreciationMethod; /** Declining balance: the rate is factor/life (default 2). */ factor?: Amount; switchToStraightLine?: boolean; units?: Amount[] …` — A depreciation schedule: [{ period, depreciation, accumulated, bookValue }]. · src/cashflow.js:151 · cash-flows
|
|
65
|
+
- `DEPRECIATION: readonly DepreciationMethod[]` · src/cashflow.js:142
|
|
66
|
+
- `taxSchedule(brackets: { upTo?: Amount | null; rate: Amount }[], options?: { rounding?: Rounding }) → { brackets: { upTo: Rational | null; rate: Rational }[]; on(income: Amount): TaxResult }` — A tax, or any charge, given as brackets: [{ upTo, rate }, …] in increasing order, the last with no upTo. · src/cashflow.js:186 · cash-flows
|
|
67
|
+
- `Bond class: face, coupon, frequency, redemption, couponAmount, periods, accrued, accruedDays, first, settlement, maturity, cashflows, price, yield, duration` · src/bonds.js:18
|
|
68
|
+
- `bond(spec: BondSpec | Bond) → Bond` · src/bonds.js:128 · bonds
|
|
69
|
+
- `YieldCurve class: discountFactors, frequency, periods, discount, spot, forward, parYield, price, spots, forwards` — A curve of discount factors d_1, d_2, … for whole periods (`frequency` periods a year), with the spot and forward rates they imply. · src/bonds.js:134
|
|
70
|
+
- `yieldCurve(spec: { spots?: Amount[]; discountFactors?: Amount[]; frequency?: number }) → YieldCurve` — A curve from spot rates (nominal annual, compounded `frequency` times a year) for 1, 2, 3, … periods, or from discount factors. · src/bonds.js:181 · yield-curves
|
|
71
|
+
- `bootstrap(bonds: (BondSpec & { price: Amount })[], options?: { frequency?: number }) → YieldCurve` — Bootstrapping: discount factors from the prices of bonds maturing in 1, 2, 3, … periods, one for each, each bond's earlier coupons valued with the factors… · src/bonds.js:191 · yield-curves
|
|
72
|
+
- `immunise(problem: { liability: { amount: Amount; time: Amount }; yield: Amount; bonds: [BondSpec | Bond, BondSpec | Bond] }) → { presentValue: Rational; weights: [Rational, Rational]; amounts: [Rational, Rational]; units: …` — Immunisation: split the money for a single liability between two bonds so that, at the going yield, the assets have the liability's present value and its… · src/bonds.js:210 · yield-curves
|
|
73
|
+
- `Scenario class: periods, periodsPerYear, project` · src/scenario.js:75
|
|
74
|
+
- `scenario(spec: ScenarioSpec | Scenario) → Scenario` · src/scenario.js:189 · scenarios
|
|
75
|
+
- `compare( scenarios: Record<string, ScenarioSpec | Scenario>, options?: { measure?: (p: Projection) => Rational }, ) → { rows: { name: string; outcome: Rational; netWorth: Rational; difference: Rational; firstNegative: …` — Scenarios side by side: compare({ rent: {...}, buy: {...} }). { rows: [{ name, netWorth, difference (from the first), minimum }], best, series (net worth by… · src/scenario.js:198 · scenarios
|
|
76
|
+
- `sensitivity( build: (inputs: Record<K, Dual>) => ScenarioSpec | Scenario, inputs: Record<K, Amount>, options?: { measure?: (p: Projection) => Rational | Dual }, ) → { base: Rational; rows: { input: K; value: Rational; derivative: …` — Which input moves the outcome most. · src/scenario.js:231 · scenarios
|
|
77
|
+
- `Dual class: v, d, add, subtract, multiply, divide, negate, pow, compareTo, toString` — A value together with its derivative with respect to one chosen input. · src/scenario.js:10
|
|
78
|
+
- `Process class: name, kind, path, rates` · src/uncertain.js:46
|
|
79
|
+
- `processes: { fixed(rate: Amount): Process; independent(dist: Sampler): Process; /** Annual returns from a finite list with exact weights: small cases can be enumerated exactly. */ choice(values: Amount[], weights?: Amount[]): …` · src/uncertain.js:81 · uncertain
|
|
80
|
+
- `simulate( spec: ScenarioSpec, options?: { returns?: Record<string, Process>; inflation?: Process | null; indexed?: string[]; events?: RandomEvent[]; runs?: number; seed?: unknown; rounding?: Rounding; measure?: (p: Projection) …` — Many runs of a scenario with uncertain inputs. simulate(spec, { returns: { stocks: processes.gbm({ drift: "6%", volatility: "18%" }) }, inflation:… · src/uncertain.js:290 · uncertain
|
|
81
|
+
- `Simulation class: kind, name, seed, runs, rounding, outcomes, sorted, mean, standardError, percentiles, ruin, ruinTimes, bands, real, quantile` · src/uncertain.js:239
|
|
82
|
+
- `sequenceRisk( spec: ScenarioSpec, options: { account: string; returns: Amount[]; shuffles?: number; seed?: unknown; measure?: (p: Projection) => Rational }, ) → { rows: { order: string; returns: Rational[]; outcome: Rational …` — The order of good and bad years. · src/uncertain.js:368 · uncertain
|
|
83
|
+
- `Portfolio class: names, means, covariance, expectedReturn, variance, risk, constants, minimumVariance, tangency` · src/portfolio.js:59
|
|
84
|
+
- `portfolio(spec: ConstructorParameters<typeof Portfolio>[0]) → Portfolio` · src/portfolio.js:207 · portfolios
|
|
85
|
+
- `returnsFrom(prices: Amount[]) → Rational[]` — Simple returns p[k+1]/p[k] − 1 from a list of prices; exact. · src/portfolio.js:45 · portfolios
|
|
86
|
+
- `capm(spec: { asset: Amount[]; market: Amount[]; riskFree?: Amount; marketReturn?: Amount | null }) → { beta: Rational; alpha: Rational; required: Rational; marketPremium: Rational; riskFree: Rational }` — The capital asset pricing model from returns: β = cov(asset, market) / var(market), α = mean(asset) − (r + β·(mean(market) − r)), and the required return r… · src/portfolio.js:214 · portfolios
|
|
87
|
+
- `solveExact(M: Rational[][], b: Rational[]) → Rational[] | null` — Solve M x = b exactly (Gauss–Jordan over the rationals); null when M is singular. · src/portfolio.js:26
|
|
88
|
+
- `strategy(legs: Leg[]) → { legs: Leg[]; cost: Rational; payoff(spot: Amount): Rational; profit(spot: Amount): Rational; kinks: Rational[]; breakEvens: Rational[]; maxProfit: Rational | null; maxLoss: Rational | null; }` — A strategy: legs { type: "call" | "put" | "stock" | "bond", strike (for an option; the face for a bond), premium (what one unit cost; default 0), quantity… · src/options.js:29 · options
|
|
89
|
+
- `parity(spec: { call?: Amount | RationalInterval; put?: Amount | RationalInterval; spot?: Amount | RationalInterval; strike?: Amount; rate: Amount; time: Amount; compounding?: "continuous" | "annual"; bits?: number }) → { …` — Put–call parity C − P = S − K·DF for European options on a stock without dividends. · src/options.js:83 · options
|
|
90
|
+
- `binomialTree(spec: { spot: Amount; strike: Amount; steps: number; type?: "call" | "put"; style?: "european" | "american"; up?: Amount; down?: Amount; growth?: Amount; volatility?: Amount; time?: Amount; rate?: Amount; places?: …` — Price an option on a recombining binomial tree, exactly. { spot, strike, steps, type: "call" | "put", style: "european" | "american", up, down, growth }:… · src/options.js:115 · options
|
|
91
|
+
- `blackScholes(spec: { spot: Amount; strike: Amount; rate: Amount; volatility: Amount; time: Amount; dividendYield?: Amount; bits?: number }) → { call: RationalInterval; put: RationalInterval; d1: RationalInterval; d2: …` — European option values under Black–Scholes with continuous compounding: { spot, strike, rate, volatility, time, dividendYield = 0 }. · src/options.js:216 · options
|
|
92
|
+
- `impliedVolatility(spec: { price: Amount; type?: "call" | "put"; spot: Amount; strike: Amount; rate: Amount; time: Amount; dividendYield?: Amount; digits?: number; bits?: number }) → RationalInterval` — The volatility at which Black–Scholes gives a stated price, enclosed to `digits` digits. · src/options.js:261 · options
|
|
93
|
+
- `normalCdf(x: Amount | RationalInterval, bits?: number) → RationalInterval` — the standard normal distribution function, enclosed: (1 + erf(x/√2))/2 · src/options.js:198
|
|
94
|
+
- `normalPdf(x: Amount | RationalInterval, bits?: number) → RationalInterval` — the standard normal density, enclosed · src/options.js:200
|
|
95
|
+
- `LifeTable class: startAge, lastAge, lives, l, d, p, q, deferredQ, curtateExpectation, completeExpectation, rows` · src/life.js:10
|
|
96
|
+
- `lifeTable(spec: ConstructorParameters<typeof LifeTable>[0]) → LifeTable` · src/life.js:80 · life
|
|
97
|
+
- `deMoivre(omega: number, options?: { startAge?: number }) → LifeTable` — de Moivre's law: l_x = ω − x, so deaths are uniform up to the limiting age ω. · src/life.js:82 · life
|
|
98
|
+
- `lifeAnnuity(table: LifeTable, spec: { age: number; rate: Amount; term?: number | null; due?: boolean; deferred?: number }) → Rational` — Life annuity of 1 a year for a life aged x: due (payments at the start of each year, ä) or immediate (at the end, a), for `term` years (default for life),… · src/life.js:99 · life
|
|
99
|
+
- `lifeInsurance(table: LifeTable, spec: { age: number; rate: Amount; term?: number | null; deferred?: number }) → Rational` — Life insurance of 1 paid at the end of the year of death, for a life aged x: whole life (term null) or for `term` years, after `deferred` years. · src/life.js:114 · life
|
|
100
|
+
- `pureEndowment(table: LifeTable, spec: { age: number; rate: Amount; term: number }) → Rational` — pure endowment nEx = v^n · nPx: 1 paid at time n if the life is alive · src/life.js:125
|
|
101
|
+
- `endowment(table: LifeTable, spec: { age: number; rate: Amount; term: number }) → Rational` — endowment insurance: term insurance plus the pure endowment · src/life.js:127 · life
|
|
102
|
+
- `netPremium(table: LifeTable, spec: { kind?: PolicyKind; benefit?: Amount; age: number; rate: Amount; term?: number | null; payments?: number | null }) → Rational` — The level annual net premium (paid at the start of each year while alive, for `payments` years) for a benefit: { kind: "whole life" | "term" | "endowment",… · src/life.js:138 · life
|
|
103
|
+
- `reserve(table: LifeTable, spec: { kind?: PolicyKind; benefit?: Amount; age: number; rate: Amount; term?: number | null; payments?: number | null; time: number }) → Rational` — The prospective net reserve after t years: the value then of the benefit still to come less the value of the premiums still to come. · src/life.js:150 · life
|
|
104
|
+
|
|
105
|
+
## Example
|
|
106
|
+
|
|
107
|
+
```js
|
|
108
|
+
import { plan, amount, format, show, loan, irr, bond } from "@ratmath/finance";
|
|
109
|
+
const l = loan({ principal: 250000, rate: "6%", periods: 360 });
|
|
110
|
+
console.log("payment", show(l.payment, 2), " exactly", show(l.exactPayment, 8), "before rounding");
|
|
111
|
+
console.log("last payment", show(l.finalPayment, 2), " total interest", format(l.totals.interest));
|
|
112
|
+
console.log("in floating point, 0.1 + 0.2 =", 0.1 + 0.2, "; here:", String(amount("0.1").add(amount("0.2"))));
|
|
113
|
+
const two = irr([-1000, 2300, -1320]);
|
|
114
|
+
console.log("rates of return of −1000, +2300, −1320:", two.rates.map((r) => r.text).join(" and "), "—", two.note);
|
|
115
|
+
const b = bond({ coupon: "5%", periods: 20 });
|
|
116
|
+
console.log("bond at a 6% yield:", show(b.price("6%").clean, 6), " duration", show(b.duration("6%").macaulay, 4), "years");
|
|
117
|
+
plan.map((p) => `${p.phase}. ${p.contents}`)
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## More
|
|
121
|
+
|
|
122
|
+
- tests/: worked examples for every function
|
|
123
|
+
- https://ratmath.com/core/ (numbers), https://ratmath.com/shelf/ (all the libraries)
|