finance-calculator-pro 1.0.5 → 1.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/README.md CHANGED
@@ -1,348 +1,451 @@
1
1
  # finance-calculator-pro
2
2
 
3
3
  [![NPM Version](https://img.shields.io/npm/v/finance-calculator-pro.svg)](https://www.npmjs.com/package/finance-calculator-pro)
4
- 📖 **[View the Official Documentation](https://boffincoders.github.io/finance-calculator/)**
4
+ [![NPM Downloads](https://img.shields.io/npm/dm/finance-calculator-pro.svg)](https://www.npmjs.com/package/finance-calculator-pro)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-ready-blue.svg)](https://www.typescriptlang.org/)
6
+ [![Zero Dependencies](https://img.shields.io/badge/dependencies-zero-brightgreen.svg)](https://www.npmjs.com/package/finance-calculator-pro?activeTab=dependencies)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
+
9
+ 📖 **[View the Official Documentation & Live Playground →](https://boffincoders.github.io/finance-calculator/)**
5
10
 
6
11
  ![finance-calculator-pro banner](https://raw.githubusercontent.com/boffincoders/finance-calculator/refs/heads/master/.github/assets/finance-calculator-pro.png)
7
12
 
8
- A highly modular, fully independent fundamental financial calculation engine. Whether you're building a stock screener or tracking your portfolio, this library calculates the metrics tracking a company's valuation, profitability, liquidity, efficiency, and risk flawlessly.
13
+ > **Zero-dependency financial analysis engine for JavaScript and TypeScript.**
14
+ > Calculate 60+ financial metrics — valuation ratios, profitability, liquidity, solvency, efficiency, intrinsic value, composite scoring, technical indicators (SMA, EMA, RSI, MACD, ATR, ADX, Bollinger Bands), and bankruptcy risk scores — from raw financial data. No API calls. No runtime dependencies. Works in Node.js, browsers, and edge runtimes.
15
+
16
+ ---
17
+
18
+ ## What is finance-calculator-pro?
9
19
 
10
- It accepts raw numeric data—no dependency on heavy financial APIs. It pairs amazingly well with normalized data structures (like those from `yahoo-finance2`), or simply your own math.
20
+ `finance-calculator-pro` is a modular financial metrics library that transforms raw company fundamentals (income statement, balance sheet, cash flow data) into structured analysis — complete with computed values, signal ratings (`Good` / `Bad` / `Neutral`), and human-readable insights.
21
+
22
+ Built for:
23
+ - 📊 **Stock screener** and equity research tools
24
+ - 💼 **Portfolio analysis** dashboards
25
+ - 🏦 **FinTech applications** and investment platforms
26
+ - 🔍 **Fundamental analysis** pipelines (pairs naturally with [`yahoo-finance2`](https://www.npmjs.com/package/yahoo-finance2))
27
+ - 🎓 **Financial education** tools and calculators
28
+
29
+ ---
11
30
 
12
31
  ## Installation
13
32
 
14
33
  ```bash
15
34
  npm install finance-calculator-pro
35
+ # or
36
+ yarn add finance-calculator-pro
37
+ # or
38
+ pnpm add finance-calculator-pro
16
39
  ```
17
40
 
41
+ Works with **Node.js ≥ 16**. Ships as **CJS + ESM + TypeScript type declarations**. Zero runtime dependencies.
42
+
18
43
  ---
19
44
 
20
45
  ## 🏢 Enterprise Support & FinTech Development
21
46
 
22
- **finance-calculator-pro** is engineered and maintained by **Boffin Coders**, a premier software development agency specializing in FinTech, custom dashboards, and enterprise-grade software solutions.
47
+ **finance-calculator-pro** is engineered and maintained by **[Boffin Coders](https://boffincoders.com)**, a software development agency specialising in FinTech, financial dashboards, and enterprise-grade data platforms.
23
48
 
24
- Are you building a stock screener, a neo-bank, or an internal financial tool? We can help you accelerate development.
25
- 👉 **[Let's talk about your next project!](https://boffincoders.com)**
49
+ Building a stock screener, neo-bank, or internal financial analysis tool? [Let's talk →](https://boffincoders.com)
26
50
 
27
51
  ---
28
52
 
29
- ## Complete List of Available Metrics
30
-
31
- The engine can calculate the following metrics natively from basic fundamental variables:
32
-
33
- ### 🏦 Valuation
34
- - **Price-to-Earnings (P/E)**: `price / eps`
35
- - **Price-to-Book (P/B)**: `price / bookValuePerShare`
36
- - **Price-to-Sales (P/S)**: `price / revenuePerShare`
37
- - **Price/Earnings-to-Growth (PEG)**: `pe / expectedEarningsGrowthRate`
38
- - **Enterprise Multiple (EV/EBITDA)**: `enterpriseValue / ebitda`
39
- - **Dividend Yield**: `annualDividendPerShare / price`
40
- - **Discounted Cash Flow (DCF)**: Calculates Enterprise Present Value from terminal rates and sequential FCFs.
41
- - **Graham Number**: `sqrt(22.5 * eps * bookValuePerShare)`
42
-
43
- ### 📈 Profitability
44
- - **Return on Assets (ROA)**: `netIncome / totalAssets`
45
- - **Return on Equity (ROE)**: `netIncome / totalEquity`
46
- - **Return on Invested Capital (ROIC)**: `nopat / investedCapital`
47
- - **Gross Margin**: `grossProfit / revenue`
48
- - **Operating Margin**: `operatingIncome / revenue`
49
- - **Net Profit Margin**: `netIncome / revenue`
50
- - **Free Cash Flow Margin**: `fcf / revenue`
51
-
52
- ### 💧 Liquidity & Solvency
53
- - **Current Ratio**: `totalAssets / totalLiabilities` (Using broader snapshot)
54
- - **Quick Ratio**: `(totalAssets - inventory) / totalLiabilities`
55
- - **Debt-to-Equity**: `totalDebt / totalEquity`
56
- - **Interest Coverage**: `ebit / interestExpense`
57
-
58
- ### ⚙️ Efficiency
59
- - **Asset Turnover**: `revenue / totalAssets`
60
- - **Inventory Turnover**: `costOfRevenue / inventory`
61
-
62
- ### ⚠️ Risk & Insights
63
- - **Altman Z-Score**: Fundamental bankruptcy risk predictor combining 5 variables.
64
- - **Sharpe Ratio**: ROI vs Risk-free rate adjusted for standard deviation.
65
- - **Target Upside**: `%` potential from current `price` to `analystTargetPrice`.
66
-
67
- ### 📊 Growth (Timeseries)
68
- - **YoY / QoQ Growth Rates**: Automatically tracks sequential growth of Revenue, Net Income, EPS, and Cash Flows.
69
- - **CAGR**: Compound Annual Growth Rate over multi-period arrays.
53
+ ## Metrics Reference 60+ Functions Across 12 Categories
54
+
55
+ ### Valuation Ratios
56
+ | Metric | Function | Formula |
57
+ |---|---|---|
58
+ | Price-to-Earnings (P/E) | `pe()` | `Price / EPS` |
59
+ | Price-to-Book (P/B) | `pb()` | `Price / Book Value Per Share` |
60
+ | Price-to-Sales (P/S) | `ps()` | `Price / Revenue Per Share` |
61
+ | Price/Earnings-to-Growth (PEG) | `peg()` | `P/E / Earnings Growth Rate` |
62
+ | EV/EBITDA (Enterprise Multiple) | `evEbitda()` | `Enterprise Value / EBITDA` |
63
+ | EV / Revenue | `evRevenue()` | `Enterprise Value / Revenue` |
64
+ | EV / Free Cash Flow | `evFcf()` | `Enterprise Value / FCF` |
65
+ | Price-to-Cash-Flow (P/CF) | `priceToCashFlow()` | `Market Cap / Operating Cash Flow` |
66
+ | Earnings Yield | `earningsYield()` | `EPS / Price` |
67
+ | Dividend Yield | `dividendYield()` | `Annual Dividend / Price` |
68
+ | Discounted Cash Flow (DCF) | `calculateDCF()` | Terminal value + discounted FCF streams |
69
+ | Graham Number | `grahamNumber()` | `√(22.5 × EPS × Book Value)` |
70
+ | Market Cap to Total Capital | `marketCapToDebtCap()` | `Market Cap / (Market Cap + Total Debt)` |
71
+
72
+ ### Profitability Metrics
73
+ | Metric | Function | Formula |
74
+ |---|---|---|
75
+ | Return on Assets (ROA) | `roa()` | `Net Income / Total Assets` |
76
+ | Return on Equity (ROE) | `roe()` | `Net Income / Total Equity` |
77
+ | Return on Invested Capital (ROIC) | `roic()` | `NOPAT / Invested Capital` |
78
+ | Gross Margin | `grossMargin()` | `Gross Profit / Revenue` |
79
+ | Operating Margin | `operatingMargin()` | `Operating Income / Revenue` |
80
+ | Net Profit Margin | `netProfitMargin()` | `Net Income / Revenue` |
81
+ | Free Cash Flow Margin | `fcfMargin()` | `FCF / Revenue` |
82
+
83
+ ### Liquidity Ratios
84
+ | Metric | Function | Formula |
85
+ |---|---|---|
86
+ | Current Ratio | `currentRatio()` | `Current Assets / Current Liabilities` |
87
+ | Quick Ratio (Acid-Test) | `quickRatio()` | `(Current Assets Inventory) / Current Liabilities` |
88
+ | Debt-to-Equity | `debtToEquity()` | `Total Debt / Total Equity` |
89
+ | Interest Coverage Ratio | `interestCoverage()` | `EBIT / Interest Expense` |
90
+
91
+ ### Solvency & Leverage Metrics
92
+ | Metric | Function | Formula |
93
+ |---|---|---|
94
+ | Net Debt | `netDebt()` | `Total Debt − Cash & Equivalents` |
95
+ | Net Debt / EBITDA | `netDebtToEbitda()` | `(Debt − Cash) / EBITDA` |
96
+ | Debt-to-Assets | `debtToAssets()` | `Total Debt / Total Assets` |
97
+
98
+ ### Efficiency Metrics
99
+ | Metric | Function | Formula |
100
+ |---|---|---|
101
+ | Asset Turnover | `assetTurnover()` | `Revenue / Average Assets` |
102
+ | Inventory Turnover | `inventoryTurnover()` | `COGS / Average Inventory` |
103
+ | Receivables Turnover | `receivablesTurnover()` | `Revenue / Trade Receivables` |
104
+ | Days Sales Outstanding (DSO) | `daysSalesOutstanding()` | `365 / Receivables Turnover` |
105
+ | Payable Days (DPO) | `payableDays()` | `(Trade Payables / COGS) × 365` |
106
+ | Working Capital Days | `workingCapitalDays()` | `(Working Capital / Revenue) × 365` |
107
+ | Cash Conversion Cycle | `cashConversionCycle()` | `DSO + DIO − DPO` |
108
+
109
+ ### Earnings Quality Metrics
110
+ | Metric | Function | Formula |
111
+ |---|---|---|
112
+ | Payout Ratio | `payoutRatio()` | `Annual Dividend / EPS` |
113
+ | Cash Conversion Ratio (CCR) | `cashConversionRatio()` | `Operating Cash Flow / Net Income` |
114
+
115
+ ### Risk & Bankruptcy Prediction
116
+ | Metric | Function | Notes |
117
+ |---|---|---|
118
+ | Altman Z-Score | `altmanZScore()` | Z > 2.99 = safe, 1.81–2.99 = grey zone, < 1.81 = distress |
119
+ | Piotroski F-Score | `piotroski()` | 9-signal scorecard; 8–9 = strong, 0–2 = weak |
120
+ | Sharpe Ratio | `sharpe()` | Risk-adjusted return vs risk-free rate |
121
+ | Target Upside | `targetUpside()` | % gap to analyst target price |
122
+
123
+ ### Intrinsic Valuation & Scoring
124
+ | Metric | Function | Notes |
125
+ |---|---|---|
126
+ | Graham Number | `grahamNumber()` | Benjamin Graham's defensive value ceiling |
127
+ | Net Current Value Per Share | `computeNCVPS()` | (Current Assets − Total Liabilities) / Shares |
128
+ | Intrinsic Value Estimate | `computeIntrinsicValue()` | Simple 5-yr EPS projection with margin of safety |
129
+ | G-Factor (Composite) | `computeGFactor()` | Quality×40% + Growth×35% + Momentum×25% |
130
+ | Quality Score | `computeQualityScore()` | Piotroski + ROE vs sector + margins + pledge + promoter |
131
+ | Growth Score | `computeGrowthScore()` | Revenue growth + profit growth + EPS growth + CFO |
132
+ | Value Score | `computeValueScore()` | P/E vs avg + P/B vs sector + PEG + historical percentile |
133
+ | Momentum Score | `computeMomentumScore()` | SMA200 + RSI + ADX + volume ratio + ROC-125 |
134
+
135
+ ### Growth & Timeseries Analysis
136
+ | Function | Description |
137
+ |---|---|
138
+ | `calculateGrowthRate()` | Single-period % growth rate |
139
+ | `yoyGrowth()` | Year-over-year growth rates for a series |
140
+ | `qoqGrowth()` | Quarter-over-quarter growth rates |
141
+ | `cagr()` | Compound Annual Growth Rate |
142
+ | `medianGrowth()` | Median YoY growth rate (outlier-resistant) |
143
+
144
+ ### TTM & Historical Aggregation
145
+ | Function | Description |
146
+ |---|---|
147
+ | `computeTTM()` | Trailing Twelve Months sum (last 4 quarters) |
148
+ | `computeTTMAvg()` | Trailing Twelve Months average |
149
+ | `computeNYearAverage()` | Rolling N-year average of quarterly data |
150
+ | `computeNYearSum()` | Rolling N-year sum of quarterly data |
151
+ | `computeHistoricalPoint()` | Value at exactly N quarters back |
152
+
153
+ ### Technical Indicators *(native — zero dependencies)*
154
+ | Function | Description |
155
+ |---|---|
156
+ | `sma(prices, period)` | Simple Moving Average |
157
+ | `ema(prices, period)` | Exponential Moving Average |
158
+ | `rsi(prices, period?)` | Relative Strength Index (default 14) |
159
+ | `roc(prices, period?)` | Rate of Change (default 14) |
160
+ | `macd(prices, fast?, slow?, signal?)` | MACD line, signal line, histogram |
161
+ | `atr(highs, lows, closes, period?)` | Average True Range (default 14) |
162
+ | `bollingerBands(prices, period?, mult?)` | Upper, Middle, Lower bands + Bandwidth |
163
+ | `adx(highs, lows, closes, period?)` | ADX + +DI + −DI (default 14) |
164
+ | `mfi(highs, lows, closes, volumes, period?)` | Money Flow Index (default 14) |
165
+ | `vwap(highs, lows, closes, volumes)` | Volume-Weighted Average Price |
166
+ | `beta(stockReturns, benchmarkReturns)` | Beta vs benchmark |
167
+ | `pivotPoints(high, low, close)` | Classic Pivot Points (P, R1–R3, S1–S3) |
70
168
 
71
169
  ---
72
170
 
73
- ## 🏗 Data Inputs: What the API Accepts
74
-
75
- To use the massive aggregator functions (like `analyzeCompany` or `analyzeValuation`), you just pass an object of shape `CompanySnapshotInput`.
76
-
77
- **EVERY FIELD IS OPTIONAL**. If you omit a field, the engine simply skips the metric that calculates it and safely returns `null` for that metric!
78
-
79
- ### `CompanySnapshotInput` (Used for Snapshot Analyzers)
80
- ```typescript
81
- interface CompanySnapshotInput {
82
- price?: number;
83
- marketCap?: number;
84
- totalRevenue?: number;
85
- grossProfit?: number;
86
- operatingIncome?: number;
87
- netIncome?: number;
88
- freeCashFlow?: number;
89
- eps?: number;
90
- bookValuePerShare?: number;
91
- revenuePerShare?: number;
92
- totalAssets?: number;
93
- totalLiabilities?: number;
94
- totalEquity?: number;
95
- totalDebt?: number;
96
- cashAndEquivalents?: number;
97
- inventory?: number;
98
- interestExpense?: number;
99
- costOfRevenue?: number;
100
- annualDividendPerShare?: number;
101
- expectedEarningsGrowthRate?: number;
102
- ebitda?: number;
103
- workingCapital?: number;
104
- retainedEarnings?: number;
105
- ebit?: number;
106
- taxRate?: number;
107
- returns?: number; // for sharpe
108
- riskFree?: number; // for sharpe
109
- stdDev?: number; // for sharpe
110
- analystTargetPrice?: number;
111
- }
112
- ```
113
-
114
- ### `FundamentalTimeseriesInput` (Used for Trend Analyzers)
115
- These metrics look at arrays chronologically from **oldest** to **newest**.
116
- ```typescript
117
- interface FundamentalTimeseriesInput {
118
- revenue: number[];
119
- netIncome: number[];
120
- costOfRevenue?: number[];
121
- operatingIncome?: number[];
122
- freeCashFlow?: number[];
123
- eps?: number[];
124
- }
125
- ```
126
-
127
- ---
171
+ ## Quick Start
128
172
 
129
- ## 🛠 Complete Usage Guide
173
+ ### The All-in-One API: `analyzeCompany()`
130
174
 
131
- ### 1. The Super Analyzer: `analyzeCompany`
132
- Pass your raw snapshot of a company, and let the engine derive everything at once. Setting `withInsights = true` will automatically translate numbers into human-readable recommendations ("Good", "Bad", "Neutral").
175
+ Pass any subset of a company's fundamentals and get structured analysis across all 7 categories at once:
133
176
 
134
177
  ```typescript
135
178
  import { analyzeCompany } from 'finance-calculator-pro';
136
179
 
137
- // You ONLY need to provide the fields you care about!
138
- const rawData = {
180
+ const data = {
139
181
  price: 150,
140
- eps: 5,
182
+ eps: 5,
141
183
  bookValuePerShare: 20,
142
184
  marketCap: 150000,
143
185
  totalDebt: 20000,
144
186
  cashAndEquivalents: 5000,
187
+ ebitda: 9000,
145
188
  netIncome: 5000,
189
+ operatingCashFlow: 7500,
190
+ totalRevenue: 50000,
146
191
  totalAssets: 100000,
147
192
  totalLiabilities: 60000,
148
193
  totalEquity: 40000,
149
194
  };
150
195
 
151
- // With Insights (Best for Beginners & UI)
152
- const insightAnalysis = analyzeCompany(rawData, true);
153
-
154
- console.log(JSON.stringify(insightAnalysis.valuation, null, 2));
155
- /*
156
- {
157
- "pe": {
158
- "value": 30,
159
- "status": "Bad",
160
- "insight": "Expensive. High growth is priced in."
161
- },
162
- "pb": {
163
- "value": 7.5,
164
- "status": "Bad",
165
- "insight": "Trading at a high premium to book value."
166
- },
167
- "ps": {
168
- "value": null,
169
- "status": "N/A",
170
- "insight": "Sales data unavailable."
171
- }
172
- }
173
- */
174
- ```
196
+ // withInsights: true returns { value, status, insight } for every metric
197
+ const analysis = analyzeCompany(data, true);
175
198
 
176
- ### 2. Categorical Evaluation
177
- If you only want to process a specific category instead of all metrics at once, you can explicitly call categorical analyzers! They accept the exact same `CompanySnapshotInput`.
199
+ // Valuation
200
+ console.log(analysis.valuation.pe);
201
+ // { value: 30, status: "Bad", insight: "Expensive. High growth is priced in." }
178
202
 
179
- Available Categorical Analyzers:
180
- - `analyzeValuation(data, withInsights?)`
181
- - `analyzeProfitability(data, withInsights?)`
182
- - `analyzeLiquidity(data, withInsights?)`
183
- - `analyzeEfficiency(data, withInsights?)`
184
- - `analyzeRisk(data, withInsights?)`
203
+ console.log(analysis.valuation.evEbitda);
204
+ // { value: 18.33, status: "Bad", insight: "Expensive relative to cash earnings." }
185
205
 
186
- ```typescript
187
- import { analyzeProfitability } from 'finance-calculator-pro';
206
+ // Solvency
207
+ console.log(analysis.solvency.netDebtToEbitda);
208
+ // { value: 1.5, status: "Good", insight: "Low leverage. Manageable debt load." }
209
+
210
+ // Earnings Quality
211
+ console.log(analysis.quality.cashConversionRatio);
212
+ // { value: 1.5, status: "Good", insight: "Cash-backed earnings. Strong quality." }
188
213
 
189
- const profitabilityMetrics = analyzeProfitability(rawData, true);
190
- console.log(profitabilityMetrics.roe.insight); // "Strong return on shareholder equity."
214
+ // Risk
215
+ console.log(analysis.risk.altmanZScore);
216
+ // { value: 3.71, status: "Good", insight: "Safe zone. Low bankruptcy risk." }
191
217
  ```
192
218
 
193
- ### 3. Individual Metric Insights
194
- If you only need to calculate and evaluate a **single metric** (like P/E), you can combine the pure math modules directly with the `evaluate` engine to get insights without building a full company snapshot!
219
+ Returns 7 analysis categories: `valuation` · `profitability` · `liquidity` · `solvency` · `efficiency` · `risk` · `quality`
195
220
 
196
- ```typescript
197
- import { pe, evaluate } from 'finance-calculator-pro';
221
+ Every field in the input is **optional** — missing fields cause their dependent metrics to return `null` safely. The engine never throws.
198
222
 
199
- // 1. Calculate the raw numerical value
200
- const ratio = pe(150 /* price */, 5 /* eps */); // -> 30
223
+ ---
201
224
 
202
- // 2. Pass it natively to the Evaluator for automated context
203
- const insight = evaluate.pe(ratio);
225
+ ### Categorical Analyzers
204
226
 
205
- console.log(JSON.stringify(insight, null, 2));
206
- /*
207
- {
208
- "value": 30,
209
- "status": "Bad",
210
- "insight": "Expensive. High growth is priced in."
211
- }
212
- */
227
+ Run analysis on a single dimension — useful for dashboards, screeners, or compute-sensitive environments:
228
+
229
+ ```typescript
230
+ import {
231
+ analyzeValuation,
232
+ analyzeProfitability,
233
+ analyzeLiquidity,
234
+ analyzeSolvency,
235
+ analyzeEfficiency,
236
+ analyzeRisk,
237
+ analyzeQuality,
238
+ } from 'finance-calculator-pro';
239
+
240
+ const solvency = analyzeSolvency(data, true);
241
+ console.log(solvency.netDebtToEbitda);
242
+ // { value: 1.5, status: "Good", insight: "..." }
243
+
244
+ const quality = analyzeQuality(data, true);
245
+ console.log(quality.cashConversionRatio);
246
+ // { value: 1.5, status: "Good", insight: "Cash-backed earnings. Strong quality." }
213
247
  ```
214
248
 
215
- ### 4. Batch Analysis (Screening)
216
- Evaluate hundreds of companies seamlessly in a single line.
249
+ ---
250
+
251
+ ### Batch Analysis — Stock Screener
252
+
253
+ Evaluate an entire watchlist in one call:
217
254
 
218
255
  ```typescript
219
256
  import { analyzeBatch } from 'finance-calculator-pro';
220
257
 
221
- const multipleCompanies = [ company1, company2, company3 ];
222
- const batchResults = analyzeBatch(multipleCompanies, true);
258
+ const results = analyzeBatch([appleData, msftData, nvidiaData, tcsData], true);
259
+
260
+ // Sort by P/E ascending — cheapest first
261
+ const byPe = results
262
+ .filter(r => r.valuation.pe?.value !== null)
263
+ .sort((a, b) => (a.valuation.pe!.value as number) - (b.valuation.pe!.value as number));
223
264
  ```
224
265
 
225
- ### 5. Timeseries / Trend Analysis
226
- Pass arrays of data (oldest to newest) to get automated sequential growth rates and historical margins over time.
266
+ ---
267
+
268
+ ### Timeseries & Growth Trend Analysis
269
+
270
+ Pass chronological arrays (oldest → newest) to compute growth rates and margin trends automatically:
227
271
 
228
272
  ```typescript
229
273
  import { analyzeFundamentalTrends } from 'finance-calculator-pro';
230
274
 
231
- const timeseriesData = {
232
- revenue: [40000, 45000, 50000],
233
- netIncome: [4000, 5000, 6000]
234
- };
275
+ const trends = analyzeFundamentalTrends({
276
+ revenue: [365_817, 394_328, 383_285],
277
+ netIncome: [ 94_680, 99_803, 96_995],
278
+ }, 'annual');
235
279
 
236
- // Pass "annual" or "quarterly" depending on data density
237
- const trends = analyzeFundamentalTrends(timeseriesData, "annual");
238
-
239
- console.log(JSON.stringify(trends, null, 2));
240
- /*
241
- {
242
- "periodType": "annual",
243
- "growth": {
244
- "revenueGrowth": [0.125, 0.111111],
245
- "netIncomeGrowth": [0.25, 0.20],
246
- "revenueCagr": 0.118,
247
- "netIncomeCagr": 0.224
248
- },
249
- "margins": {
250
- "netMargins": [0.1, 0.111, 0.12]
251
- }
252
- }
253
- */
280
+ console.log(trends.growth.revenueCagr); // -0.022 (-2.2% CAGR)
281
+ console.log(trends.growth.revenueGrowth); // [0.0777, -0.0282]
282
+ console.log(trends.margins.netProfitMargin); // [0.259, 0.253, 0.253]
283
+ console.log(trends.quality.fcfConversion); // FCF / Net Income per period
254
284
  ```
255
285
 
256
- ### 6. Individual Mathematical Metrics (API Reference)
257
- Because this is fundamentally a generic node package, if you only need a single lightweight calculation without any object-mapping overhead, you can import and execute the mathematical functions directly.
286
+ ---
287
+
288
+ ### Individual Math Functions
258
289
 
259
- Every function returns a `number | null` (returning `null` implicitly if any division goes to zero or infinity, guaranteeing runtime safety).
290
+ Import any function directly for lightweight single-metric use. Every function returns `number | null` `null` means a required input was absent; the library never throws:
260
291
 
261
- #### Valuation
262
292
  ```typescript
263
- import { pe, pb, ps, peg, evEbitda, calculateEnterpriseValue, dividendYield, calculateDCF } from 'finance-calculator-pro';
264
-
265
- pe(150 /* price */, 5 /* eps */); // -> 30
266
- pb(150 /* price */, 20 /* bookValuePerShare */); // -> 7.5
267
- ps(150 /* price */, 50 /* revenuePerShare */); // -> 3
268
- peg(30 /* peRatio */, 0.15 /* earningsGrowthRate */); // -> 200
269
- calculateEnterpriseValue(150000 /* marketCap */, 20000 /* debt */, 5000 /* cash */); // -> 165000
270
- evEbitda(165000 /* enterpriseValue */, 10000 /* ebitda */); // -> 16.5
271
- dividendYield(1.5 /* annualDividendPerShare */, 150 /* price */); // -> 0.01 (1%)
272
-
273
- // DCF Example
274
- calculateDCF(
275
- [3000, 3500, 4000, 4500, 5000] /* projectedFCF */,
276
- 0.10 /* discountRateWACC */,
277
- 0.025 /* terminalGrowthRate */
278
- );
293
+ import {
294
+ pe, pb, ps, peg, evEbitda, evRevenue, evFcf,
295
+ priceToCashFlow, earningsYield, grahamNumber, calculateDCF,
296
+ roa, roe, roic, grossMargin, operatingMargin, netProfitMargin,
297
+ currentRatio, quickRatio, debtToEquity, interestCoverage,
298
+ netDebt, netDebtToEbitda, debtToAssets,
299
+ assetTurnover, receivablesTurnover, daysSalesOutstanding,
300
+ payoutRatio, cashConversionRatio,
301
+ altmanZScore, piotroski, sharpe, targetUpside,
302
+ evaluate,
303
+ } from 'finance-calculator-pro';
304
+
305
+ // Valuation
306
+ pe(150, 5); // 30
307
+ priceToCashFlow(150_000, 7_000); // 21.43
308
+ earningsYield(5, 150); // → 0.0333 (3.33%)
309
+ grahamNumber(5, 20); // → 47.43 (null if EPS or book ≤ 0)
310
+
311
+ // Solvency
312
+ netDebtToEbitda(20_000, 5_000, 10_000); // → 1.5
313
+ debtToAssets(20_000, 100_000); // → 0.20
314
+
315
+ // Efficiency
316
+ daysSalesOutstanding(50_000, 6_250); // → 45.6 days
317
+
318
+ // Earnings Quality
319
+ cashConversionRatio(7_000, 5_000); // → 1.4
320
+
321
+ // Risk
322
+ altmanZScore(15_000, 20_000, 7_500, 250_000, 50_000, 100_000, 60_000); // → 3.71
323
+ sharpe(0.12, 0.04, 0.15); // → 0.533
324
+
325
+ // Piotroski F-Score
326
+ const result = piotroski({
327
+ netIncome: 5_000, totalAssets: 100_000, operatingCashFlow: 7_000,
328
+ priorNetIncome: 4_000, priorTotalAssets: 100_000,
329
+ });
330
+ result.score; // → 4
331
+ result.maxScore; // → 5
332
+
333
+ // Pair raw math with the Insights Engine
334
+ const ratio = pe(150, 5); // → 30
335
+ evaluate.pe(ratio);
336
+ // { value: 30, status: "Bad", insight: "Expensive. High growth is priced in." }
279
337
  ```
280
338
 
281
- #### Profitability
282
- ```typescript
283
- import { roa, roe, roic, grossMargin, operatingMargin, netProfitMargin, fcfMargin } from 'finance-calculator-pro';
339
+ ---
284
340
 
285
- roa(5000 /* netIncome */, 100000 /* totalAssets */); // -> 0.05
286
- roe(5000 /* netIncome */, 40000 /* totalEquity */); // -> 0.125
287
- roic(7000 /* operatingIncome */, 0.2 /* taxRate */, 20000 /* debt */, 40000 /* equity */, 5000 /* cash */); // -> 0.1018
341
+ ### Works with any data source
288
342
 
289
- // Margins
290
- grossMargin(50000 /* revenue */, 20000 /* costOfRevenue */); // -> 0.60
291
- operatingMargin(7000 /* operatingIncome */, 50000 /* revenue */); // -> 0.14
292
- netProfitMargin(5000 /* netIncome */, 50000 /* revenue */); // -> 0.10
293
- fcfMargin(3000 /* freeCashFlow */, 50000 /* revenue */); // -> 0.06
294
- ```
343
+ `finance-calculator-pro` accepts plain numbers — no proprietary data format required. Feed it data from `yahoo-finance2`, Alpha Vantage, Financial Modeling Prep, Polygon.io, your own database, or manually entered values. If you can get the numbers, the engine handles the rest.
295
344
 
296
- #### Liquidity
297
- ```typescript
298
- import { currentRatio, quickRatio, debtToEquity, interestCoverage } from 'finance-calculator-pro';
345
+ ---
299
346
 
300
- currentRatio(100000 /* currentAssets */, 60000 /* currentLiabilities */); // -> 1.66
301
- quickRatio(100000 /* currentAssets */, 10000 /* inventory */, 60000 /* currentLiabilities */); // -> 1.5
302
- debtToEquity(20000 /* totalDebt */, 40000 /* totalEquity */); // -> 0.5
303
- interestCoverage(7500 /* ebit */, 500 /* interestExpense */); // -> 15
304
- ```
347
+ ## TypeScript Support
348
+
349
+ Full type declarations included. All input fields are optional:
305
350
 
306
- #### Efficiency
307
351
  ```typescript
308
- import { assetTurnover, inventoryTurnover } from 'finance-calculator-pro';
352
+ import type { CompanySnapshotInput, FundamentalTimeseriesInput } from 'finance-calculator-pro';
309
353
 
310
- assetTurnover(50000 /* revenue */, 100000 /* averageTotalAssets */); // -> 0.5
311
- inventoryTurnover(20000 /* costOfRevenue */, 10000 /* averageInventory */); // -> 2.0
354
+ const snapshot: CompanySnapshotInput = {
355
+ price: 150,
356
+ eps: 5,
357
+ // Every field is optional — add only what you have
358
+ };
312
359
  ```
313
360
 
314
- #### Risk & Insights
361
+ **`CompanySnapshotInput` fields:**
362
+
315
363
  ```typescript
316
- import { altmanZScore, sharpe, targetUpside, grahamNumber } from 'finance-calculator-pro';
317
-
318
- // Altman Z-Score
319
- altmanZScore(
320
- 15000 /* workingCapital */,
321
- 20000 /* retainedEarnings */,
322
- 7500 /* ebit */,
323
- 150000 /* marketValueEquity */,
324
- 50000 /* sales */,
325
- 100000 /* totalAssets */,
326
- 60000 /* totalLiabilities */
327
- ); // -> 2.707
328
-
329
- sharpe(0.12 /* return */, 0.04 /* riskFree */, 0.15 /* stdDev */); // -> 0.533
330
- targetUpside(150 /* currentPrice */, 180 /* targetPrice */); // -> 0.20 (20% upside)
331
- grahamNumber(5 /* eps */, 20 /* bookValuePerShare */); // -> 47.43
364
+ interface CompanySnapshotInput {
365
+ // Pricing
366
+ price?: number;
367
+ marketCap?: number;
368
+ eps?: number;
369
+ bookValuePerShare?: number;
370
+ revenuePerShare?: number;
371
+ annualDividendPerShare?: number;
372
+ analystTargetPrice?: number;
373
+
374
+ // Income Statement
375
+ totalRevenue?: number;
376
+ grossProfit?: number;
377
+ operatingIncome?: number;
378
+ netIncome?: number;
379
+ freeCashFlow?: number;
380
+ operatingCashFlow?: number;
381
+ ebitda?: number;
382
+ ebit?: number;
383
+ costOfRevenue?: number;
384
+ interestExpense?: number;
385
+ expectedEarningsGrowthRate?: number;
386
+
387
+ // Balance Sheet
388
+ totalAssets?: number;
389
+ totalLiabilities?: number;
390
+ totalEquity?: number;
391
+ totalDebt?: number;
392
+ longTermDebt?: number;
393
+ cashAndEquivalents?: number;
394
+ inventory?: number;
395
+ tradeReceivables?: number;
396
+ workingCapital?: number;
397
+ retainedEarnings?: number;
398
+ sharesOutstanding?: number;
399
+ taxRate?: number;
400
+
401
+ // Risk / Portfolio
402
+ returns?: number;
403
+ riskFree?: number;
404
+ stdDev?: number;
405
+ }
332
406
  ```
333
407
 
334
- #### Timeseries / Growth Trends
335
- The growth modules return chronological arrays representing growth from the previous period. For $N$ inputs, they return an array of length $N-1$.
408
+ ---
409
+
410
+ ## API Summary
411
+
412
+ | Function | Category | Description |
413
+ |---|---|---|
414
+ | `analyzeCompany(data, insights?)` | All-in-one | All 7 categories at once |
415
+ | `analyzeValuation(data, insights?)` | Valuation | P/E, P/B, P/S, PEG, EV/EBITDA, Graham, P/CF, EY, EV/Rev, EV/FCF |
416
+ | `analyzeProfitability(data, insights?)` | Profitability | ROA, ROE, ROIC, all margins |
417
+ | `analyzeLiquidity(data, insights?)` | Liquidity | Current, Quick, D/E, Interest Coverage |
418
+ | `analyzeSolvency(data, insights?)` | Solvency | Net Debt, Net Debt/EBITDA, Debt/Assets |
419
+ | `analyzeEfficiency(data, insights?)` | Efficiency | Asset Turnover, Inventory, Receivables, DSO |
420
+ | `analyzeRisk(data, insights?)` | Risk | Altman Z-Score, Sharpe, Piotroski F-Score |
421
+ | `analyzeQuality(data, insights?)` | Quality | Payout Ratio, Cash Conversion Ratio |
422
+ | `analyzeBatch(dataArray, insights?)` | Batch | Array of snapshots → array of analyses |
423
+ | `analyzeFundamentalTrends(data, period)` | Timeseries | YoY/QoQ growth, CAGR, margin trends |
336
424
 
337
- ```typescript
338
- import { calculateGrowthRate, yoyGrowth, qoqGrowth, cagr } from 'finance-calculator-pro';
425
+ ---
339
426
 
340
- // Base YoY historical array mapping
341
- yoyGrowth([40000, 45000, 50000] /* chronologicalDataPoints */); // -> [0.125, 0.1111]
427
+ ## Why finance-calculator-pro?
342
428
 
343
- // Base QoQ trailing historical array mapping
344
- qoqGrowth([10000, 10500, 12000, 11000] /* chronologicalDataPoints */); // -> [0.05, 0.1428, -0.0833]
429
+ | Feature | finance-calculator-pro |
430
+ |---|---|
431
+ | Dependencies | **Zero** |
432
+ | Bundle size | **< 20 KB** (tree-shakeable) |
433
+ | TypeScript | **Full types included** |
434
+ | Return type | `number \| null` (never throws) |
435
+ | Insights engine | **Built-in** (value + status + insight) |
436
+ | Batch processing | **Yes** |
437
+ | Timeseries / growth | **Yes** |
438
+ | Browser / Edge compatible | **Yes** |
439
+ | ESM + CJS | **Both** |
345
440
 
346
- // CAGR (Beginning Value, Ending Value, Periods)
347
- cagr(40000 /* beginningValue */, 50000 /* endingValue */, 2 /* periods */); // -> 0.118 (11.8%)
348
- ```
441
+ ---
442
+
443
+ ## License
444
+
445
+ MIT © [Boffin Coders](https://boffincoders.com)
446
+
447
+ ---
448
+
449
+ ## Keywords
450
+
451
+ financial ratios · stock analysis · fundamental analysis · valuation metrics · P/E ratio · price-to-earnings · price-to-book · EV/EBITDA · enterprise value · DCF · discounted cash flow · Graham number · Altman Z-Score · Piotroski F-Score · Sharpe ratio · ROE · ROA · ROIC · profit margin · liquidity ratio · debt-to-equity · solvency · current ratio · quick ratio · asset turnover · days sales outstanding · payout ratio · cash conversion ratio · earnings yield · stock screener · investment analysis · equity analysis · portfolio analysis · FinTech · financial calculator · TypeScript · JavaScript · Node.js