Production-ready finance library for portfolio construction, risk analytics, quantitative metrics, and ML-based regime detection
npm install @railpath/finance-toolkit
A comprehensive TypeScript library for portfolio management and risk analytics.
@railpath/finance-toolkit provides a complete collection of financial metrics with focus on modularity, type-safety, and performance.
Part of the RailPath open source ecosystem – building financial infrastructure that belongs to everyone.
---
---
Written in TypeScript, works seamlessly in JavaScript projects.
Type definitions included for IDE autocomplete.
``bash`
npm install @railpath/finance-toolkit
The library is published as CommonJS for maximum compatibility across all environments:
- ✅ Modern ESM Projects - import works seamlessly with CommonJS
- ✅ Jest & Testing - works out-of-the-box, no configuration needed
- ✅ TypeScript Projects - full type support included
- ✅ All Bundlers - Webpack, Vite, Rollup, esbuild all support CommonJS
- ✅ Node.js - works in any Node.js version
`typescript
// Modern ESM syntax - works!
import { calculateSharpeRatio } from '@railpath/finance-toolkit';
// CommonJS - works!
const { calculateSharpeRatio } = require('@railpath/finance-toolkit');
`
Why CommonJS? It's the most compatible format. Modern tools can import CommonJS packages, and tree-shaking works just fine for libraries that export pure functions like this one.
`typescript
import {
calculateTimeWeightedReturn,
calculateMoneyWeightedReturn
} from '@railpath/finance-toolkit';
// Time-Weighted Return (TWR)
const twr = calculateTimeWeightedReturn({
portfolioValues: [1000, 1100, 1200, 1150],
cashFlows: [0, 100, 0, -50],
annualizationFactor: 252
});
// Money-Weighted Return (MWR) - IRR
// Uses robust numerical methods (Damped Newton-Raphson with Bisection fallback)
const mwr = calculateMoneyWeightedReturn({
cashFlows: [1000, 100, -50],
dates: [new Date('2023-01-01'), new Date('2023-06-01'), new Date('2023-12-01')],
finalValue: 1150,
initialValue: 0,
maxIterations: 100,
tolerance: 1e-6
});
console.log(mwr.mwr); // Period return
console.log(mwr.annualizedMWR); // Annualized return
console.log(mwr.method); // 'newton-raphson' or 'bisection'
console.log(mwr.iterations); // Number of iterations
`
`typescript
import {
calculateVaR,
calculateSharpeRatio,
calculateMaxDrawdown
} from '@railpath/finance-toolkit';
// Value at Risk (95% Confidence)
const var95 = calculateVaR({
returns: [0.01, 0.02, -0.01, 0.03, -0.02],
confidenceLevel: 0.95,
method: 'historical'
});
// Sharpe Ratio
const sharpe = calculateSharpeRatio({
returns: [0.01, 0.02, -0.01, 0.03],
riskFreeRate: 0.02,
annualizationFactor: 252
});
// Maximum Drawdown
const maxDD = calculateMaxDrawdown({
portfolioValues: [1000, 1100, 1050, 1200, 1150]
});
`
`typescript
import {
calculateCorrelationMatrix,
calculatePortfolioVolatility
} from '@railpath/finance-toolkit';
// Asset Correlation Matrix
const correlation = calculateCorrelationMatrix({
assetReturns: [
[0.01, 0.02, -0.01], // Asset 1
[0.015, 0.025, -0.005] // Asset 2
]
});
// Portfolio Volatility
const portfolioVol = calculatePortfolioVolatility({
weights: [0.6, 0.4],
covarianceMatrix: [[0.04, 0.02], [0.02, 0.09]]
});
`
`typescript
import {
calculateSMA,
calculateEMA,
calculateMACD,
calculateRSI,
calculateStochastic,
calculateWilliamsR,
calculateBollingerBands,
calculateATR
} from '@railpath/finance-toolkit';
// Simple Moving Average (SMA)
const sma = calculateSMA({
prices: [100, 102, 101, 103, 105, 104, 106],
period: 5
});
// Exponential Moving Average (EMA)
const ema = calculateEMA({
prices: [100, 102, 101, 103, 105, 104, 106],
period: 5
});
// MACD (Moving Average Convergence Divergence)
const macd = calculateMACD({
prices: [100, 102, 101, 103, 105, 104, 106, 107, 108, 109, 110, 111, 112, 113, 114],
fastPeriod: 12,
slowPeriod: 26,
signalPeriod: 9
});
// Relative Strength Index (RSI)
const rsi = calculateRSI({
prices: [100, 102, 101, 103, 105, 104, 106],
period: 14
});
// Stochastic Oscillator
const stochastic = calculateStochastic({
high: [102, 103, 101, 104, 105, 106, 107],
low: [98, 99, 97, 100, 101, 102, 103],
close: [100, 102, 100, 103, 104, 105, 106],
kPeriod: 14,
dPeriod: 3
});
// Williams %R
const williamsR = calculateWilliamsR({
high: [102, 103, 101, 104, 105, 106, 107],
low: [98, 99, 97, 100, 101, 102, 103],
close: [100, 102, 100, 103, 104, 105, 106],
period: 14
});
// Bollinger Bands
const bollinger = calculateBollingerBands({
prices: [100, 102, 101, 103, 105, 104, 106],
period: 20,
stdDevMultiplier: 2
});
`
`typescript
import { detectRegime } from '@railpath/finance-toolkit';
// Simple regime detection (3 states: bearish, neutral, bullish)
const result = detectRegime(prices);
console.log(result.currentRegime); // 'bullish'
console.log(result.confidence); // 0.85
console.log(result.regimes); // ['neutral', 'neutral', 'bullish', ...]
// Advanced with custom features
const advancedResult = detectRegime(prices, {
numStates: 4,
features: ['returns', 'volatility', 'rsi'],
featureWindow: 20,
stateLabels: ['strong_bearish', 'weak_bearish', 'weak_bullish', 'strong_bullish']
});
`
`typescript`
// Average True Range (ATR)
const atr = calculateATR({
high: [101, 103, 102, 104, 106, 105, 107],
low: [99, 101, 100, 102, 104, 103, 105],
close: [100, 102, 101, 103, 105, 104, 106],
period: 14
});
---
---
All functions are fully typed with Zod validation and modular schema architecture:
`typescript
import type {
TimeWeightedReturnOptions,
TimeWeightedReturnResult,
SMAOptions,
SMAResult,
RSIOptions,
RSIResult
} from '@railpath/finance-toolkit';
// Type-safe Options
const options: TimeWeightedReturnOptions = {
portfolioValues: [1000, 1100, 1200],
cashFlows: [0, 100, 0],
annualizationFactor: 252
};
// Type-safe Results
const result: TimeWeightedReturnResult = calculateTimeWeightedReturn(options);
console.log(result.twr); // number
console.log(result.annualizedTWR); // number
console.log(result.periodReturns); // number[]
// Technical Indicators with separate Options/Result types
const smaOptions: SMAOptions = {
prices: [100, 102, 101, 103, 105],
period: 3
};
const smaResult: SMAResult = calculateSMA(smaOptions);
console.log(smaResult.sma); // number[]
console.log(smaResult.count); // number
console.log(smaResult.indices); // number[]
// MACD with multiple periods
const macdOptions: MACDOptions = {
prices: [100, 102, 101, 103, 105, 104, 106],
fastPeriod: 12,
slowPeriod: 26,
signalPeriod: 9
};
const macdResult: MACDResult = calculateMACD(macdOptions);
console.log(macdResult.macdLine); // number[]
console.log(macdResult.signalLine); // number[]
console.log(macdResult.histogram); // number[]
`
---
For detailed implementation specifications, see:
- Portfolio Optimization - Constraints, solver details, mathematical formulation
- VaR Methods - Distribution assumptions, time horizons, simulation parameters
- Technical Indicators - Calculation methods, smoothing techniques, standards
- IRR Calculation - Numerical methods, convergence strategies, edge case handling
---
| Function | Description | Input | Output |
|----------|-------------|-------|--------|
| calculateTimeWeightedReturn | TWR Performance | Portfolio Values, Cash Flows | TWR, Annualized TWR, Period Returns |
| calculateMoneyWeightedReturn | MWR Performance (IRR) | Cash Flows, Dates, Final Value | MWR, Annualized MWR, NPV, Iterations, Method |
| calculatePortfolioMetrics | Comprehensive Analysis | Portfolio Values, Risk-Free Rate | CAGR, Sharpe, Sortino, VaR, ES, Volatility |
| calculatePerformanceAttribution | Factor Analysis | Returns, Factor Returns | Factor Contributions, Active Return |
| calculatePortfolioOptimization | Mean-Variance Optimization | Expected Returns, Covariance Matrix | Optimal Weights, Risk-Return |
| calculatePortfolioRebalancing | Rebalancing Strategies | Current Weights, Target Weights | New Weights, Trade Amounts |
| calculateEqualWeightPortfolio | Equal Weight Allocation | Asset Count | Equal Weights, Portfolio Metrics |
| calculateReturns | Return Calculations | Prices, Dates | Various Return Types |
| calculateRiskMetrics | Portfolio Risk Analysis | Returns, Risk-Free Rate | Risk Metrics, VaR, ES |
| calculateInformationRatio | Active Return Analysis | Portfolio Returns, Benchmark Returns | Information Ratio, Active Return |
| calculateTrackingError | Benchmark Deviation | Portfolio Returns, Benchmark Returns | Tracking Error, Active Risk |
| Function | Description | Methods |
|----------|-------------|---------|
| calculateVaR | Value at Risk | Historical, Parametric, Monte Carlo |
| calculateVaR95 | VaR 95% Confidence | Historical, Parametric, Monte Carlo |
| calculateVaR99 | VaR 99% Confidence | Historical, Parametric, Monte Carlo |
| calculateHistoricalVaR | Historical VaR | Historical Method |
| calculateParametricVaR | Parametric VaR | Normal Distribution |
| calculateMonteCarloVaR | Monte Carlo VaR | Simulation Method |
| calculateHistoricalExpectedShortfall | Historical ES | Historical Method |
| calculateParametricExpectedShortfall | Parametric ES | Normal Distribution |
| calculateSharpeRatio | Risk-Adjusted Returns | Standard, Annualized |
| calculateSortinoRatio | Downside Risk-Adjusted | Standard, Annualized |
| calculateSemideviation | Downside Volatility | Zero/Mean Threshold |
| calculateCalmarRatio | Return vs. Drawdown | Calmar Ratio |
| calculateSkewness | Distribution Asymmetry | Third Moment |
| calculateKurtosis | Distribution Tailedness | Fourth Moment (Excess) |
| calculateAlpha | CAPM Alpha | Asset vs. Benchmark |
| calculateBeta | CAPM Beta | Asset vs. Benchmark |
| calculateMaxDrawdown | Maximum Loss | Peak-to-Trough Analysis |
| calculateStandardDeviation | Standard Deviation | Classical Measure |
| Function | Description | Input |
|----------|-------------|-------|
| calculateVolatility | Standard Deviation | Returns Array |
| calculateEWMAVolatility | Exponentially Weighted | Returns, Lambda |
| calculateParkinsonVolatility | High-Low Range | High, Low Prices |
| calculateGarmanKlassVolatility | OHLC-based | Open, High, Low, Close |
| calculateStandardDeviation | Classical Measure | Returns Array |
| Function | Description | Input |
|----------|-------------|-------|
| calculateCorrelationMatrix | Asset Correlations | Asset Returns Matrix |
| calculateCovarianceMatrix | Asset Covariances | Asset Returns Matrix |
| calculatePortfolioVolatility | Portfolio Risk | Weights, Covariance Matrix |
| Function | Description | Input | Output |
|----------|-------------|-------|--------|
| calculateSMA | Simple Moving Average | Prices Array, Period | SMA Values, Indices |
| calculateEMA | Exponential Moving Average | Prices Array, Period | EMA Values, Smoothing Factor |
| calculateMACD | Moving Average Convergence Divergence | Prices Array, Fast/Slow/Signal Periods | MACD Line, Signal Line, Histogram |
| calculateRSI | Relative Strength Index | Prices Array, Period | RSI Values (0-100), Gains/Losses |
| calculateStochastic | Stochastic Oscillator | High/Low/Close Arrays, K/D Periods | %K, %D, Highest High, Lowest Low |
| calculateWilliamsR | Williams %R | High/Low/Close Arrays, Period | Williams %R Values (-100 to 0) |
| calculateBollingerBands | Bollinger Bands | Prices Array, Period, StdDev Multiplier | Upper/Middle/Lower Bands, %B |
| calculateATR | Average True Range | High/Low/Close Arrays, Period | ATR Values, True Range |
| Function | Description | Input | Output |
|----------|-------------|-------|--------|
| detectRegime | HMM-based Market Regime Detection | Prices Array, Options | Current Regime, Regime Sequence, Probabilities, Model |
| trainHMM | Train Hidden Markov Model | Feature Matrix, Options | Trained HMM Model |
| extractFeatures | Extract Features from Prices | Prices Array, Feature Config | Standardized Feature Matrix |
Advanced HMM Algorithms: forward, backward, viterbi, baumWelch
📖 Full Regime Detection Documentation
---
`bashRun all tests
npm test
Test Coverage: 1300+ Tests across 65 test files
$3
This library uses a comprehensive battle testing approach to ensure accuracy by comparing TypeScript implementations against Python equivalents using battle-tested libraries (numpy, scipy, pandas).
$3
Comprehensive performance benchmarks test functions across different dataset sizes to ensure optimal performance and detect regressions. Performance tests measure execution time, memory usage, and throughput for various dataset sizes to identify bottlenecks and ensure scalability. See testing/README.md for details on the performance testing framework.
---
Build
`bash
Build for production
npm run buildDevelopment with watch mode
npm run dev
``Output: TypeScript declarations and optimized JavaScript modules
---
1. Fork the repository
2. Create a feature branch
3. Implement tests for new functions
4. Ensure all tests pass
5. Create a pull request
---
MIT License - see LICENSE for details.