@aman050807/cashflow-lens 0.2.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
@@ -27,3 +27,10 @@ Initial development release.
27
27
  - Unit tests and Node.js 20/22/24 CI workflow.
28
28
 
29
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
@@ -185,3 +185,95 @@ contracts. See [CHANGELOG.md](CHANGELOG.md).
185
185
  ## License
186
186
 
187
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.2.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",
@@ -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
@@ -211,3 +211,33 @@ export declare function formatMoney(amount: number, options: FormatMoneyOptions)
211
211
  * formatRate(0.0394, { maximumFractionDigits: 1 }); // "3.9%"
212
212
  */
213
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
@@ -142,3 +142,12 @@ exports.projectScenario = projectScenario;
142
142
  exports.compareScenarios = compareScenarios;
143
143
  exports.formatMoney = formatMoney;
144
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;