@ratmath/finance

Money that adds up

An amount of money is a fraction with a small denominator, and a computer that stores it as a binary floating-point number gets it slightly wrong from the first step. Here amounts are exact rationals. Rounding happens only where a rule you can name says so; a rate found by solving an equation is proven, and when a cash flow has two rates of return you are told both.

What is here

A first program

import { loan, irr, bond, scenario, compare, round, show } from "@ratmath/finance";

const l = loan({ principal: 250000, rate: "6%", periods: 360 });
show(l.payment, 2);            // "1498.88"
show(l.finalPayment, 2);       // "1495.22": the last payment clears the balance, visibly
show(l.totals.interest, 2);    // "289593.14", the sum of 360 rows, to the cent

irr([-1000, 2300, -1320]).rates.map((r) => r.text);   // ["1/10", "1/5"]: two rates, both reported

const b = bond({ coupon: "5%", periods: 20 });
show(b.price("6%").clean, 6);  // "92.561263"
b.duration("6%").macaulay;     // an exact fraction

round("2.345");                          // 2.34 (half-even, the default)
round("2.345", { mode: "half-up" });     // 2.35

Three kinds of answer

Exact. Anything that is arithmetic on amounts and rates over whole periods: payments, schedules, present values, bond prices on coupon dates, durations, discount factors, projections. These are Core Rationals.

Certified. Anything that needs a root or an exponential: a yield, a rate of return, continuous compounding, a fractional period. These come back as a Rational when the answer happens to be rational (a loan's rate of 1/200 a month is found as exactly that) and otherwise as a RationalInterval proven to contain the answer, as narrow as you ask with digits.

Simulated. The results of seeded repeated runs (uncertain inputs). Each carries its seed, so it can be repeated exactly, and its own sampling error: a chance of running out comes with an exact interval for the true probability.

Rounded. Only where you say, by a rule with a name: round(x, { places, mode }). show(x, places) prints either kind; for an interval it prints the correctly rounded value when both ends round to it.

Inputs are whole numbers or strings: "1234.56", "$1,234.56", "7/8", "4.5%". A JavaScript number that is not whole is refused, since 0.1 is not one tenth.

What it is not

No market data, no tax tables and no advice are built in. You supply the numbers; the library does the arithmetic and tells you how sure it is.

Still to come

Pictures: balance and amortisation charts, percentile bands, yield curves and option payoffs, in the graphics library. The plan export lists the phases, from the library roadmap, and the RatMath Shelf page lists what exists across all the libraries.

Try itEdit the code and run it with @ratmath/finance and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs