npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@uedfx/financial-calculators

v1.1.1

Published

Professional-grade financial calculators for real estate, private equity, venture capital, and startup finance. Pure TypeScript functions with no dependencies.

Downloads

396

Readme

@uedfx/financial-calculators

Professional-grade financial calculators for startups, real estate investors, private equity, and venture capital professionals.

npm version License: MIT

Features

  • IRR & NPV - Internal Rate of Return with Newton-Raphson, NPV, MIRR, XIRR/XNPV
  • Cap Rate - Real estate cap rate with market benchmarks by property type and class
  • SAFE & Convertibles - SAFE and convertible note conversion modeling
  • LBO Modeling - Full leveraged buyout model with debt schedules and IRR/MOIC
  • Business Valuation - DCF, comparable analysis, Rule of 40, SaaS metrics
  • Loan Calculations - PMT, DSCR, LTV, amortization schedules, prepayment penalties
  • 1031 Exchange - Deadlines, boot calculations, like-kind property rules
  • Portfolio Performance - TWR (Modified Dietz & True), Sharpe/Sortino/Calmar ratios, drawdown analysis

Zero dependencies. Tree-shakeable. TypeScript-first with full type definitions.

Installation

npm install @uedfx/financial-calculators

Quick Start

import {
  calculateIRR,
  calculateCapRate,
  calculateSAFEConversion,
  calculateLBO,
  calculateDCF,
  calculateMonthlyPayment,
  calculate1031Deadlines,
  calculateTrueTWR
} from '@uedfx/financial-calculators';

// IRR Calculation
const cashFlows = [-100000, 30000, 40000, 50000, 60000];
const irr = calculateIRR(cashFlows);
console.log(irr); // 0.2354 (23.54%)

// Cap Rate
const capRate = calculateCapRate(500000, 10000000);
console.log(capRate); // 5.0 (5.0%)

// Loan Payment
const monthlyPayment = calculateMonthlyPayment(500000, 0.06, 360);
console.log(monthlyPayment); // $2,997.75

// 1031 Exchange Deadlines
const deadlines = calculate1031Deadlines(new Date('2024-06-15'));
console.log(deadlines.identificationDeadline); // July 30, 2024
console.log(deadlines.exchangeDeadline); // December 12, 2024

Modules

IRR & NPV (@uedfx/financial-calculators/irr)

import { calculateIRR, calculateNPV, calculateMIRR, calculateXIRR } from '@uedfx/financial-calculators/irr';

// Basic IRR
const irr = calculateIRR([-100000, 30000, 40000, 50000, 60000]);

// NPV at 10% discount rate
const npv = calculateNPV([-100000, 30000, 40000, 50000, 60000], 0.10);

// MIRR with different financing and reinvestment rates
const mirr = calculateMIRR(cashFlows, 0.08, 0.12); // 8% financing, 12% reinvestment

// XIRR with irregular dates
const xirr = calculateXIRR(
  [-100000, 30000, 45000, 60000],
  [new Date('2024-01-01'), new Date('2024-06-15'), new Date('2025-01-01'), new Date('2025-09-30')]
);

Cap Rate (@uedfx/financial-calculators/cap-rate)

import {
  calculateCapRate,
  calculatePropertyValue,
  getMarketBenchmark,
  assessCapRate,
  generateCapRateScenarios,
  MARKET_BENCHMARKS
} from '@uedfx/financial-calculators/cap-rate';

// Basic cap rate
const capRate = calculateCapRate(500000, 10000000); // NOI / Price

// Reverse: value from cap rate
const value = calculatePropertyValue(500000, 5.5);

// Market benchmarks
const benchmark = getMarketBenchmark('MULTIFAMILY', 'classA');
console.log(benchmark); // { low: 4.25, mid: 4.75, high: 5.25 }

// Assess a property
const assessment = assessCapRate(5.5, 'MULTIFAMILY');
console.log(assessment); // { class: 'classB', label: 'Class B', description: 'Value-add opportunity' }

// Sensitivity analysis
const scenarios = generateCapRateScenarios(500000, 10000000);
// Returns array of price impacts at different cap rate changes

Supported Property Types:

  • MULTIFAMILY - Apartment buildings
  • OFFICE - Office buildings
  • RETAIL - Shopping centers, strip malls
  • INDUSTRIAL - Warehouses, distribution centers
  • SELF_STORAGE - Storage facilities
  • HOSPITALITY - Hotels, motels

Loan Calculations (@uedfx/financial-calculators/loan)

import {
  calculateMonthlyPayment,
  calculateIOPayment,
  calculateBlendedPayment,
  calculateDSCR,
  calculateLTV,
  calculateDebtYield,
  calculatePrepayPenalty,
  calculateRemainingBalance,
  calculateTotalInterest,
  generateAmortizationSchedule,
  calculateAllInRate,
  analyzeLoan
} from '@uedfx/financial-calculators/loan';

// Monthly Payment (PMT formula - matches Excel)
const payment = calculateMonthlyPayment(500000, 0.06, 360); // $2,997.75

// Interest-Only Payment
const ioPayment = calculateIOPayment(500000, 0.06); // $2,500/mo

// Debt Service Coverage Ratio
const dscr = calculateDSCR(2000000, 1500000); // 1.33x

// Loan-to-Value
const ltv = calculateLTV(7500000, 10000000); // 75%

// Prepayment Penalty (Step-down)
const penalty = calculatePrepayPenalty(1000000, 'STEP_DOWN', 1, [5, 4, 3, 2, 1]); // $50,000

// Yield Maintenance
const ymPenalty = calculatePrepayPenalty(
  1000000,
  'YIELD_MAINTENANCE',
  1,
  undefined,
  { noteRate: 0.05, treasuryRate: 0.03, remainingMonths: 36 }
);

// Full Amortization Schedule
const schedule = generateAmortizationSchedule(500000, 0.06, 360);
console.log(schedule[0]); // { month: 1, payment: 2997.75, principal: 497.75, interest: 2500, ... }

// Comprehensive Loan Analysis
const analysis = analyzeLoan({
  principal: 10000000,
  annualRate: 0.065,
  amortizationYears: 25,
  ioPeriodYears: 3,
  termYears: 10,
  annualNOI: 1200000,
  propertyValue: 15000000,
  upfrontFees: 150000,
  prepayStructure: 'STEP_DOWN',
  prepaySchedule: [5, 4, 3, 2, 1, 0],
});

1031 Exchange (@uedfx/financial-calculators/1031-exchange)

import {
  calculate1031Deadlines,
  calculate1031Boot,
  calculate1031DeferredGain,
  validate3PropertyRule,
  validate200PercentRule,
  calculate95PercentRule,
  analyze1031Exchange
} from '@uedfx/financial-calculators/1031-exchange';

// Calculate 45/180 day deadlines
const deadlines = calculate1031Deadlines(new Date('2024-06-15'));
console.log(deadlines.identificationDeadline); // 2024-07-30
console.log(deadlines.exchangeDeadline); // 2024-12-12
console.log(deadlines.daysRemaining); // Days until identification deadline

// Calculate Boot (taxable portion)
const boot = calculate1031Boot({
  salePrice: 2000000,
  originalBasis: 1200000,
  sellingCosts: 100000,
  mortgageRelieved: 800000,
  replacementPrice: 2500000,
  replacementMortgage: 1000000,
});
console.log(boot.cashBoot);     // Cash received (taxable)
console.log(boot.mortgageBoot); // Mortgage boot (if any)
console.log(boot.totalBoot);    // Total taxable boot

// Validate identification rules
const properties = [
  { id: '1', value: 500000 },
  { id: '2', value: 600000 },
  { id: '3', value: 700000 },
];
validate3PropertyRule(properties); // true (max 3 properties)
validate200PercentRule(properties, 1000000); // true if total <= 200% of sale

// Full exchange analysis
const analysis = analyze1031Exchange({
  salePrice: 2000000,
  originalBasis: 1200000,
  accumulatedDepreciation: 300000,
  sellingCosts: 100000,
  mortgageRelieved: 800000,
  capitalGainsTaxRate: 0.20,
  depreciationRecaptureTaxRate: 0.25,
  stateTaxRate: 0.05,
  replacementProperties: [
    { id: '1', value: 2500000, mortgage: 1000000 }
  ],
});
console.log(analysis.deferredGain);
console.log(analysis.potentialTaxSaved);

Portfolio Performance (@uedfx/financial-calculators/performance)

import {
  calculateModifiedDietzTWR,
  calculateTrueTWR,
  calculateTWR,
  calculateSharpeRatio,
  calculateSortinoRatio,
  calculateCalmarRatio,
  calculateVolatility,
  calculateMaxDrawdown,
  calculateRiskMetrics,
  type PerformancePoint
} from '@uedfx/financial-calculators/performance';

// Time-Weighted Return with Cash Flows (Modified Dietz)
const twr = calculateModifiedDietzTWR(
  1000000,   // Starting value
  1150000,   // Ending value
  [{ date: '2024-02-15', amount: 50000 }], // Cash flows
  new Date('2024-01-01'),
  new Date('2024-03-31')
);

// True TWR (chains sub-period returns)
const timeSeries: PerformancePoint[] = [
  { date: '2024-01-01', value: 1000000 },
  { date: '2024-06-30', value: 1050000, cashFlow: 100000 }, // 5% return, then $100k contribution
  { date: '2024-12-31', value: 1207500 }, // 5% return on new base
];
const trueTwr = calculateTrueTWR(timeSeries); // 10.25% (1.05 x 1.05 - 1)

// Full TWR with annualization
const result = calculateTWR(timeSeries, new Date('2024-01-01'), new Date('2024-12-31'));
console.log(result.twr);          // 0.1025
console.log(result.annualizedTwr); // Annualized over period
console.log(result.method);        // 'TRUE_TWR'

// Risk Metrics
const returns = [0.02, -0.01, 0.015, -0.005, 0.01, -0.02, 0.025];
const volatility = calculateVolatility(returns, 252); // Annualized

const sharpe = calculateSharpeRatio(0.12, 0.15, 0.04); // (return - rf) / vol
const sortino = calculateSortinoRatio(0.12, 0.08, 0.04); // Uses downside deviation
const calmar = calculateCalmarRatio(0.15, 0.20); // Return / Max Drawdown

// Maximum Drawdown Analysis
const drawdown = calculateMaxDrawdown(timeSeries);
console.log(drawdown.maxDrawdown);     // Peak-to-trough decline
console.log(drawdown.maxDrawdownDate); // When trough occurred
console.log(drawdown.recoveryDate);    // When recovered (or null)
console.log(drawdown.daysToTrough);    // Duration to bottom
console.log(drawdown.daysToRecover);   // Duration to recovery

// Comprehensive Risk Metrics
const riskMetrics = calculateRiskMetrics(timeSeries, 0.04);
console.log(riskMetrics.volatility);
console.log(riskMetrics.sharpeRatio);
console.log(riskMetrics.sortinoRatio);
console.log(riskMetrics.calmarRatio);
console.log(riskMetrics.maxDrawdown);

SAFE & Convertibles (@uedfx/financial-calculators/safe)

import {
  calculateSAFEConversion,
  calculateSAFEOwnership,
  compareSAFEScenarios,
  type SAFEInstrument
} from '@uedfx/financial-calculators/safe';

const instruments: SAFEInstrument[] = [
  {
    id: 'safe-1',
    name: 'YC SAFE',
    type: 'safe_post',
    principal: 500000,
    valuationCap: 10000000,
  },
  {
    id: 'safe-2',
    name: 'Angel SAFE',
    type: 'safe_post',
    principal: 250000,
    valuationCap: 8000000,
    discount: 0.20,
  },
  {
    id: 'note-1',
    name: 'Convertible Note',
    type: 'convertible_note',
    principal: 100000,
    valuationCap: 12000000,
    discount: 0.15,
    interestRate: 0.06,
    termMonths: 18,
  }
];

const result = calculateSAFEConversion({
  instruments,
  preMoneyValuation: 15000000,
  newInvestmentAmount: 3000000,
  foundersShares: 10000000,
  optionPoolPercent: 0.10,
  optionPoolOnPreMoney: true,
});

console.log(result.pricePerShare);
console.log(result.postMoneyValuation);
console.log(result.founderDilution); // 0.45 (45%)
console.log(result.capTable);
console.log(result.conversionDetails);
console.log(result.warnings);

Instrument Types:

  • safe_post - Post-money SAFE (YC standard)
  • safe_pre - Pre-money SAFE
  • convertible_note - Convertible note with interest

LBO Modeling (@uedfx/financial-calculators/lbo)

import {
  calculateLBO,
  runSensitivity,
  type LBOInputs
} from '@uedfx/financial-calculators/lbo';

const inputs: LBOInputs = {
  enterpriseValue: 100000000,
  entryEbitda: 12500000,
  holdPeriodYears: 5,
  operatingAssumptions: {
    revenueGrowthRates: [0.10, 0.08, 0.06, 0.05, 0.04],
    ebitdaMargins: [0.20, 0.21, 0.22, 0.23, 0.24],
    capexPercentRevenue: 0.02,
    nwcPercentRevenue: 0.10,
    taxRate: 0.25,
  },
  exitMultiple: 9.0,
  capitalStructure: {
    seniorDebt: { name: 'Term Loan', amount: 60000000, interestRate: 0.07, amortizationYears: 7 },
    equityContribution: 40000000,
  },
};

const result = calculateLBO(inputs);

console.log(result.returns.irr);            // 0.25 (25% IRR)
console.log(result.returns.moic);           // 2.8x MOIC
console.log(result.exitMetrics);            // Exit metrics
console.log(result.yearlyProjections);      // Year-by-year financials
console.log(result.debtSchedules);          // Debt paydown schedules

Business Valuation (@uedfx/financial-calculators/valuation)

import {
  calculateDCF,
  analyzeComparables,
  calculateRuleOf40,
  calculateSaaSValuation,
  calculateVentureValuation,
  calculateWACC,
  type DCFInputs
} from '@uedfx/financial-calculators/valuation';

// DCF Valuation
const dcfResult = calculateDCF({
  projectedCashFlows: [1000000, 1100000, 1210000, 1331000, 1464100],
  discountRate: 0.12,
  terminalGrowthRate: 0.03,
  netDebt: 2000000,
});

console.log(dcfResult.enterpriseValue);
console.log(dcfResult.equityValue);
console.log(dcfResult.pvTerminalValue);
console.log(dcfResult.impliedTerminalMultiple);

// Comparable Company Analysis
const compResult = analyzeComparables(
  [
    { name: 'Comp A', value: 500000000, ebitda: 50000000, revenue: 200000000 },
    { name: 'Comp B', value: 400000000, ebitda: 40000000, revenue: 180000000 },
    { name: 'Comp C', value: 600000000, ebitda: 55000000, revenue: 250000000 },
  ],
  { ebitda: 45000000, revenue: 190000000 }
);

console.log(compResult.medianEVEBITDA);
console.log(compResult.impliedValuations);

// SaaS Valuation
const saasResult = calculateSaaSValuation(
  5000000,  // ARR
  0.80,     // 80% growth
  1.20,     // 120% NRR
  0.75      // 75% gross margin
);

console.log(saasResult.adjustedMultiple);
console.log(saasResult.valuation);
console.log(saasResult.factors);

// Rule of 40
const rule40 = calculateRuleOf40({ revenueGrowth: 0.50, profitMargin: -0.05 });
console.log(rule40.score);     // 45
console.log(rule40.passing);   // true
console.log(rule40.assessment);

// Venture Valuation
const ventureResult = calculateVentureValuation(0.20, 2000000);
console.log(ventureResult.postMoneyValuation); // $10M
console.log(ventureResult.preMoneyValuation);  // $8M

// WACC
const wacc = calculateWACC(
  80000000,  // Equity value
  20000000,  // Debt value
  0.12,      // Cost of equity
  0.06,      // Cost of debt
  0.25       // Tax rate
);

Utility Functions

import { formatCurrency, formatPercent, formatMultiple } from '@uedfx/financial-calculators';

formatCurrency(1500000);    // "$1.50M"
formatCurrency(2500000000); // "$2.50B"
formatPercent(0.2354);      // "23.54%"
formatMultiple(2.8);        // "2.80x"

Interactive Calculators

Try these calculators with a visual interface at uedfx.com/tools:

About DFX

This package is extracted from DFX - The Private Capital Operating System. DFX helps investors, founders, and dealmakers discover opportunities, manage portfolios, and close deals faster.

Features:

  • Deal discovery and investor matching
  • AI-powered due diligence
  • Cap table management
  • Fundraising pipeline tracking
  • Real estate portfolio analytics

Mathematical Methodology

This package implements industry-standard financial formulas with high numerical precision. All calculations are verified against CFA exam reference materials, Excel/Bloomberg outputs, and GIPS standards.

IRR (Internal Rate of Return)

Formula: Find r such that NPV = 0

NPV = Σ(CF_t / (1+r)^t) = 0  for t = 0 to n

Implementation: Newton-Raphson iterative method with:

  • Maximum 100 iterations (configurable)
  • Convergence tolerance: 1e-10
  • Automatic fallback to bisection for non-convergent cases
  • Multiple starting guesses for robust convergence

Mathematical Verification:

const irr = calculateIRR(cashFlows);
const npv = calculateNPV(cashFlows, irr);
// npv is guaranteed to be < $1 (machine precision)

Time-Weighted Return (TWR)

Modified Dietz Formula:

TWR = (End Value - Start Value - Cash Flows) / (Start Value + Weighted Cash Flows)

Where weight = (Total Days - Days Since Cash Flow) / Total Days

True TWR (Chained Returns):

TWR = (1 + R₁) × (1 + R₂) × ... × (1 + Rₙ) - 1

GIPS-compliant methodology that splits at each cash flow for accurate performance measurement.

Risk Metrics

  • Sharpe Ratio: (Return - Risk-Free Rate) / Volatility
  • Sortino Ratio: (Return - Risk-Free Rate) / Downside Deviation
  • Calmar Ratio: Annualized Return / Maximum Drawdown
  • Volatility: σ_annual = σ_periodic × √(periods per year)

Numerical Precision

All calculations are performed with JavaScript's IEEE 754 double precision (15-17 significant digits). For financial applications:

| Metric | Precision | |--------|-----------| | IRR | ±0.01% (1 basis point) | | NPV | ±$1 (machine precision at IRR) | | Cap Rate | ±0.01% | | MOIC | ±0.001x | | TWR | ±0.0001% |

Test Coverage

This package maintains near-100% test coverage with:

  • 521 test cases covering all functions
  • CFA exam-style problems verified against textbook solutions
  • Excel/Bloomberg verification for loan and performance calculations
  • GIPS compliance for portfolio performance metrics
  • Edge cases: Negative returns, near-zero IRR, billion-dollar deals, floating-point precision
  • Mathematical proofs: NPV at computed IRR equals zero within tolerance

Contributing

Contributions are welcome! Please read our Contributing Guide for details.

License

MIT License - see LICENSE for details.


Built with precision by the DFX team.