@aman050807/cashflow-lens 0.1.0 → 0.3.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 CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  Changes follow semantic versioning. Dates are actual release dates.
4
4
 
5
+ ## 0.2.0 - 2026-11-19
6
+
7
+ Backward-compatible additions; all calculations are unchanged.
8
+
9
+ - `formatMoney` and `formatRate` display helpers built on `Intl.NumberFormat`,
10
+ including Indian locale grouping (`en-IN`). Display only: calculations stay
11
+ unrounded IEEE-754 numbers.
12
+ - Marked the package as side-effect free (`"sideEffects": false`) so bundlers
13
+ can drop unimported functions.
14
+ - Expanded editor hover documentation: full JSDoc with examples in the
15
+ TypeScript declarations.
16
+ - CI, npm version, bundle size and license badges in the README.
17
+ - Browser playground added to the companion demo repository.
18
+
5
19
  ## 0.1.0 - 2026-11-16
6
20
 
7
21
  Initial development release.
@@ -13,3 +27,10 @@ Initial development release.
13
27
  - Unit tests and Node.js 20/22/24 CI workflow.
14
28
 
15
29
  The model is educational. It does not calculate IRR, taxes, debt or investment risk.
30
+
31
+ ## 0.3.0 (2026-11-22)
32
+
33
+ - Add strict annual timeline projection, year-specific overrides and formula trace.
34
+ - Add NPV, same-horizon/discount comparison, deterministic stress and sensitivity grid.
35
+ - Add TypeScript types and numerical, validation and regression tests.
36
+ - Keep the original API unchanged. No IRR/XIRR, market feeds or accounting precision claims.
package/README.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # cashflow-lens
2
2
 
3
+ [![CI](https://github.com/aman050807/cashflow-lens/actions/workflows/test.yml/badge.svg)](https://github.com/aman050807/cashflow-lens/actions/workflows/test.yml)
4
+ [![npm version](https://img.shields.io/npm/v/@aman050807/cashflow-lens.svg)](https://www.npmjs.com/package/@aman050807/cashflow-lens)
5
+ [![minzipped size](https://img.shields.io/bundlephobia/minzip/@aman050807/cashflow-lens)](https://bundlephobia.com/package/@aman050807/cashflow-lens)
6
+ [![license](https://img.shields.io/npm/l/@aman050807/cashflow-lens)](https://github.com/aman050807/cashflow-lens/blob/main/LICENSE)
7
+
3
8
  Compare cashflow scenarios without mixing rental income with capital growth.
4
9
  A dependency-free JavaScript/Node.js library with CommonJS, ESM named imports,
5
10
  TypeScript declarations and strict runtime validation.
@@ -112,6 +117,36 @@ Returned fields:
112
117
  Accepts an array of the options above plus a unique `id`. Returns ranked projection
113
118
  objects. Duplicate ids throw `RangeError`; missing/blank/non-string ids throw `TypeError`.
114
119
 
120
+ ### `formatMoney(amount, options)`
121
+
122
+ Formats a money amount for display with `Intl.NumberFormat`. `options.currency`
123
+ is required (3-letter ISO 4217 code); `options.locale` defaults to `en-US`.
124
+ Use `en-IN` for Indian digit grouping.
125
+
126
+ ```js
127
+ formatMoney(100000, { locale: 'en-IN', currency: 'INR' }); // "₹1,00,000.00"
128
+ formatMoney(1000, { locale: 'en-US', currency: 'USD' }); // "$1,000.00"
129
+ ```
130
+
131
+ ### `formatRate(rate, options)`
132
+
133
+ Formats a decimal rate as a percentage. `options.maximumFractionDigits`
134
+ defaults to `2` (integer 0-20); `options.locale` defaults to `en-US`.
135
+
136
+ ```js
137
+ formatRate(0.06); // "6%"
138
+ formatRate(0.03945); // "3.95%"
139
+ ```
140
+
141
+ Both helpers are **display only**. They format output for humans; every
142
+ calculation stays an unrounded IEEE-754 number exactly as documented above.
143
+ They change nothing about financial accuracy and are never used internally.
144
+
145
+ ## Browser playground
146
+
147
+ A zero-build playground that ranks scenarios against the published package
148
+ lives in the demo repo: [cashflow-lens-demo/playground](https://github.com/aman050807/cashflow-lens-demo/tree/main/playground).
149
+
115
150
  ## Model assumptions and limits
116
151
 
117
152
  - Initial investment equals initial asset value. Acquisition costs are not modeled.
@@ -138,8 +173,8 @@ npm pack --dry-run
138
173
  ```
139
174
 
140
175
  Tests cover hand-calculated examples, losses, zero final values, fractional years,
141
- invalid input, overflow, stable sorting, scale invariance, non-mutation and both
142
- module loading styles. CI runs on Node.js 20, 22 and 24.
176
+ invalid input, overflow, stable sorting, scale invariance, non-mutation, display
177
+ formatting and both module loading styles. CI runs on Node.js 20, 22 and 24.
143
178
 
144
179
  ## Versioning
145
180
 
@@ -150,3 +185,95 @@ contracts. See [CHANGELOG.md](CHANGELOG.md).
150
185
  ## License
151
186
 
152
187
  MIT. See [LICENSE](LICENSE).
188
+
189
+ ## Analysis engine (0.3.0)
190
+
191
+ This additive API models **whole years, 1 to 50**, with an explicit cashflow schedule,
192
+ NPV, formula trace, deterministic shocks and sensitivity analysis. The original
193
+ `projectScenario` and `compareScenarios` contracts are unchanged, including their
194
+ support for fractional years. The new API deliberately does not infer dates.
195
+
196
+ ```js
197
+ const { projectTimeline, stressTest, compareTimelines, sensitivityGrid, npv }
198
+ = require('@aman050807/cashflow-lens');
199
+ const input = {
200
+ id: 'example', initialInvestment: 1000, annualIncome: 100,
201
+ annualExpenses: 20, annualGrowthRate: 0.1, years: 2,
202
+ exitFeeRate: 0.1, discountRate: 0.1,
203
+ incomeGrowthRate: 0, expenseGrowthRate: 0, overrides: []
204
+ };
205
+ const report = projectTimeline(input);
206
+ console.log(report.cashflows); // [-1000, 80, 1169] (floating-point tolerances apply)
207
+ console.log(report.summary.netProfit); // approximately 249
208
+ console.log(report.summary.netPresentValue); // approximately 38.842975
209
+ console.log(report.rows[1].trace); // formula IDs, exponents and terminal-year marker
210
+ const stress = stressTest(input, {growthDelta: -0.02, expenseMultiplier: 1.2});
211
+ ```
212
+
213
+ ### Input and validation
214
+
215
+ `normalizeScenario(input)` validates and clones the input, sorts override rows by year,
216
+ and fills defaults. Fields from `Scenario` retain their meanings. `id` defaults to
217
+ `'scenario'`. `incomeGrowthRate` and `expenseGrowthRate` default to 0 and must be at
218
+ least -1. `discountRate` defaults to 0.08 and must be greater than -1.
219
+ `years` must be an integer from 1 to 50. Unknown fields are rejected to catch typos.
220
+ All numbers must be finite numbers, never numeric strings. Overflow throws.
221
+
222
+ `overrides` is an optional array of `{year, income?, expenses?}`. Each year must be a
223
+ unique integer within the horizon. At least one override amount is required, and
224
+ amounts must be non-negative. An override replaces that year's amount only; the
225
+ next year returns to the original growth path. It does not reset the growth base.
226
+ Inputs and override records are not mutated or retained by reference.
227
+
228
+ ### Cashflow timing and formulas
229
+
230
+ - Initial capital is a negative cashflow at t=0.
231
+ - Year t income = annualIncome × (1 + incomeGrowthRate)^(t−1), unless overridden.
232
+ - Year t expenses = annualExpenses × (1 + expenseGrowthRate)^(t−1), unless overridden.
233
+ - Asset value = initialInvestment × (1 + annualGrowthRate)^t.
234
+ - Only the final year includes a sale: asset value × (1 − exitFeeRate).
235
+ - Cashflow = income − expenses + final-year net sale.
236
+ - Present value = cashflow / (1 + discountRate)^t.
237
+ - NPV = −initialInvestment + sum of yearly present values.
238
+ - Net profit = sum of all cashflows, including the negative initial capital.
239
+ - Payback is the **first non-negative year-end cumulative cashflow**, including
240
+ any final sale. Later negative cashflows can reverse this. No interpolation is used.
241
+ Discounted payback applies the same rule to discounted cashflows. `null` means not reached.
242
+
243
+ `npv(rate, cashflows)` also accepts a standalone non-empty array where index 0
244
+ is t=0. It supports negative flows and negative rates greater than -1.
245
+
246
+ ### Comparison, stress and sensitivity
247
+
248
+ `compareTimelines(inputs, metric = 'netPresentValue')` accepts `netPresentValue`,
249
+ `netProfit`, or `totalReturnRate`. It requires unique ids, identical whole-year
250
+ horizons and identical discount rates. Equal values retain input order. Empty
251
+ input returns `[]`. The caller must still ensure the same currency and units.
252
+ Absolute NPV comparisons at different initial investments are not capital-efficiency
253
+ rankings, and no metric accounts for risk or suitability.
254
+
255
+ `stressTest(input, {growthDelta = -0.02, expenseMultiplier = 1.2})` returns a base
256
+ and stressed analysis plus the explicit shock values. Growth delta changes asset
257
+ growth only. The expense multiplier scales both modeled annual expenses and any
258
+ explicit expense overrides; it does not change income. An invalid resulting growth
259
+ rate throws instead of silently clamping. These are assumptions, not probability estimates.
260
+
261
+ `sensitivityGrid(input, growthRates, expenseMultipliers)` returns rows by expense
262
+ multiplier, columns by absolute asset growth rate. Each cell contains the two axis
263
+ values and an NPV computed by the same engine. Each axis needs 1 to 25 values.
264
+ The demo floors its display-axis growth scenarios at -100% and labels that choice.
265
+
266
+ ### Trace and export contract
267
+
268
+ `projectTimeline` returns `{schema, assumptions, timing, cashflows, rows, summary}`.
269
+ Schema is `cashflow-lens.analysis/v1`. Each row contains modeled monetary values,
270
+ a discount factor, present value, cumulative totals and `trace` with formula IDs
271
+ (`income.compound`, `income.override`, `expenses.compound`, `expenses.override`),
272
+ exponents and the terminal-year marker. There is no timestamp or randomness;
273
+ the same input and package version produces the same numerical result in the
274
+ same JavaScript environment. Display rounding never feeds back into calculations.
275
+
276
+ Not modeled: taxes, debt, FX, inflation adjustment, reinvestment, dated irregular
277
+ cashflows, IRR/XIRR, stochastic risk or live prices. These standard financial
278
+ formulas are not novel inventions. The reusable validation, scenario workflow,
279
+ trace and tests are the engineering contribution. Demand has not been established.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aman050807/cashflow-lens",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Pure, dependency-free cashflow and investment scenario calculations with explicit assumptions.",
5
5
  "main": "./src/index.js",
6
6
  "types": "./src/index.d.ts",
@@ -10,6 +10,7 @@
10
10
  "default": "./src/index.js"
11
11
  }
12
12
  },
13
+ "sideEffects": false,
13
14
  "files": [
14
15
  "src",
15
16
  "README.md",
@@ -0,0 +1,100 @@
1
+ 'use strict';
2
+ // All periods are whole years. Cashflows occur at year end; period zero is capital paid.
3
+ const SCHEMA = 'cashflow-lens.analysis/v1';
4
+ const allowed = new Set(['id','initialInvestment','annualIncome','annualExpenses','annualGrowthRate','incomeGrowthRate','expenseGrowthRate','years','exitFeeRate','discountRate','overrides']);
5
+ function number(value, name, min = -Infinity, max = Infinity) {
6
+ if (typeof value !== 'number' || !Number.isFinite(value)) throw new TypeError(`${name} must be a finite number`);
7
+ if (value < min || value > max) throw new RangeError(`${name} must be between ${min} and ${max}`);
8
+ return value;
9
+ }
10
+ function finite(value) { if (!Number.isFinite(value)) throw new RangeError('calculation exceeds finite number range'); return value; }
11
+ function object(value, name) { if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError(`${name} must be an object`); }
12
+ function normalizeScenario(input) {
13
+ object(input, 'scenario');
14
+ for (const key of Object.keys(input)) if (!allowed.has(key)) throw new TypeError(`Unknown scenario field: ${key}`);
15
+ const s = { id: 'scenario', annualExpenses: 0, annualGrowthRate: 0, incomeGrowthRate: 0, expenseGrowthRate: 0, exitFeeRate: 0, discountRate: 0.08, overrides: [], ...input };
16
+ if (typeof s.id !== 'string' || !s.id.trim()) throw new TypeError('id must be a non-empty string');
17
+ number(s.initialInvestment, 'initialInvestment', Number.MIN_VALUE);
18
+ number(s.annualIncome, 'annualIncome', 0); number(s.annualExpenses, 'annualExpenses', 0);
19
+ for (const key of ['annualGrowthRate','incomeGrowthRate','expenseGrowthRate']) number(s[key], key, -1);
20
+ number(s.exitFeeRate, 'exitFeeRate', 0, 1); number(s.discountRate, 'discountRate', -1);
21
+ if (s.discountRate === -1) throw new RangeError('discountRate must be greater than -1');
22
+ number(s.years, 'years', 1, 50); if (!Number.isInteger(s.years)) throw new RangeError('years must be an integer from 1 to 50');
23
+ if (!Array.isArray(s.overrides)) throw new TypeError('overrides must be an array');
24
+ const seen = new Set();
25
+ s.overrides = Array.from(s.overrides, (row) => {
26
+ object(row, 'override');
27
+ for (const key of Object.keys(row)) if (!['year','income','expenses'].includes(key)) throw new TypeError(`Unknown override field: ${key}`);
28
+ number(row.year, 'override.year', 1, s.years);
29
+ if (!Number.isInteger(row.year) || seen.has(row.year)) throw new RangeError('override years must be unique integers within the horizon');
30
+ seen.add(row.year);
31
+ if (row.income === undefined && row.expenses === undefined) throw new TypeError('override needs income or expenses');
32
+ const copy = { year: row.year };
33
+ for (const key of ['income','expenses']) if (row[key] !== undefined) copy[key] = number(row[key], `override.${key}`, 0);
34
+ return copy;
35
+ }).sort((a,b) => a.year - b.year);
36
+ return s;
37
+ }
38
+ function npv(rate, cashflows) {
39
+ number(rate, 'rate', -1); if (rate === -1) throw new RangeError('rate must be greater than -1');
40
+ if (!Array.isArray(cashflows) || !cashflows.length) throw new TypeError('cashflows must be a non-empty array');
41
+ let sum = 0;
42
+ for (let t=0; t<cashflows.length; t++) sum = finite(sum + finite(number(cashflows[t], `cashflows[${t}]`) / Math.pow(1+rate,t)));
43
+ return sum;
44
+ }
45
+ function projectTimeline(input) {
46
+ const s = normalizeScenario(input);
47
+ const rows = [];
48
+ let cumulative = -s.initialInvestment, discountedCumulative = cumulative;
49
+ const cashflows = [-s.initialInvestment];
50
+ for (let year=1; year<=s.years; year++) {
51
+ const override = s.overrides.find(x => x.year === year) || {};
52
+ const modeledIncome = finite(s.annualIncome * Math.pow(1+s.incomeGrowthRate, year-1));
53
+ const modeledExpenses = finite(s.annualExpenses * Math.pow(1+s.expenseGrowthRate, year-1));
54
+ const income = override.income === undefined ? modeledIncome : override.income;
55
+ const expenses = override.expenses === undefined ? modeledExpenses : override.expenses;
56
+ const assetValue = finite(s.initialInvestment * Math.pow(1+s.annualGrowthRate, year));
57
+ const exitFee = year === s.years ? finite(assetValue * s.exitFeeRate) : 0;
58
+ const saleProceeds = year === s.years ? finite(assetValue-exitFee) : 0;
59
+ const operatingCashflow = finite(income-expenses);
60
+ const cashflow = finite(operatingCashflow+saleProceeds);
61
+ const discountFactor = finite(1/Math.pow(1+s.discountRate, year));
62
+ const presentValue = finite(cashflow*discountFactor);
63
+ cumulative = finite(cumulative+cashflow); discountedCumulative = finite(discountedCumulative+presentValue);
64
+ cashflows.push(cashflow);
65
+ rows.push({year,income,expenses,assetValue,exitFee,saleProceeds,operatingCashflow,cashflow,discountFactor,presentValue,cumulative,discountedCumulative,
66
+ trace:{income:override.income === undefined ? 'income.compound' : 'income.override', expenses:override.expenses === undefined ? 'expenses.compound' : 'expenses.override', cashflow:'income - expenses + saleProceeds', presentValue:'cashflow / (1 + discountRate)^year', incomeExponent:year-1, assetExponent:year, terminal:year===s.years}});
67
+ }
68
+ const netPresentValue = npv(s.discountRate,cashflows);
69
+ return {schema:SCHEMA, assumptions:s, timing:'initial capital at t=0; income, expenses and sale at year end; no reinvestment',cashflows,rows,
70
+ summary:{netProfit:cumulative,totalReturnRate:finite(cumulative/s.initialInvestment),netPresentValue,operatingIncome:finite(rows.reduce((v,r)=>v+r.operatingCashflow,0)),terminalProceeds:rows.at(-1).saleProceeds,
71
+ paybackYear:rows.find(r=>r.cumulative>=0)?.year ?? null,discountedPaybackYear:rows.find(r=>r.discountedCumulative>=0)?.year ?? null}};
72
+ }
73
+ function compareTimelines(scenarios, metric='netPresentValue') {
74
+ if (!Array.isArray(scenarios)) throw new TypeError('scenarios must be an array');
75
+ if (!['netPresentValue','netProfit','totalReturnRate'].includes(metric)) throw new RangeError('unsupported ranking metric');
76
+ const results = Array.from(scenarios, projectTimeline), ids = new Set();
77
+ for (const r of results) {
78
+ if (ids.has(r.assumptions.id)) throw new RangeError('scenario ids must be unique'); ids.add(r.assumptions.id);
79
+ if (r.assumptions.years !== results[0].assumptions.years || r.assumptions.discountRate !== results[0].assumptions.discountRate) throw new RangeError('comparison needs the same horizon and discount rate');
80
+ }
81
+ return results.sort((a,b)=>b.summary[metric]-a.summary[metric]);
82
+ }
83
+ function stressTest(input, shocks={}) {
84
+ object(shocks,'shocks');
85
+ for (const k of Object.keys(shocks)) if (!['growthDelta','expenseMultiplier'].includes(k)) throw new TypeError(`Unknown shock: ${k}`);
86
+ const s=normalizeScenario(input), growthDelta=number(shocks.growthDelta ?? -0.02,'growthDelta'), expenseMultiplier=number(shocks.expenseMultiplier ?? 1.2,'expenseMultiplier',0);
87
+ const adjusted={...s,id:`${s.id}-stress`,annualGrowthRate:s.annualGrowthRate+growthDelta,annualExpenses:finite(s.annualExpenses*expenseMultiplier),overrides:s.overrides.map(r=>({...r,...(r.expenses===undefined?{}:{expenses:finite(r.expenses*expenseMultiplier)})}))};
88
+ return {base:projectTimeline(s),stressed:projectTimeline(adjusted),shocks:{growthDelta,expenseMultiplier}};
89
+ }
90
+ function sensitivityGrid(input, growthRates, expenseMultipliers) {
91
+ const s=normalizeScenario(input);
92
+ for (const values of [growthRates,expenseMultipliers]) if(!Array.isArray(values)||!values.length||values.length>25) throw new RangeError('grid axes need 1 to 25 values');
93
+ return Array.from(expenseMultipliers, multiplier => Array.from(growthRates, growth => ({growthRate:number(growth,'growthRate',-1),expenseMultiplier:number(multiplier,'expenseMultiplier',0),netPresentValue:stressTest({...s,annualGrowthRate:growth},{growthDelta:0,expenseMultiplier:multiplier}).stressed.summary.netPresentValue})));
94
+ }
95
+ exports.normalizeScenario=normalizeScenario;
96
+ exports.npv=npv;
97
+ exports.projectTimeline=projectTimeline;
98
+ exports.compareTimelines=compareTimelines;
99
+ exports.stressTest=stressTest;
100
+ exports.sensitivityGrid=sensitivityGrid;
package/src/index.d.ts CHANGED
@@ -1,28 +1,243 @@
1
- /** Rates are decimals (0.05 = 5%); money uses one consistent currency. */
1
+ /**
2
+ * cashflow-lens: compare cashflow scenarios without mixing rental income
3
+ * with capital growth.
4
+ *
5
+ * All money arguments must use one consistent currency/unit. Rates are
6
+ * decimal fractions: `0.08` means 8%. Results are unrounded JavaScript
7
+ * numbers (IEEE-754, not decimal accounting); round for display only.
8
+ * All examples are fictional, not investment advice.
9
+ */
10
+
11
+ /**
12
+ * A scenario to project. Rates are decimals (`0.05` = 5%); money uses one
13
+ * consistent currency.
14
+ *
15
+ * @example
16
+ * const flat = {
17
+ * initialInvestment: 5000000, // ₹50 lakh
18
+ * annualIncome: 300000, // rent
19
+ * annualExpenses: 60000, // maintenance, tax
20
+ * annualGrowthRate: 0.04,
21
+ * years: 5,
22
+ * exitFeeRate: 0.02
23
+ * };
24
+ */
2
25
  export interface Scenario {
26
+ /** Initial asset value / capital invested. Must be greater than zero. */
3
27
  initialInvestment: number;
28
+ /** Gross income per year. Must be non-negative. */
4
29
  annualIncome: number;
30
+ /** Fixed annual expenses. Default `0`. Must be non-negative. */
5
31
  annualExpenses?: number;
32
+ /** Annual compound asset growth as a decimal. Default `0`. At least `-1`. */
6
33
  annualGrowthRate?: number;
34
+ /** Holding period in years; fractional years allowed. Must be greater than zero. */
7
35
  years: number;
36
+ /** Fraction of ending asset value charged at exit. Default `0`. Between `0` and `1`. */
8
37
  exitFeeRate?: number;
9
38
  }
39
+
40
+ /**
41
+ * The projection returned by {@link projectScenario}. All rates are decimal
42
+ * fractions; all money fields use the input's currency.
43
+ */
10
44
  export interface Projection {
45
+ /** `annualIncome - annualExpenses` */
11
46
  netAnnualIncome: number;
47
+ /** `netAnnualIncome * years` (income is not reinvested) */
12
48
  accumulatedIncome: number;
49
+ /** `initialInvestment * (1 + annualGrowthRate) ** years` */
13
50
  endingAssetValue: number;
51
+ /** `endingAssetValue * exitFeeRate` */
14
52
  exitFee: number;
53
+ /** `endingAssetValue - exitFee` */
15
54
  terminalProceeds: number;
55
+ /** `terminalProceeds + accumulatedIncome - initialInvestment` */
16
56
  netProfit: number;
57
+ /** `netAnnualIncome / initialInvestment` */
17
58
  cashYieldRate: number;
59
+ /** `netProfit / initialInvestment` (cumulative, not annualized) */
18
60
  totalReturnRate: number;
19
- /** Capital-only CAGR after exit fees. Excludes interim income. */
61
+ /** Capital-only CAGR after exit fees. Excludes interim income; do not add it to cash yield. */
20
62
  capitalCagrRate: number;
21
63
  }
64
+
65
+ /** A {@link Scenario} plus a unique non-empty string `id`. */
22
66
  export interface IdentifiedScenario extends Scenario { id: string; }
67
+
68
+ /** A {@link Projection} plus the `id` of the scenario it came from. */
23
69
  export interface RankedProjection extends Projection { id: string; }
70
+
71
+ /**
72
+ * Annual net income divided by initial investment. Returns a decimal rate.
73
+ *
74
+ * @param initialInvestment Positive initial capital.
75
+ * @param annualIncome Non-negative gross annual income.
76
+ * @param annualExpenses Non-negative annual expenses. Default `0`.
77
+ * @returns `(annualIncome - annualExpenses) / initialInvestment`
78
+ * @throws {TypeError} Non-finite or wrongly typed arguments.
79
+ * @throws {RangeError} Negative income/expenses or non-positive investment.
80
+ *
81
+ * @example
82
+ * cashYield(10000, 800, 200); // 0.06, i.e. 6%
83
+ */
24
84
  export declare function cashYield(initialInvestment: number, annualIncome: number, annualExpenses?: number): number;
85
+
86
+ /**
87
+ * Cumulative total return: income and terminal proceeds versus initial
88
+ * investment. Not annualized.
89
+ *
90
+ * @param initialInvestment Positive initial capital.
91
+ * @param terminalProceeds Non-negative proceeds at exit.
92
+ * @param accumulatedIncome Income over the holding period; may be negative. Default `0`.
93
+ * @returns `(terminalProceeds + accumulatedIncome - initialInvestment) / initialInvestment`
94
+ * @throws {TypeError} Non-finite or wrongly typed arguments.
95
+ * @throws {RangeError} Negative terminal proceeds or non-positive investment.
96
+ *
97
+ * @example
98
+ * totalReturn(10000, 10804.5, 1200); // 0.20045, i.e. 20.045% over the period
99
+ */
25
100
  export declare function totalReturn(initialInvestment: number, terminalProceeds: number, accumulatedIncome?: number): number;
101
+
102
+ /**
103
+ * Capital-only compound annual growth rate. Not IRR/XIRR: ignores interim
104
+ * income and its timing. A zero final value returns `-1` (100% loss).
105
+ *
106
+ * @param initialValue Positive starting value.
107
+ * @param finalValue Non-negative ending value.
108
+ * @param years Positive period; fractional years allowed.
109
+ * @returns `(finalValue / initialValue) ** (1 / years) - 1`
110
+ * @throws {TypeError} Non-finite or wrongly typed arguments.
111
+ * @throws {RangeError} Negative final value, or non-positive initial value or years.
112
+ *
113
+ * @example
114
+ * cagr(100, 121, 2); // 0.1, i.e. 10% per year
115
+ */
26
116
  export declare function cagr(initialValue: number, finalValue: number, years: number): number;
117
+
118
+ /**
119
+ * Project one scenario: fixed annual net income (not reinvested) plus
120
+ * constant compound asset growth, minus an exit fee on the ending value.
121
+ *
122
+ * Model limits: no taxes, inflation, debt, vacancies or reinvestment.
123
+ * Unknown option fields are ignored.
124
+ *
125
+ * @param scenario The scenario to project.
126
+ * @returns The {@link Projection}. Throws `RangeError` if any result overflows to a non-finite number.
127
+ * @throws {TypeError} Missing/invalid fields or a non-object argument.
128
+ * @throws {RangeError} Out-of-range fields (see {@link Scenario}).
129
+ *
130
+ * @example
131
+ * const p = projectScenario({
132
+ * initialInvestment: 10000, annualIncome: 800, annualExpenses: 200,
133
+ * annualGrowthRate: 0.05, years: 2, exitFeeRate: 0.02
134
+ * });
135
+ * p.netProfit; // 2004.5
136
+ * p.cashYieldRate; // 0.06
137
+ * p.totalReturnRate; // 0.20045
138
+ * p.capitalCagrRate; // about 0.0394
139
+ */
27
140
  export declare function projectScenario(scenario: Scenario): Projection;
141
+
142
+ /**
143
+ * Rank scenarios by total return rate, highest first. Equal rates retain
144
+ * input order. Inputs are never mutated; empty input returns `[]`.
145
+ *
146
+ * Only compare like-for-like horizons and currency assumptions: this ranks
147
+ * one metric, not risk, liquidity, suitability or investment quality.
148
+ *
149
+ * @param scenarios Scenarios with unique non-empty string `id`s.
150
+ * @returns Ranked projections carrying each scenario's `id`.
151
+ * @throws {TypeError} Non-array input, or a missing/blank/non-string `id`.
152
+ * @throws {RangeError} Duplicate `id`s.
153
+ *
154
+ * @example
155
+ * const ranked = compareScenarios([
156
+ * { id: 'income-first', initialInvestment: 10000, annualIncome: 800, years: 3 },
157
+ * { id: 'growth-first', initialInvestment: 10000, annualIncome: 400, annualGrowthRate: 0.05, years: 3 }
158
+ * ]);
159
+ * ranked.map(row => row.id); // ['growth-first', 'income-first']
160
+ */
28
161
  export declare function compareScenarios(scenarios: readonly IdentifiedScenario[]): RankedProjection[];
162
+
163
+ /** Options for {@link formatMoney}. */
164
+ export interface FormatMoneyOptions {
165
+ /**
166
+ * BCP 47 locale controlling digit grouping and symbol placement.
167
+ * Default `'en-US'`. Use `'en-IN'` for Indian grouping (`1,00,000`).
168
+ */
169
+ locale?: string;
170
+ /** 3-letter ISO 4217 currency code, e.g. `'INR'`, `'USD'`, `'EUR'`. Required. */
171
+ currency: string;
172
+ }
173
+
174
+ /** Options for {@link formatRate}. */
175
+ export interface FormatRateOptions {
176
+ /** BCP 47 locale. Default `'en-US'`. */
177
+ locale?: string;
178
+ /** Fraction digits shown after the decimal point, integer 0-20. Default `2`. */
179
+ maximumFractionDigits?: number;
180
+ }
181
+
182
+ /**
183
+ * Format a money amount for display, using the runtime's `Intl.NumberFormat`
184
+ * data. Display only: the returned string is for humans and never feeds the
185
+ * library's calculations, which stay unrounded IEEE-754 numbers.
186
+ *
187
+ * @param amount Finite number in the given currency.
188
+ * @param options See {@link FormatMoneyOptions}. `currency` is required.
189
+ * @returns A localized currency string.
190
+ * @throws {TypeError} Non-finite amount, missing/non-string currency, or non-object options.
191
+ * @throws {RangeError} Currency that is not a 3-letter ISO 4217 code.
192
+ *
193
+ * @example
194
+ * formatMoney(100000, { locale: 'en-IN', currency: 'INR' }); // "₹1,00,000.00"
195
+ * formatMoney(1000, { locale: 'en-US', currency: 'USD' }); // "$1,000.00"
196
+ */
197
+ export declare function formatMoney(amount: number, options: FormatMoneyOptions): string;
198
+
199
+ /**
200
+ * Format a decimal rate as a percentage for display. Display only: rounding
201
+ * applies to the string, not to stored values.
202
+ *
203
+ * @param rate Finite decimal rate (`0.06` = 6%).
204
+ * @param options See {@link FormatRateOptions}.
205
+ * @returns A localized percent string.
206
+ * @throws {TypeError} Non-finite rate, non-integer digits, or non-object options.
207
+ * @throws {RangeError} `maximumFractionDigits` outside 0-20.
208
+ *
209
+ * @example
210
+ * formatRate(0.06); // "6%"
211
+ * formatRate(0.0394, { maximumFractionDigits: 1 }); // "3.9%"
212
+ */
213
+ export declare function formatRate(rate: number, options?: FormatRateOptions): string;
214
+
215
+ /** Whole-year, end-of-year model. Rates are decimals. Overrides replace one year's modeled flow. */
216
+ export interface TimelineScenario extends IdentifiedScenario {
217
+ incomeGrowthRate?: number;
218
+ expenseGrowthRate?: number;
219
+ discountRate?: number;
220
+ overrides?: {year: number; income?: number; expenses?: number}[];
221
+ }
222
+ export interface TimelineRow {
223
+ year: number; income: number; expenses: number; assetValue: number; exitFee: number;
224
+ saleProceeds: number; operatingCashflow: number; cashflow: number; discountFactor: number;
225
+ presentValue: number; cumulative: number; discountedCumulative: number;
226
+ trace: {income: string; expenses: string; cashflow: string; presentValue: string; incomeExponent: number; assetExponent: number; terminal: boolean};
227
+ }
228
+ export interface TimelineAnalysis {
229
+ schema: 'cashflow-lens.analysis/v1'; assumptions: Required<TimelineScenario>; timing: string;
230
+ cashflows: number[]; rows: TimelineRow[];
231
+ summary: {netProfit: number; totalReturnRate: number; netPresentValue: number; operatingIncome: number; terminalProceeds: number; paybackYear: number | null; discountedPaybackYear: number | null};
232
+ }
233
+ /** Validates strict fields and clones normalized input. 1..50 integer years only. */
234
+ export declare function normalizeScenario(input: TimelineScenario): Required<TimelineScenario>;
235
+ /** Periodic NPV, t=0 is first flow. rate > -1. Never annualizes or infers dates. */
236
+ export declare function npv(rate: number, cashflows: readonly number[]): number;
237
+ export declare function projectTimeline(input: TimelineScenario): TimelineAnalysis;
238
+ /** Requires identical horizons and discount rates. All money must use the same currency. */
239
+ export declare function compareTimelines(inputs: readonly TimelineScenario[], metric?: 'netPresentValue' | 'netProfit' | 'totalReturnRate'): TimelineAnalysis[];
240
+ export interface StressShocks {growthDelta?: number; expenseMultiplier?: number;}
241
+ /** Growth delta changes asset growth; expense multiplier scales modeled and overridden expenses. */
242
+ export declare function stressTest(input: TimelineScenario, shocks?: StressShocks): {base: TimelineAnalysis; stressed: TimelineAnalysis; shocks: Required<StressShocks>};
243
+ export declare function sensitivityGrid(input: TimelineScenario, growthRates: readonly number[], expenseMultipliers: readonly number[]): {growthRate: number; expenseMultiplier: number; netPresentValue: number}[][];
package/src/index.js CHANGED
@@ -91,8 +91,63 @@ function compareScenarios(scenarios) {
91
91
  }).sort((a, b) => b.totalReturnRate - a.totalReturnRate);
92
92
  }
93
93
 
94
+ function localeOf(value) {
95
+ if (value === undefined) return 'en-US';
96
+ if (typeof value !== 'string' || value.trim() === '') {
97
+ throw new TypeError('locale must be a non-empty BCP 47 string, e.g. "en-IN"');
98
+ }
99
+ return value;
100
+ }
101
+
102
+ /**
103
+ * Format a money amount for display, e.g. "\u20B91,00,000.00" in en-IN/INR.
104
+ * Display only: the result is a string for humans and never feeds calculations.
105
+ */
106
+ function formatMoney(amount, options = {}) {
107
+ finite(amount, 'amount');
108
+ if (options === null || typeof options !== 'object' || Array.isArray(options)) {
109
+ throw new TypeError('options must be an object');
110
+ }
111
+ if (options.currency === undefined) throw new TypeError('options.currency is required');
112
+ if (typeof options.currency !== 'string') throw new TypeError('currency must be a string');
113
+ if (!/^[A-Za-z]{3}$/.test(options.currency)) {
114
+ throw new RangeError('currency must be a 3-letter ISO 4217 code, e.g. "INR"');
115
+ }
116
+ return new Intl.NumberFormat(localeOf(options.locale),
117
+ { style: 'currency', currency: options.currency.toUpperCase() }).format(amount);
118
+ }
119
+
120
+ /**
121
+ * Format a decimal rate as a percentage for display, e.g. 0.06 -> "6%".
122
+ * Display only: rounding applies to the string, not to stored values.
123
+ */
124
+ function formatRate(rate, options = {}) {
125
+ finite(rate, 'rate');
126
+ if (options === null || typeof options !== 'object' || Array.isArray(options)) {
127
+ throw new TypeError('options must be an object');
128
+ }
129
+ const digits = options.maximumFractionDigits === undefined ? 2 : options.maximumFractionDigits;
130
+ if (typeof digits !== 'number' || !Number.isInteger(digits)) {
131
+ throw new TypeError('maximumFractionDigits must be an integer');
132
+ }
133
+ if (digits < 0 || digits > 20) throw new RangeError('maximumFractionDigits must be between 0 and 20');
134
+ return new Intl.NumberFormat(localeOf(options.locale),
135
+ { style: 'percent', maximumFractionDigits: digits }).format(rate);
136
+ }
137
+
94
138
  exports.cashYield = cashYield;
95
139
  exports.totalReturn = totalReturn;
96
140
  exports.cagr = cagr;
97
141
  exports.projectScenario = projectScenario;
98
142
  exports.compareScenarios = compareScenarios;
143
+ exports.formatMoney = formatMoney;
144
+ exports.formatRate = formatRate;
145
+
146
+ // Explicit exports preserve Node's CommonJS named-export discovery for ESM consumers.
147
+ const analysis = require('./analysis.js');
148
+ exports.normalizeScenario = analysis.normalizeScenario;
149
+ exports.npv = analysis.npv;
150
+ exports.projectTimeline = analysis.projectTimeline;
151
+ exports.compareTimelines = analysis.compareTimelines;
152
+ exports.stressTest = analysis.stressTest;
153
+ exports.sensitivityGrid = analysis.sensitivityGrid;