### Install and Initialize Finance.js
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/START_HERE.md
Install the library using npm and initialize it with a new instance. This library requires zero configuration.
```javascript
npm install financejs
const Finance = require('financejs');
const finance = new Finance();
```
--------------------------------
### Install Finance.js
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/README.md
Install the Finance.js library using npm. This command is used for project setup.
```bash
npm install financejs
```
--------------------------------
### Basic Usage Example (TypeScript)
Source: https://github.com/ebradyjobory/finance.js/blob/master/README.md
Demonstrates how to import and use the Finance.js library with TypeScript syntax.
```typescript
import { Finance } from 'financejs'
let finance = new Finance();
// To calculate Amortization
finance.AM(20000, 7.5, 5, 0);
// => 400.76
```
--------------------------------
### Basic Usage Example (CommonJS)
Source: https://github.com/ebradyjobory/finance.js/blob/master/README.md
Demonstrates how to import and use the Finance.js library with CommonJS module syntax.
```javascript
var Finance = require('financejs');
var finance = new Finance();
// To calculate Amortization
finance.AM(20000, 7.5, 5, 0);
// => 400.76
```
--------------------------------
### Instantiate Finance.js with TypeScript
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/configuration.md
Import and create an instance of the Finance class using TypeScript. This is the only setup required.
```typescript
import { Finance } from 'financejs';
const finance = new Finance();
```
--------------------------------
### Instantiate Finance.js with CommonJS
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/configuration.md
Import and create an instance of the Finance class using CommonJS modules. This is the only setup required.
```javascript
const Finance = require('financejs');
const finance = new Finance();
```
--------------------------------
### Related Metrics Calculation Examples
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/DebtAndCapital.md
Demonstrates the calculation of related financial metrics such as Debt-to-Equity Ratio, Debt-to-Income Ratio, and Leverage Ratio.
```javascript
const finance = new Finance();
// Debt-to-Equity Ratio (similar, slightly different)
const totalAssets = 3000000;
const totalDebt = 1500000;
const totalEquity = totalAssets - totalDebt;
const debtToEquity = totalDebt / totalEquity;
// => 1.5 (debt is 1.5x equity)
// Debt-to-Income Ratio (personal finance)
const personalDebt = 100000;
const personalIncome = 75000;
const debtToIncome = personalDebt / personalIncome;
// => 1.33 or 133%
// Leverage Ratio (what this method calculates)
const lr = finance.LR(50000, 100000, 75000);
// => 2.0 ($2 of obligations per $1 of income)
```
--------------------------------
### Quarterly Compounding Example
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/GrowthAndRates.md
Demonstrates calculating future value with quarterly compounding. Ensure the Finance class is instantiated before use.
```javascript
const finance = new Finance();
// Principal $1,500, rate 4.3%, compounded quarterly, 6 years
const amount = finance.CI(4.3, 4, 1500, 6);
// => 1938.84
// $1,500 grows to $1,938.84 in 6 years
```
--------------------------------
### Daily Compounding Example
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/GrowthAndRates.md
Illustrates calculating future value with daily compounding. The Finance class must be initialized before use.
```javascript
const finance = new Finance();
// $5,000 at 3% compounded daily for 10 years
const amount = finance.CI(3, 365, 5000, 10);
// => 6740.93
```
--------------------------------
### Company Leverage Ratio Example
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/DebtAndCapital.md
Calculate the leverage ratio for a company. Use total liabilities, total debts, and EBIT as inputs.
```javascript
const finance = new Finance();
// Company with:
// Total liabilities: $2,000,000
// Long-term debt: $1,000,000
// EBIT (earnings before interest/taxes): $500,000
const lr = finance.LR(2000000, 1000000, 500000);
// => 6.0
// High leverage: $6 of obligations per $1 of income
```
--------------------------------
### TypeScript Usage with Finance.js
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/README.md
Demonstrates how to import and use Finance.js with full TypeScript type support. Ensure you have the 'financejs' package installed.
```typescript
import { Finance } from 'financejs';
const finance = new Finance();
// Fully typed method calls
const pv: number = finance.PV(5, 100);
const fv: number = finance.FV(0.5, 1000, 12);
const df: number[] = finance.DF(10, 6);
```
--------------------------------
### Monthly Compounding Example
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/GrowthAndRates.md
Shows how to calculate future value with monthly compounding. Instantiate the Finance class prior to calling this method.
```javascript
const finance = new Finance();
// $10,000 at 2.5% compounded monthly for 5 years
const amount = finance.CI(2.5, 12, 10000, 5);
// => 11312.28
```
--------------------------------
### Compare Payback Period and NPV
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/ProjectEvaluation.md
This example demonstrates how to calculate both the Payback Period (speed of investment recovery) and Net Present Value (overall project profitability considering time value of money).
```javascript
const finance = new Finance();
// Payback Period: how fast to break even
const payback = finance.PP(0, -100, 50);
// => 2 years
// NPV: what's project worth (accounting for time & all cash)
const npv = finance.NPV(10, -100, 50, 50, 30, 20);
// => 5.27
// Project creates $5.27 of value despite longer payback
```
--------------------------------
### Individual Leverage Ratio Example
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/DebtAndCapital.md
Calculate the leverage ratio for an individual. Ensure you input personal liabilities, debts, and annual income.
```javascript
const finance = new Finance();
// Person with:
// Liabilities (credit card, mortgage): $25,000
// Other debts (student loans): $10,000
// Annual income: $20,000
const lr = finance.LR(25, 10, 20);
// => 1.75
// Leverage ratio of 1.75
```
--------------------------------
### Calculate NPV for Project Rejection
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/TimeValueOfMoney.md
This example demonstrates calculating NPV for a project where the expected returns are insufficient to cover the initial investment and the required rate of return, leading to a negative NPV.
```javascript
const finance = new Finance();
// Investment $100,000, returns only $30k, $30k, $30k at 10% rate
const npv = finance.NPV(10, -100000, 30000, 30000, 30000);
// => -7298.36
// Interpretation: Project destroys value (reject it)
```
--------------------------------
### Industry Comparison Leverage Ratios
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/DebtAndCapital.md
Compare leverage ratios across different industries. This example demonstrates calculations for financial institutions, utilities, technology companies, and retail.
```javascript
const finance = new Finance();
// Financial institutions (banks, insurance): High leverage is normal
// Leverage: 10+
// Utilities: Moderate to high leverage (stable cash flows)
const utility = finance.LR(500000, 1500000, 1000000);
// => 2.0
// Technology companies: Low leverage (fast growth, high equity)
const tech = finance.LR(200000, 100000, 800000);
// => 0.375
// Retail: Moderate leverage (competitive industry)
const retail = finance.LR(300000, 700000, 500000);
// => 2.0
```
--------------------------------
### Calculate XIRR for Stock Investment with Dividends
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/ReturnAnalysis.md
This example demonstrates calculating the XIRR for a stock investment that includes initial purchase, dividend receipts, and a final sale. It highlights how to structure the cash flows and dates for a scenario involving multiple transactions over time.
```javascript
const finance = new Finance();
// Jan 1 2020: Buy stock for $10,000
// Dec 15 2020: Receive dividend $500
// Dec 15 2021: Receive dividend $600
// Jan 15 2022: Sell for $12,000
const xirr = finance.XIRR(
[-10000, 500, 600, 12000],
[
new Date(2020, 0, 1),
new Date(2020, 11, 15),
new Date(2021, 11, 15),
new Date(2022, 0, 15)
],
0
);
// => 8.27 (approximately)
```
--------------------------------
### Calculate ROI for Real Estate Investment
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/ReturnAnalysis.md
This example shows how to calculate the ROI for a real estate investment. It uses the ROI method with the purchase price and sale price to determine the percentage return.
```javascript
const finance = new Finance();
// Purchased property for $300,000, sold for $400,000
const roi = finance.ROI(-300000, 400000);
// => 33.33
// 33.33% return on investment
```
--------------------------------
### Immediate Calculation After Instantiation
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/configuration.md
After instantiating Finance.js, calculations can be performed immediately without any further setup. This highlights the library's stateless and configuration-free design.
```javascript
// This is the only setup needed:
const finance = new Finance();
// Immediately start making calculations:
const pv = finance.PV(5, 100);
const fv = finance.FV(0.5, 1000, 12);
const npv = finance.NPV(10, -500000, 200000, 300000, 200000);
```
--------------------------------
### IAR Example: Real Estate Investment
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/ReturnAnalysis.md
Shows how to calculate the inflation-adjusted return for a real estate investment, considering property appreciation and inflation.
```javascript
const finance = new Finance();
// Property appreciation: 4%, Inflation rate: 2.5%
const realReturn = finance.IAR(0.04, 0.025);
// => 1.463 (approximately)
```
--------------------------------
### API Reference File Structure
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/GUIDE.md
Each method documentation file includes a signature, parameters, return values, formulas, examples, use cases, related methods, and source location.
```markdown
## METHOD_NAME — Full Name
Short description of what the method does.
### Signature
Code block with TypeScript signature
### Parameters
Table with columns: Parameter | Type | Required | Default | Description
### Returns
Description of return value and type
### Formula
Mathematical formula (if applicable)
### Examples
Usually 2-3 realistic usage examples
### Use Cases
When you'd actually use this method
### Related Methods
Links to other methods you might use together
### Source
File location and line number in source code
```
--------------------------------
### Using Fractional Rates with PMT in Finance.js
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/README.md
The PMT method is an exception and accepts fractional rates. For example, use 0.02 for 2%.
```javascript
finance.PMT(0.02, 36, -1000000);
// 2% fractional rate
```
--------------------------------
### JavaScript Number Parameter Type Example
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/INDEX.md
Demonstrates the use of JavaScript numbers for parameters, where rates are expressed as percentages (e.g., 5 for 5%).
```javascript
finance.PV(5, 100); // 5% rate (not 0.05)
```
--------------------------------
### Manufacturing Firm Leverage Ratio Example
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/DebtAndCapital.md
Calculate the leverage ratio for a manufacturing firm. Input current liabilities, long-term debt, and EBIT.
```javascript
const finance = new Finance();
// Manufacturer with:
// Current liabilities: $500,000
// Long-term debt: $1,500,000
// EBIT: $400,000
const lr = finance.LR(500000, 1500000, 400000);
// => 5.0
// $5 of obligations per $1 of operating income
```
--------------------------------
### IAR Example: Typical Savings Account
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/ReturnAnalysis.md
Demonstrates calculating the inflation-adjusted return for a typical savings account with a low investment return and a slightly higher inflation rate.
```javascript
const finance = new Finance();
// Investment return: 1.5%, Inflation rate: 2.0%
const realReturn = finance.IAR(0.015, 0.020);
// => -0.493 (approximately)
// You're actually losing 0.493% in purchasing power
```
--------------------------------
### IAR Example: Stock Market Returns
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/ReturnAnalysis.md
Illustrates calculating the inflation-adjusted return for a stock market investment, showing a positive real return after inflation.
```javascript
const finance = new Finance();
// Investment return: 8%, Inflation rate: 3%
const realReturn = finance.IAR(0.08, 0.03);
// => 4.854368932038833
// Real return is about 4.85% in today's dollars
```
--------------------------------
### IAR Example: Nominal Return vs. Inflation
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/ReturnAnalysis.md
Highlights a scenario where a positive nominal return is eroded by higher inflation, resulting in a negative real return.
```javascript
const finance = new Finance();
// Savings at 2%, but inflation at 5%
const nominalReturn = 0.02; // 2% nominal
const inflationRate = 0.05; // 5% inflation
const realReturn = finance.IAR(nominalReturn, inflationRate);
// => -2.857
// Lost 2.857% in purchasing power
```
--------------------------------
### Calculate Auto Loan Payment
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/TimeValueOfMoney.md
This example demonstrates calculating the monthly payment for an auto loan. The rate should be the monthly interest rate, and the principal should represent the loan amount.
```javascript
const finance = new Finance();
// $25,000 car loan at 0.5% monthly (6% annual), 60 months
const monthlyPayment = finance.PMT(0.005, 60, -25000);
// => 460.48
```
--------------------------------
### Calculate Stock Present Value (High Growth)
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/GrowthAndRates.md
This example demonstrates calculating the present value for a high-growth stock. Ensure you provide the expected growth rate, required return, and current dividend.
```javascript
const finance = new Finance();
// Current dividend: $2 per share
// Growth rate: 8% annually
// Required return: 12%
const stockValue = finance.stockPV(8, 12, 2);
// => 52
// Stock intrinsic value: $52 per share
```
--------------------------------
### IRR Method Input Object Example
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/types.md
Demonstrates the structure of the input object for the IRR method, including maximum iterations and an array of cash flows. Ensure cashFlow contains at least one positive and one negative value.
```typescript
{
depth: number; // Maximum iterations (e.g., 10000)
cashFlow: number[]; // Array of cash flows
}
```
```javascript
const data = {
depth: 10000,
cashFlow: [-6, 297, 307]
};
finance.IRR(data);
```
--------------------------------
### Quick Reference: Methods by Input Pattern (Simple)
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/GUIDE.md
Lists methods that accept a small, fixed number of parameters, categorized by the number and type of inputs.
```markdown
**Methods taking just 2-3 parameters:**
- R72(rate)
- ROI(investment, earnings)
- PV(rate, cashFlow)
- FV(rate, cashFlow, periods)
- LR(liabilities, debts, income)
- CAPM(riskFreeRate, beta, marketReturn)
- CI(rate, compoundings, principal, periods)
- CAGR(beginning, ending, periods)
- stockPV(growth, return, dividend)
```
--------------------------------
### PV, FV, and NPV Calculations
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/TimeValueOfMoney.md
Demonstrates how to use PV for discounting, FV for projecting, and NPV for project evaluation based on different financial scenarios. Ensure the Finance class is instantiated.
```javascript
const finance = new Finance();
// 1. Single future cash flow?
// → Use PV to discount to today
const pv = finance.PV(10, 100000, 5);
// 2. Current investment growing?
// → Use FV to project forward
const fv = finance.FV(10, 100000, 5);
// 3. Multiple cash flows and initial investment?
// → Use NPV for project evaluation
const npv = finance.NPV(10, -500000, 200000, 300000, 200000);
```
--------------------------------
### Instantiate and Use Finance Class
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/types.md
Demonstrates how to import and instantiate the Finance class to perform calculations. Ensure the 'financejs' library is imported.
```typescript
import { Finance } from 'financejs';
const finance = new Finance();
const pv = finance.PV(5, 100);
```
--------------------------------
### Run Tests with npm
Source: https://github.com/ebradyjobory/finance.js/blob/master/README.md
Execute the test suite for the Finance.js library using npm.
```bash
npm test
```
--------------------------------
### Using Percentage Rates in Finance.js
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/README.md
Demonstrates how to use percentage rates for most methods like PV. Ensure rates are provided as percentages.
```javascript
finance.PV(5, 100);
// 5% interest rate
```
```javascript
finance.CAGR(10000, 19500, 3);
// compound growth rate calculation
```
--------------------------------
### Batch PV Calculations and Sensitivity Table
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/TimeValueOfMoney.md
Shows how to calculate Present Value (PV) for multiple discount rates using Array.map and then create a sensitivity table. Requires the Finance class to be instantiated.
```javascript
const finance = new Finance();
// Calculate PV for multiple discount rates
const rates = [3, 5, 7, 10, 15];
const futureAmount = 100000;
const periods = 5;
const presentValues = rates.map(rate =>
finance.PV(rate, futureAmount, periods)
);
// => [86261.30, 78352.60, 71299.52, 62092.13, 49850.32]
// Create sensitivity table
const table = rates.map((rate, i) => ({
discountRate: rate + '%',
presentValue: presentValues[i]
}));
console.table(table);
```
--------------------------------
### Manual NPV Construction with Reusable Discount Factors
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/ProjectEvaluation.md
Shows how to generate discount factors once and then apply them to multiple cash flow scenarios for NPV calculations. This is efficient for analyzing various financial situations with a consistent discount rate.
```javascript
const finance = new Finance();
// Create reusable discount factors
const dfs = finance.DF(12, 10);
// => [1, 0.893, 0.797, 0.712, 0.636, 0.567, 0.507, 0.452, 0.404, 0.361]
// Apply to different cash flow scenarios
function calculateNPV(cashFlows, dfs) {
return cashFlows.reduce((sum, cf, i) => sum + cf * dfs[i], 0);
}
const scenario1 = [-100000, 30000, 30000, 30000, 30000];
const scenario2 = [-100000, 25000, 30000, 40000, 35000];
const scenario3 = [-100000, 20000, 20000, 60000, 30000];
console.log('Scenario 1 NPV:', calculateNPV(scenario1, dfs));
console.log('Scenario 2 NPV:', calculateNPV(scenario2, dfs));
console.log('Scenario 3 NPV:', calculateNPV(scenario3, dfs));
```
--------------------------------
### Quick Reference: Methods by Input Pattern (Variable)
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/GUIDE.md
Lists methods that accept a variable number of parameters, often indicated by ellipses (...).
```markdown
**Methods taking variable parameters:**
- NPV(rate, investment, ...cashFlows)
- PI(rate, investment, ...cashFlows)
- PP(periods, ...cashFlows)
- IRR({depth, cashFlow})
- AM(principal, rate, period, yearOrMonth, payAtBeginning?)
```
--------------------------------
### JavaScript Decimal Rate Parameter Type Example
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/INDEX.md
Illustrates that certain methods like PMT and IAR use decimal rates (e.g., 0.02 for 2%).
```javascript
finance.PMT(0.02, 36, -1000000); // 0.02 = 2%
```
--------------------------------
### Calculate Mortgage Payment and Total Interest
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/DebtAndCapital.md
Calculates the monthly payment for a home mortgage and provides an example of how to determine the total amount paid and total interest over the life of the loan.
```javascript
const finance = new Finance();
// Home purchase: $300,000
// Mortgage rate: 4.5%
// Term: 30 years
const monthlyPayment = finance.AM(300000, 4.5, 30, 0);
// => 1520.06
// Total paid: 360 × $1520.06 = $547,221.60
// Total interest: $247,221.60
```
--------------------------------
### Batch Processing with PV
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/TimeValueOfMoney.md
Shows how to use the PV function in a batch process to calculate present values for multiple discount rates and create a sensitivity table.
```APIDOC
## Batch Processing with PV
This example demonstrates how to perform batch calculations using the PV function, such as calculating present values for a series of discount rates and generating a sensitivity table.
### Method:
`PV(rate, futureAmount, periods)`
### Example Usage:
```javascript
const finance = new Finance();
const rates = [3, 5, 7, 10, 15];
const futureAmount = 100000;
const periods = 5;
// Calculate PV for multiple discount rates
const presentValues = rates.map(rate =>
finance.PV(rate, futureAmount, periods)
);
// Create a sensitivity table
const table = rates.map((rate, i) => ({
discountRate: rate + '%',
presentValue: presentValues[i]
}));
console.table(table);
```
### Output:
(The output will be a table showing discount rates and their corresponding present values.)
```
--------------------------------
### Finance.js No Dependencies
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/configuration.md
Demonstrates that Finance.js has no external runtime dependencies, as indicated by an empty dependencies object in package.json.
```json
{
"dependencies": {}
}
```
--------------------------------
### Trigger IRR Error: Convergence Failure
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/errors.md
This example demonstrates how the IRR calculation might fail to converge if the 'depth' parameter is set too low for the given cash flow pattern.
```javascript
const finance = new Finance();
// This might throw if depth is too small for the cash flow pattern
try {
finance.IRR({
depth: 10, // Very low limit
cashFlow: [-6, 297, 307]
});
} catch (e) {
console.error(e.message);
// Might be "IRR can't find a result"
}
```
--------------------------------
### Rank Projects by Profitability Index
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/ProjectEvaluation.md
Demonstrates how to rank multiple investment projects based on their Profitability Index. This is useful for capital rationing, allowing selection of projects that offer the best return per dollar invested within a budget.
```javascript
const finance = new Finance();
const projects = [
{ name: 'A', investment: -100000, flows: [40000, 40000, 40000] },
{ name: 'B', investment: -50000, flows: [20000, 20000, 20000] },
{ name: 'C', investment: -75000, flows: [30000, 30000, 30000] }
];
const rate = 10;
// Rank by Profitability Index
const rankings = projects.map(p => ({
name: p.name,
pi: finance.PI(rate, p.investment, ...p.flows)
})).sort((a, b) => b.pi - a.pi);
console.log(rankings);
// Select highest PI projects within capital budget
```
--------------------------------
### Quick Reference: Methods by Category
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/GUIDE.md
A table listing financial methods, their corresponding files, and a brief purpose. Useful for quickly finding a method by its category.
```markdown
| Method | File | Purpose |
|--------|------|---------|
| PV | TimeValueOfMoney.md | Present value of future cash |
| FV | TimeValueOfMoney.md | Future value of investment |
| NPV | TimeValueOfMoney.md | Net present value of project |
| PMT | TimeValueOfMoney.md | Periodic loan payment |
| IRR | ReturnAnalysis.md | Internal rate of return |
| XIRR | ReturnAnalysis.md | IRR with irregular dates |
| ROI | ReturnAnalysis.md | Return on investment % |
| CAPM | ReturnAnalysis.md | Expected return vs risk |
| IAR | ReturnAnalysis.md | Real return after inflation |
| CAGR | GrowthAndRates.md | Compound annual growth rate |
| CI | GrowthAndRates.md | Compound interest |
| R72 | GrowthAndRates.md | Rule of 72 (years to double) |
| stockPV | GrowthAndRates.md | Stock value with dividends |
| PP | ProjectEvaluation.md | Payback period |
| PI | ProjectEvaluation.md | Profitability index |
| DF | ProjectEvaluation.md | Discount factors |
| AM | DebtAndCapital.md | Amortization/loan payment |
| LR | DebtAndCapital.md | Leverage ratio |
| WACC | DebtAndCapital.md | Weighted average cost of capital |
```
--------------------------------
### Quick Reference: Methods Taking Dates
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/GUIDE.md
Highlights methods that require date inputs, such as XIRR for irregular cash flow timing.
```markdown
**Methods taking dates:**
- XIRR(cashFlows, dates, guess)
```
--------------------------------
### CAPM Calculation - Stock with Market Beta
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/ReturnAnalysis.md
Calculates the expected return for a stock with a beta of 1.0, indicating it moves in line with the market. This example uses a risk-free rate of 2% and an expected market return of 10%.
```javascript
const finance = new Finance();
// Risk-free rate: 2%, Beta: 1.0 (moves with market), Market return: 10%
const expectedReturn = finance.CAPM(2, 1, 10);
// => 0.08 (8% expected return)
// Stock is expected to return the market average
```
--------------------------------
### Safe XIRR and PV Error Handling
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/errors.md
Demonstrates how to safely handle potential null returns from XIRR (non-convergence) and NaN returns from PV (invalid inputs) by checking the results before proceeding.
```javascript
const finance = new Finance();
const xirr = finance.XIRR(cashFlows, dates, 0);
if (xirr === null) {
console.error('XIRR did not converge');
}
const pv = finance.PV(rate, cashFlow, periods);
if (!isFinite(pv)) {
console.error('PV calculation failed; check input values');
}
```
--------------------------------
### Handle IRR Missing Value Signs Error
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/errors.md
This example demonstrates how to safely calculate IRR by first verifying that the cash flow array contains both positive and negative values. If not, it returns null and logs a warning.
```javascript
const finance = new Finance();
function calculateIRRSafely(cashFlows, depth = 10000) {
// Verify cash flows contain both positive and negative values
const hasPositive = cashFlows.some(cf => cf > 0);
const hasNegative = cashFlows.some(cf => cf < 0);
if (!hasPositive || !hasNegative) {
console.warn('Cannot calculate IRR: cash flows must include both positive and negative values');
return null;
}
return finance.IRR({
depth: depth,
cashFlow: cashFlows
});
}
// Usage:
const result = calculateIRRSafely([100, 200, 300]); // Returns null
const result2 = calculateIRRSafely([-500, 300, 200]); // Calculates IRR
```
--------------------------------
### Calculate CAGR - Economic Growth
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/GrowthAndRates.md
Calculate the compound annual growth rate for economic indicators like GDP. This example shows how to apply the CAGR method to large values representing economic growth over a period of years.
```javascript
const finance = new Finance();
// GDP: $20 trillion → $28 trillion over 5 years
const cagr = finance.CAGR(20000000000000, 28000000000000, 5);
// => 7.00
// 7.00% annual GDP growth
```
--------------------------------
### Use Rate Parameters in Finance.js
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/configuration.md
Pass interest rates as percentages directly to methods like PV and FV. Ensure the rate is correctly formatted as a percentage.
```javascript
finance.PV(5, 100); // 5% interest rate
finance.FV(0.5, 1000, 12); // 0.5% interest rate
```
--------------------------------
### Calculate PI for a Profitable Project
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/ProjectEvaluation.md
Demonstrates calculating the Profitability Index for a project with a positive PI value, indicating profitability. Ensure the 'Finance' class is instantiated and the correct parameters (discount rate, initial investment, and cash flows) are provided.
```javascript
const finance = new Finance();
// Initial investment: -$40,000
// Cash flows: $18k, $12k, $10k, $9k, $6k
// Discount rate: 10%
const pi = finance.PI(10, -40000, 18000, 12000, 10000, 9000, 6000);
// => 1.09
// For every $1 invested, gain $1.09 in present value
// Project is profitable
```
--------------------------------
### CAPM Calculation - Aggressive Stock
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/ReturnAnalysis.md
Calculates the expected return for an aggressive stock with a beta greater than 1 (2.5), indicating higher volatility than the market. This example uses a 2% risk-free rate and a 10% expected market return.
```javascript
const finance = new Finance();
// Tech startup with β = 2.5 (2.5x market volatility)
const expectedReturn = finance.CAPM(2, 2.5, 10);
// => 0.22 (22% expected return)
// Higher risk = higher expected return
```
--------------------------------
### Basic Usage with CommonJS
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/README.md
Demonstrates basic usage of the Finance.js library with CommonJS modules. Calculates Present Value (PV) with a given rate and cash flow.
```javascript
// CommonJS
const Finance = require('financejs');
const finance = new Finance();
// Calculate Present Value
finance.PV(5, 100); // Rate 5%, cash flow $100
// => 95.24
```
--------------------------------
### CAPM Calculation - Defensive Stock
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/ReturnAnalysis.md
Calculates the expected return for a defensive stock with a beta less than 1 (0.7), signifying lower volatility than the market. The example uses a 2% risk-free rate and a 10% expected market return.
```javascript
const finance = new Finance();
// Utility stock with β = 0.7 (less volatile than market)
const expectedReturn = finance.CAPM(2, 0.7, 10);
// => 0.062 (6.2% expected return)
// Lower risk = lower expected return
```
--------------------------------
### Basic Usage with ES Modules/TypeScript
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/README.md
Demonstrates basic usage of the Finance.js library with ES Modules or TypeScript. Calculates Present Value (PV) with a given rate and cash flow.
```typescript
// ES Modules / TypeScript
import { Finance } from 'financejs';
const finance = new Finance();
finance.PV(5, 100);
// => 95.24
```
--------------------------------
### Trigger IRR Error: Missing Value Signs
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/errors.md
These examples show how to trigger the 'IRR requires at least one positive value and one negative value' error by providing cash flow arrays with only positive or only negative values.
```javascript
const finance = new Finance();
// This throws - all positive values
try {
finance.IRR({
depth: 10000,
cashFlow: [100, 200, 300] // All positive
});
} catch (e) {
console.error(e.message);
// => "IRR requires at least one positive value and one negative value"
}
```
```javascript
const finance = new Finance();
// This throws - all negative values
try {
finance.IRR({
depth: 10000,
cashFlow: [-100, -200, -300] // All negative
});
} catch (e) {
console.error(e.message);
// => "IRR requires at least one positive value and one negative value"
}
```
--------------------------------
### Browser Integration with Finance.js
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/README.md
Shows how to include Finance.js in an HTML file and use its methods in a browser environment. This requires the 'finance.js' script to be loaded.
```html
```
--------------------------------
### PV, FV, and NPV Functions
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/TimeValueOfMoney.md
Demonstrates the basic usage of PV, FV, and NPV functions for different financial calculations.
```APIDOC
## PV, FV, and NPV Functions
This section illustrates how to use the core Time Value of Money functions: PV, FV, and NPV.
### Use Cases:
- **PV**: To determine the current worth of a future sum of money.
- **FV**: To calculate the future value of a present investment.
- **NPV**: To evaluate the profitability of a project by considering all cash flows and the discount rate.
### Method Signatures (Inferred from examples):
- `PV(rate, futureAmount, periods)`
- `FV(rate, presentAmount, periods)`
- `NPV(rate, ...cashFlows)`
### Example Usage:
```javascript
const finance = new Finance();
// Calculate Present Value
const pv = finance.PV(10, 100000, 5);
// Calculate Future Value
const fv = finance.FV(10, 100000, 5);
// Calculate Net Present Value for a project
const npv = finance.NPV(10, -500000, 200000, 300000, 200000);
```
```
--------------------------------
### Finance.js File Organization Structure
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/GUIDE.md
This tree structure outlines the organization of the finance.js documentation files, including the main navigation hub, README, guide, type definitions, configuration, error reference, and API reference categorized by financial concepts.
```tree
/output/
│
├── INDEX.md
│ └── Navigation hub with links to all docs
│ Use this to find what you need
│
├── README.md
│ └── Project overview and quick start
│ Start here if brand new
│
├── GUIDE.md (this file)
│ └── How to use the reference
│
├── types.md
│ └── TypeScript definitions and conventions
│ Use if working with TypeScript
│
├── configuration.md
│ └── Setup information (zero config)
│ Use if setting up the library
│
├── errors.md
│ └── Error reference and patterns
│ Use when you hit an error
│
└── api-reference/
├── Finance.md
│ └── All 18 methods A-Z
│ Use for quick method lookup
│
├── TimeValueOfMoney.md
│ └── PV, FV, NPV, PMT + comparisons
│ Use when working with time value
│
├── ReturnAnalysis.md
│ └── IRR, XIRR, ROI, CAPM, IAR + patterns
│ Use when measuring returns
│
├── GrowthAndRates.md
│ └── CAGR, CI, R72, stockPV + examples
│ Use when projecting growth
│
├── ProjectEvaluation.md
│ └── PP, PI, DF + decision framework
│ Use when evaluating projects
│
└── DebtAndCapital.md
└── AM, LR, WACC + capital structure
Use when analyzing debt/capital
```
--------------------------------
### Quick Reference: Methods Returning Arrays
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/GUIDE.md
Identifies methods that return an array of numbers, such as discount factors.
```markdown
**Methods returning arrays:**
- DF() returns number[]
```
--------------------------------
### Calculate Basic Investment Growth
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/TimeValueOfMoney.md
Demonstrates how to calculate the future value of an investment with a given annual rate and number of years. Requires initializing the Finance class.
```javascript
const finance = new Finance();
// If I invest $1,000 at 0.5% annual rate for 12 years, how much will I have?
const fv = finance.FV(0.5, 1000, 12);
// => 1061.68
```
--------------------------------
### Calculate CAGR - Stock Investment
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/GrowthAndRates.md
Use the CAGR method to calculate the compound annual growth rate for a stock investment. This example shows how to determine the annual growth rate when an initial investment grows to a final value over a specified number of years.
```javascript
const finance = new Finance();
// Investment: $10,000 → $19,500 over 3 years
const cagr = finance.CAGR(10000, 19500, 3);
// => 24.93
// 24.93% annual compound growth
```
--------------------------------
### Compare Projects using PI vs NPV
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/ProjectEvaluation.md
Illustrates how the Profitability Index (PI) can be a better metric than Net Present Value (NPV) for comparing projects of different sizes, especially under capital constraints. PI focuses on return per dollar invested.
```javascript
const finance = new Finance();
// Project A: Large investment
const npvA = finance.NPV(10, -1000000, 300000, 300000, 300000, 300000, 300000);
// => 137,240.79 (large NPV)
const piA = finance.PI(10, -1000000, 300000, 300000, 300000, 300000, 300000);
// => 1.14 (moderate PI)
// Project B: Small investment
const npvB = finance.NPV(10, -50000, 20000, 20000, 20000, 20000, 20000);
// => 25,810.42 (smaller NPV, but still positive)
const piB = finance.PI(10, -50000, 20000, 20000, 20000, 20000, 20000);
// => 1.52 (higher PI)
// With limited capital:
// Choose Project B (higher return per dollar)
// even though Project A has higher absolute NPV
```
--------------------------------
### CAGR vs ROI Comparison
Source: https://github.com/ebradyjobory/finance.js/blob/master/_autodocs/api-reference/GrowthAndRates.md
Compare the Compound Annual Growth Rate (CAGR) with the simple Return on Investment (ROI). This snippet highlights how CAGR provides an annualized perspective, while ROI shows the total return over the entire period, illustrating the difference with an example investment.
```javascript
const finance = new Finance();
// ROI shows total return regardless of time
const roi = finance.ROI(-10000, 19500);
// => 95 (95% total return)
// CAGR shows average annual return
const cagr = finance.CAGR(10000, 19500, 3);
// => 24.93 (24.93% per year)
// Over 3 years at 24.93% compound:
// Year 1: 10,000 × 1.2493 = 12,493
// Year 2: 12,493 × 1.2493 = 15,609
// Year 3: 15,609 × 1.2493 = 19,500
```