### Build TypeScript and Run HMM Tests (Quick Start) Source: https://github.com/railpath/finance-toolkit/blob/main/testing/battle-testing/SETUP.md Quick start commands to build the TypeScript project and run the HMM battle tests from the project root. Assumes dependencies are already installed. ```bash # From project root npm run build # Run HMM battle tests cd testing/battle-testing python3 hmm_battle_tester.py ``` -------------------------------- ### Install Python Dependencies with Virtual Environment Source: https://github.com/railpath/finance-toolkit/blob/main/testing/battle-testing/SETUP.md Sets up a Python virtual environment, activates it, and then installs NumPy, SciPy, and Pandas. This isolates dependencies for the project. ```bash cd testing/battle-testing python3 -m venv venv source venv/bin/activate pip install numpy scipy pandas ``` -------------------------------- ### HMM Battle Test Output Example Source: https://github.com/railpath/finance-toolkit/blob/main/testing/battle-testing/SETUP.md An example of the expected output from the HMM battle tests, showing individual test case results and an overall summary. It indicates passed and failed tests. ```text ================================================================================ HMM BATTLE TESTING - TypeScript vs Python (scipy/numpy) ================================================================================ 📊 Testing logSumExp -------------------------------------------------------------------------------- ⚙️ basic_log_sum_exp: Basic log-sum-exp calculation ✅ PASSED ⚙️ large_negative_values: Numerically challenging large negative values ✅ PASSED ⚙️ empty_array: Edge case: empty array ✅ PASSED 📊 Testing normalizeRows -------------------------------------------------------------------------------- ⚙️ basic_normalization: Normalize 2x3 matrix rows ✅ PASSED ⚙️ zero_row: Handle zero row with uniform distribution ✅ PASSED 📊 Testing gaussianPDF -------------------------------------------------------------------------------- ⚙️ standard_normal_at_zero: Standard normal PDF at x=0 ✅ PASSED ⚙️ shifted_gaussian: Gaussian with mean=1, var=0.5 at x=1 ✅ PASSED 📊 Testing forwardAlgorithm -------------------------------------------------------------------------------- ⚙️ simple_2_state_hmm: Forward algorithm with 2 states, 3 observations ✅ PASSED 📊 Testing viterbiAlgorithm -------------------------------------------------------------------------------- ⚙️ simple_2_state_hmm: Viterbi algorithm finds most likely path ✅ PASSED ================================================================================ SUMMARY ================================================================================ Total Tests: 13 ✅ Passed: 13 (100.0%) ❌ Failed: 0 (0.0%) ``` -------------------------------- ### Install Python Dependencies with Homebrew Source: https://github.com/railpath/finance-toolkit/blob/main/testing/battle-testing/SETUP.md Installs NumPy and SciPy using the Homebrew package manager. This is a recommended approach for managing Python dependencies on macOS. ```bash brew install numpy scipy ``` -------------------------------- ### Run Standard Finance Function Tests Source: https://github.com/railpath/finance-toolkit/blob/main/testing/battle-testing/SETUP.md Executes the battle tests for standard finance functions using the `battle_tester.py` script. Ensure you are in the correct directory. ```bash cd testing/battle-testing python3 battle_tester.py ``` -------------------------------- ### Recreate Virtual Environment Source: https://github.com/railpath/finance-toolkit/blob/main/testing/battle-testing/SETUP.md Steps to remove and recreate a Python virtual environment, then reinstall dependencies. This is useful for resolving environment-specific issues. ```bash # Remove and recreate venv rm -rf venv python3 -m venv venv source venv/bin/activate pip install --upgrade pip pip install numpy scipy pandas ``` -------------------------------- ### Check Python Dependencies Installation Source: https://github.com/railpath/finance-toolkit/blob/main/testing/battle-testing/SETUP.md Verifies if NumPy, SciPy, and Pandas are installed and accessible in the current Python environment. It prints a success message if all are found. ```python python3 -c "import numpy, scipy, pandas; print('✅ All dependencies available')" ``` -------------------------------- ### Troubleshoot SSL Certificate Issues (macOS) Source: https://github.com/railpath/finance-toolkit/blob/main/testing/battle-testing/SETUP.md Command to install SSL certificates on macOS, which can resolve issues encountered during pip installs. This command may require adjusting the Python version in the path. ```bash # Install certificates (macOS) /Applications/Python\ 3.*/Install\ Certificates.command ``` -------------------------------- ### Install Python Dependencies with Pip (Break System Packages) Source: https://github.com/railpath/finance-toolkit/blob/main/testing/battle-testing/SETUP.md Installs NumPy, SciPy, and Pandas using pip, bypassing system package restrictions. Use this option with caution as it can affect system Python packages. ```bash pip3 install --break-system-packages numpy scipy pandas ``` -------------------------------- ### Run HMM Battle Tests Source: https://github.com/railpath/finance-toolkit/blob/main/testing/battle-testing/SETUP.md Builds the TypeScript project, then runs the HMM battle tests using `hmm_battle_tester.py`. This script compares TypeScript HMM implementations against Python's SciPy/NumPy. ```bash cd testing/battle-testing # First, ensure TypeScript is built cd ../.. npm run build cd testing/battle-testing # Run HMM battle tests python3 hmm_battle_tester.py ``` -------------------------------- ### Troubleshoot SSL Certificate Issues (Homebrew) Source: https://github.com/railpath/finance-toolkit/blob/main/testing/battle-testing/SETUP.md Alternative method to resolve SSL certificate issues by installing SciPy via Homebrew, bypassing pip's certificate handling. ```bash # Or use Homebrew (bypasses pip) brew install scipy ``` -------------------------------- ### Install Dependencies and Run Battle Tests (Bash) Source: https://github.com/railpath/finance-toolkit/blob/main/testing/battle-testing/README.md This snippet outlines the steps to set up and execute the battle testing framework. It includes installing Python dependencies, building the TypeScript project, and running the main test script. ```bash # Install dependencies pip install -r requirements.txt # Build TypeScript project cd .. && npm run build && cd testing # Run comprehensive battle tests python battle_tester.py ``` -------------------------------- ### Install @railpath/finance-toolkit using npm Source: https://github.com/railpath/finance-toolkit/blob/main/README.md This command installs the finance-toolkit library from the npm registry. It is a prerequisite for using any of the library's functionalities in your project. ```bash npm install @railpath/finance-toolkit ``` -------------------------------- ### Troubleshoot Module Not Found Errors Source: https://github.com/railpath/finance-toolkit/blob/main/testing/battle-testing/SETUP.md Commands to help diagnose 'Module Not Found' errors in Python. It includes checking installed packages and inspecting the Python path. ```bash # Check what's installed pip3 list | grep -E "numpy|scipy|pandas" # Check Python path python3 -c "import sys; print('\n'.join(sys.path))" ``` -------------------------------- ### State Mapping Examples Source: https://github.com/railpath/finance-toolkit/blob/main/docs/REGIME_DETECTION.md Illustrates how states are mapped to labels based on their mean return. Shows examples for 2, 3, and 4 states, demonstrating the naming conventions for different market conditions. ```typescript ['bearish', 'bullish'] ``` ```typescript ['bearish', 'neutral', 'bullish'] ``` ```typescript ['strong_bearish', 'weak_bearish', 'weak_bullish', 'strong_bullish'] ``` -------------------------------- ### Prerequisites for Running HMM Battle Tests Source: https://github.com/railpath/finance-toolkit/blob/main/testing/battle-testing/HMM_BATTLE_TESTING.md Shell commands to set up the environment for running HMM battle tests. This includes installing Python dependencies and building the TypeScript project. ```bash # Install Python dependencies pip install -r requirements.txt # Build TypeScript project cd ../.. && npm run build && cd testing/battle-testing ``` -------------------------------- ### Example HMM Battle Test Output Source: https://github.com/railpath/finance-toolkit/blob/main/testing/battle-testing/HMM_BATTLE_TESTING.md An example of the expected output from the HMM battle testing script. It shows the test execution progress, individual test case results (PASSED/FAILED), and a final summary. ```text ================================================================================ HMM BATTLE TESTING - TypeScript vs Python (scipy/numpy) ================================================================================ 📊 Testing logSumExp -------------------------------------------------------------------------------- ⚙️ basic_log_sum_exp: Basic log-sum-exp calculation ✅ PASSED ⚙️ large_negative_values: Numerically challenging large negative values ✅ PASSED 📊 Testing gaussianPDF -------------------------------------------------------------------------------- ⚙️ standard_normal_at_zero: Standard normal PDF at x=0 ✅ PASSED ... (further test cases) ================================================================================ SUMMARY ================================================================================ Total Tests: 15 ✅ Passed: 15 (100.0%) ❌ Failed: 0 (0.0%) ``` -------------------------------- ### Detect Regime with Simple Prices (TypeScript) Source: https://github.com/railpath/finance-toolkit/blob/main/docs/REGIME_DETECTION.md This example demonstrates the basic usage of the `detectRegime` function with an array of prices to identify market regimes. It returns the current regime, confidence level, and a sequence of detected regimes over time. No external libraries are required beyond the finance-toolkit. ```typescript import { detectRegime } from '@railpath/finance-toolkit'; const prices = [100, 102, 105, 103, 107, 110, 108, 112, 115, ...]; const result = detectRegime(prices); console.log(result.currentRegime); // 'bullish' console.log(result.confidence); // 0.85 console.log(result.regimes); // ['neutral', 'neutral', 'bullish', 'bullish', ...] ``` -------------------------------- ### Configure Regime Detection Options (TypeScript) Source: https://github.com/railpath/finance-toolkit/blob/main/docs/REGIME_DETECTION.md This example shows how to customize the regime detection process using advanced configuration options. You can specify the number of states, desired features (e.g., RSI, MACD), feature window size, training iterations, convergence tolerance, and custom state labels. ```typescript const result = detectRegime(prices, { numStates: 4, features: ['returns', 'volatility', 'rsi'], featureWindow: 20, maxIterations: 100, convergenceTolerance: 1e-6, stateLabels: ['strong_bearish', 'weak_bearish', 'weak_bullish', 'strong_bullish'] }); ``` -------------------------------- ### Importing @railpath/finance-toolkit in ESM and CommonJS Source: https://github.com/railpath/finance-toolkit/blob/main/README.md Demonstrates how to import functionalities from the @railpath/finance-toolkit library using both modern ECMAScript Modules (ESM) syntax and CommonJS syntax. This ensures compatibility with various JavaScript project setups. ```typescript // Modern ESM syntax - works! import { calculateSharpeRatio } from '@railpath/finance-toolkit'; // CommonJS - works! const { calculateSharpeRatio } = require('@railpath/finance-toolkit'); ``` -------------------------------- ### HMM Algorithms: Forward, Backward, Viterbi, Baum-Welch (TypeScript) Source: https://github.com/railpath/finance-toolkit/blob/main/docs/REGIME_DETECTION.md This example demonstrates the core algorithms of the HMM implementation, including Forward-Backward for calculating state probabilities, Viterbi for finding the most likely state sequence, and Baum-Welch for Expectation-Maximization training. These functions require pre-defined HMM parameters and observations. ```typescript import { forward, backward, viterbi, baumWelch, initializeHMM } from '@railpath/finance-toolkit'; // Forward-Backward for probabilities const forwardResult = forward(observations, transitionMatrix, emissionParams, initialProbs); const backwardResult = backward(observations, transitionMatrix, emissionParams, forwardResult.scalingFactors); // Viterbi for most likely path const viterbiResult = viterbi(observations, transitionMatrix, emissionParams, initialProbs); // Baum-Welch for EM training const model = baumWelch(observations, numStates, { maxIterations: 100, convergenceTolerance: 1e-6 }); ``` -------------------------------- ### ML Utilities: Matrix and Statistical Functions (TypeScript) Source: https://github.com/railpath/finance-toolkit/blob/main/docs/REGIME_DETECTION.md This example showcases various machine learning utilities provided by the finance toolkit, including matrix operations (logSumExp, normalizeRows) and statistical functions (gaussianPDF, calculateMean, standardize). These are helpful for custom HMM implementations or advanced data processing. ```typescript import { // Matrix Operations logSumExp, normalizeRows, normalizeArray, // Statistical Functions gaussianPDF, logGaussianPDF, multivariateGaussianPDF, calculateMean, calculateVariance, standardize, // Validation validatePriceArray, validateFeatureMatrix, validateHMMParameters } from '@railpath/finance-toolkit'; ``` -------------------------------- ### Provide Custom Feature Matrix for Regime Detection (TypeScript) Source: https://github.com/railpath/finance-toolkit/blob/main/docs/REGIME_DETECTION.md This example demonstrates how to supply a pre-calculated custom feature matrix to the `detectRegime` function. This is useful when you have already computed specific financial indicators or want to use a unique set of features for regime detection. ```typescript // Pass your own feature matrix const customFeatures = [ [0.01, 0.15, 45], // [return, volatility, rsi] for t=0 [0.02, 0.14, 52], // for t=1 [-0.01, 0.18, 38], // for t=2 // ... ]; const result = detectRegime(prices, { features: customFeatures, numStates: 3 }); ``` -------------------------------- ### Train HMM Model with Extracted Features (TypeScript) Source: https://github.com/railpath/finance-toolkit/blob/main/docs/REGIME_DETECTION.md This example illustrates how to use the low-level API to first extract features from price data using `extractFeatures` and then train a Hidden Markov Model (HMM) using the `trainHMM` function. This provides more control over the feature engineering and model training process. ```typescript import { trainHMM, extractFeatures } from '@railpath/finance-toolkit'; // Extract features const features = extractFeatures(prices, { features: 'default', window: 20 }); // Train model const model = trainHMM(features, { numStates: 3, maxIterations: 100, convergenceTolerance: 1e-6 }); ``` -------------------------------- ### TypeScript Finance Toolkit Functions with Zod Validation Source: https://github.com/railpath/finance-toolkit/blob/main/README.md Demonstrates the usage of various finance-toolkit functions in TypeScript, highlighting type-safe inputs and outputs using Zod validation. Includes examples for portfolio performance calculations like Time Weighted Return and technical indicators such as Simple Moving Average (SMA) and Moving Average Convergence Divergence (MACD). ```typescript import type { TimeWeightedReturnOptions, TimeWeightedReturnResult, SMAOptions, SMAResult, RSIOptions, RSIResult, MACDOptions, MACDResult } from '@railpath/finance-toolkit'; // Type-safe Options for Time Weighted Return const options: TimeWeightedReturnOptions = { portfolioValues: [1000, 1100, 1200], cashFlows: [0, 100, 0], annualizationFactor: 252 }; // Type-safe Results for Time Weighted Return // Assuming calculateTimeWeightedReturn is imported and available // 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 }; // Assuming calculateSMA is imported and available // 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 }; // Assuming calculateMACD is imported and available // const macdResult: MACDResult = calculateMACD(macdOptions); // console.log(macdResult.macdLine); // number[] // console.log(macdResult.signalLine); // number[] // console.log(macdResult.histogram); // number[] ``` -------------------------------- ### Build Project with npm Source: https://github.com/railpath/finance-toolkit/blob/main/README.md Commands for building the project. Includes options for production builds and development with watch mode enabled. The output consists of TypeScript declarations and optimized JavaScript modules. ```bash # Build for production npm run build # Development with watch mode npm run dev ``` -------------------------------- ### Run npm Test Commands Source: https://github.com/railpath/finance-toolkit/blob/main/README.md Provides common npm commands for executing various types of tests within the project, including watch mode, coverage, integration, and performance benchmarks. These commands facilitate the testing and quality assurance process. ```bash # Run all tests npm test # Run tests in watch mode npm run test:watch # Run tests with coverage npm run test:coverage # Run integration tests npm run test:integration # Run integration tests in watch mode npm run test:integration:watch # Run performance benchmarks npm run test:performance # Run performance benchmarks in watch mode npm run test:performance:watch ``` -------------------------------- ### RSI Array Length Example Source: https://github.com/railpath/finance-toolkit/blob/main/docs/TECHNICAL_INDICATORS.md Illustrates the output array length for the Relative Strength Index (RSI) calculation, which is shorter than the input price array by the specified period. This is due to the need for prior price changes. ```typescript // RSI: prices.length - period calculateRSI({ prices: [1,2,3,4,5,6], period: 3 }) // → rsi: [50, 60, 70] (3 values, needs price changes) ``` -------------------------------- ### Calculate VaR 99% Pre-configured Function Source: https://github.com/railpath/finance-toolkit/blob/main/docs/VAR_METHODS.md A convenience function to calculate Value at Risk (VaR) at a 99% confidence level. It accepts historical returns and allows specifying the calculation method, defaulting to 'parametric' in this example. ```typescript import { calculateVaR99 } from '@railpath/finance-toolkit'; const result = calculateVaR99({ returns: dailyReturns, method: 'parametric' }); ``` -------------------------------- ### SMA/EMA Array Length Example Source: https://github.com/railpath/finance-toolkit/blob/main/docs/TECHNICAL_INDICATORS.md Demonstrates the resulting array length for Simple Moving Average (SMA) and Exponential Moving Average (EMA) calculations, showing that the output array is shorter than the input price array by a factor related to the period. ```typescript // SMA/EMA: prices.length - period + 1 calculateSMA({ prices: [1,2,3,4,5], period: 3 }) // → sma: [2, 3, 4] (3 values) ``` -------------------------------- ### Simple Regime Detection with Defaults Source: https://github.com/railpath/finance-toolkit/blob/main/docs/REGIME_DETECTION.md Demonstrates the simplest usage of the `detectRegime` function from the finance-toolkit. It takes price data as input and returns the current market regime and its confidence level using default parameters. ```typescript import { detectRegime } from '@railpath/finance-toolkit'; // Price data (e.g., from an API) const prices = [/* ... */]; // Simplest usage with defaults const result = detectRegime(prices); // Output current market sentiment console.log(`Current Market Regime: ${result.currentRegime}`); console.log(`Confidence: ${(result.confidence * 100).toFixed(1)}%`); ``` -------------------------------- ### Extract Features from Price Data (TypeScript) Source: https://github.com/railpath/finance-toolkit/blob/main/docs/REGIME_DETECTION.md This example shows how to use the `extractFeatures` function to generate a feature matrix from raw price data. You can specify which features to include (e.g., returns, volatility, RSI, MACD) and the window size for calculating rolling indicators. ```typescript import { extractFeatures } from '@railpath/finance-toolkit'; const features = extractFeatures(prices, { features: ['returns', 'volatility', 'rsi', 'macd'], window: 20 }); // Returns: T x D matrix (standardized) ``` -------------------------------- ### Perform Portfolio Optimization using Markowitz Model Source: https://context7.com/railpath/finance-toolkit/llms.txt Implements Markowitz mean-variance portfolio optimization to find optimal asset weights. Supports minimum variance, maximum Sharpe ratio, and target return objectives. Requires expected returns and a covariance matrix. Optional parameters include risk-free rate, weight constraints, and target return. ```typescript import { calculatePortfolioOptimization } from '@railpath/finance-toolkit'; const expectedReturns = [0.08, 0.12, 0.06, 0.10]; const covarianceMatrix = [ [0.04, 0.02, 0.01, 0.015], [0.02, 0.09, 0.03, 0.025], [0.01, 0.03, 0.02, 0.015], [0.015, 0.025, 0.015, 0.05] ]; // Minimum Variance Portfolio const minVar = calculatePortfolioOptimization({ expectedReturns, covarianceMatrix }); console.log(minVar.weights); // Optimal weights for minimum risk console.log(minVar.expectedReturn); // Expected portfolio return console.log(minVar.volatility); // Portfolio volatility (std dev) console.log(minVar.converged); // true if optimization converged // Maximum Sharpe Ratio Portfolio const maxSharpe = calculatePortfolioOptimization({ expectedReturns, covarianceMatrix, riskFreeRate: 0.03, minWeight: 0.0, // No short selling maxWeight: 0.5, // Max 50% in any asset sumTo1: true // Weights sum to 1 }); console.log(maxSharpe.weights); // [0.2, 0.35, 0.15, 0.3] (example) console.log(maxSharpe.sharpeRatio); // Portfolio Sharpe ratio console.log(maxSharpe.method); // 'maximumSharpe' // Target Return Portfolio const targetReturn = calculatePortfolioOptimization({ expectedReturns, covarianceMatrix, targetReturn: 0.09, // Target 9% return minWeight: 0.0, maxWeight: 1.0, sumTo1: true }); console.log(targetReturn.weights); // Minimum variance for 9% return console.log(targetReturn.expectedReturn); // Should be ≈ 0.09 ``` -------------------------------- ### Pre-configured VaR Functions Source: https://github.com/railpath/finance-toolkit/blob/main/docs/VAR_METHODS.md Provides convenience functions for calculating VaR at common confidence levels (95% and 99%) with a specified method. ```APIDOC ## GET /railpath/finance-toolkit/var/preconfigured ### Description Provides pre-configured endpoints to calculate VaR at specific confidence levels (95% and 99%) using a chosen method (historical, parametric, or montecarlo). ### Method GET ### Endpoint /railpath/finance-toolkit/var/preconfigured ### Parameters #### Query Parameters - **returns** (number[]) - Required - An array of historical asset returns. - **confidenceLevel** (number) - Required - The desired confidence level. Accepts 0.95 or 0.99. - **method** (string) - Required - The VaR calculation method. Accepts 'historical', 'parametric', or 'montecarlo'. - **simulations** (number) - Optional - The number of simulations to perform for the 'montecarlo' method. Defaults to 10,000. ### Request Example `GET /railpath/finance-toolkit/var/preconfigured?confidenceLevel=0.95&method=historical&returns=[0.01,-0.005,0.02,...]` `GET /railpath/finance-toolkit/var/preconfigured?confidenceLevel=0.99&method=montecarlo&simulations=20000&returns=[0.01,-0.005,0.02,...]` ### Response #### Success Response (200) - **value** (number) - The calculated Value at Risk (VaR). - **confidenceLevel** (number) - The confidence level used. - **method** (string) - The method used for calculation. - **simulations** (number, optional) - The number of simulations if 'montecarlo' method was used. #### Response Example ```json { "value": 0.016, "confidenceLevel": 0.95, "method": "historical" } ``` ```json { "value": 0.022, "confidenceLevel": 0.99, "method": "montecarlo", "simulations": 20000 } ``` ``` -------------------------------- ### Comprehensive Portfolio Metrics Source: https://context7.com/railpath/finance-toolkit/llms.txt Calculates a wide array of portfolio metrics in a single function call, including CAGR, Sharpe Ratio, Sortino Ratio, VaR, Expected Shortfall, and more. ```APIDOC ## Portfolio Metrics (Comprehensive) ### Description Calculates comprehensive portfolio metrics including CAGR, Sharpe, Sortino, VaR, Expected Shortfall, and more in a single call. ### Method `calculatePortfolioMetrics` ### Parameters #### Request Body - **portfolioValues** (number[]) - Required - An array of historical portfolio values. - **riskFreeRate** (number) - Required - The annual risk-free rate of return. - **confidenceLevel** (number) - Required - The confidence level for VaR calculation (e.g., 0.95 for 95%). - **annualizationFactor** (number) - Required - The factor used for annualizing metrics (e.g., 252 for trading days). ### Request Example ```json { "portfolioValues": [10000, 11000, 10500, 12000, 11500, 13000, 12500, 14000], "riskFreeRate": 0.02, "confidenceLevel": 0.95, "annualizationFactor": 252 } ``` ### Response #### Success Response (200) - **cagr** (number) - Compound Annual Growth Rate. - **sharpeRatio** (number) - Risk-adjusted return (excess return per unit of volatility). - **sortinoRatio** (number) - Downside risk-adjusted return. - **calmarRatio** (number) - Return / Max Drawdown. - **maxDrawdown** (number) - Maximum drawdown. - **volatility** (number) - Annualized volatility. - **var95** (number) - Value at Risk at 95% confidence level. - **expectedShortfall** (number) - Expected Shortfall (Conditional Value at Risk). - **skewness** (number) - Measure of the asymmetry of the probability distribution. - **kurtosis** (number) - Measure of the "tailedness" of the probability distribution. - **totalReturn** (number) - Cumulative return over the period. #### Response Example ```json { "cagr": 0.15, "sharpeRatio": 1.2, "sortinoRatio": 1.8, "calmarRatio": 2.1, "maxDrawdown": 0.10, "volatility": 0.12, "var95": 0.05, "expectedShortfall": 0.07, "skewness": 0.5, "kurtosis": 2.5, "totalReturn": 1.4 } ``` ### Notes - Provides a complete portfolio health check in one function call. ``` -------------------------------- ### Multi-State Analysis with Custom Labels Source: https://github.com/railpath/finance-toolkit/blob/main/docs/REGIME_DETECTION.md Shows how to perform multi-state analysis by specifying the number of states and custom labels for each state. This allows for more granular identification of market regimes beyond the default 'bullish' and 'bearish'. ```typescript import { detectRegime } from '@railpath/finance-toolkit'; const result = detectRegime(prices, { numStates: 4, stateLabels: [ 'crash', // Very negative trend 'bearish', // Negative trend 'bullish', // Positive trend 'rally' // Very positive trend ] }); // Identify regime changes for (let i = 1; i < result.regimes.length; i++) { if (result.regimes[i] !== result.regimes[i-1]) { console.log(`Regime changed from ${result.regimes[i-1]} to ${result.regimes[i]} at index ${i}`); } } ``` -------------------------------- ### Running HMM Battle Tests Source: https://github.com/railpath/finance-toolkit/blob/main/testing/battle-testing/HMM_BATTLE_TESTING.md The command to execute the HMM battle testing script using Python. This initiates the comparison between TypeScript and Python implementations. ```bash python hmm_battle_tester.py ``` -------------------------------- ### Regime Detection with Technical Indicators Source: https://github.com/railpath/finance-toolkit/blob/main/docs/REGIME_DETECTION.md Illustrates using `detectRegime` with custom features, including technical indicators like RSI and MACD, and a specified feature window. It also shows how to access and log the trained model's transition matrix and emission parameters. ```typescript import { detectRegime } from '@railpath/finance-toolkit'; const result = detectRegime(prices, { numStates: 3, features: ['returns', 'volatility', 'rsi', 'macd'], featureWindow: 20 }); // Save model for analysis const model = result.model; console.log('Transition Matrix:', model.transitionMatrix); console.log('Emission Parameters:', model.emissionParams); ``` -------------------------------- ### Basic Portfolio Optimization (TypeScript) Source: https://github.com/railpath/finance-toolkit/blob/main/docs/PORTFOLIO_OPTIMIZATION.md Performs basic Mean-Variance Optimization with expected returns, covariance matrix, and an optional risk-free rate. It calculates optimal weights, expected return, volatility, and Sharpe ratio. ```typescript import { calculatePortfolioOptimization } from '@railpath/finance-toolkit'; const result = calculatePortfolioOptimization({ expectedReturns: [0.10, 0.12, 0.08, 0.15], covarianceMatrix: [ [0.04, 0.02, 0.01, 0.03], [0.02, 0.09, 0.02, 0.04], [0.01, 0.02, 0.01, 0.02], [0.03, 0.04, 0.02, 0.16] ], riskFreeRate: 0.03 }); console.log(result.weights); // [0.25, 0.30, 0.20, 0.25] console.log(result.expectedReturn); // 0.1125 console.log(result.sharpeRatio); // 1.85 ``` -------------------------------- ### Advanced Custom Pipeline: Feature Extraction, Training, and Viterbi Source: https://github.com/railpath/finance-toolkit/blob/main/docs/REGIME_DETECTION.md Details an advanced workflow using the finance-toolkit. It demonstrates a custom pipeline involving extracting features with specified indicators and window, training a Hidden Markov Model (HMM), and then applying the Viterbi algorithm to find the most likely sequence of states. ```typescript import { extractFeatures, trainHMM, viterbi } from '@railpath/finance-toolkit'; // Step 1: Extract features const features = extractFeatures(prices, { features: ['returns', 'volatility', 'rsi'], window: 20 }); // Step 2: Train model const model = trainHMM(features, { numStates: 3, maxIterations: 100 }); // Step 3: Find most likely state sequence const viterbiResult = viterbi( features, model.transitionMatrix, model.emissionParams, model.initialProbs ); console.log('State sequence:', viterbiResult.path); console.log('Log probability:', viterbiResult.logProbability); ``` -------------------------------- ### Advanced HMM Algorithms for Custom Regime Detection in TypeScript Source: https://context7.com/railpath/finance-toolkit/llms.txt Provides low-level Hidden Markov Model algorithms including feature extraction, model training (trainHMM, Baum-Welch), and inference (forward, backward, Viterbi). Essential for building custom regime detection models. Requires price data and configuration for features, states, and iterations. ```typescript import { trainHMM, extractFeatures, forward, backward, viterbi, baumWelch } from '@railpath/finance-toolkit'; const prices = [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]; // Extract features from price data const featureMatrix = extractFeatures(prices, { features: ['returns', 'volatility'], window: 5 }); console.log(featureMatrix); // 2D array: [observations x features] // Train HMM model const model = trainHMM(featureMatrix, { numStates: 3, maxIterations: 100, convergenceTolerance: 1e-4 }); console.log(model.transitionMatrix); // P(state_j | state_i) console.log(model.emissionParams); // Gaussian params for each state console.log(model.initialProbs); // Initial state probabilities // Forward algorithm (filtering) const forwardResult = forward( featureMatrix, model.transitionMatrix, model.emissionParams, model.initialProbs ); console.log(forwardResult.alpha); // Forward probabilities console.log(forwardResult.logLikelihood); // Model log-likelihood // Backward algorithm const backwardResult = backward( featureMatrix, model.transitionMatrix, model.emissionParams ); console.log(backwardResult.beta); // Backward probabilities // Viterbi algorithm (most likely state sequence) const viterbiResult = viterbi( featureMatrix, model.transitionMatrix, model.emissionParams, model.initialProbs ); console.log(viterbiResult.path); // Most likely state sequence console.log(viterbiResult.probability); // Path probability // Baum-Welch algorithm (EM training) const trainedModel = baumWelch( featureMatrix, model.transitionMatrix, model.emissionParams, model.initialProbs, { maxIterations: 50, tolerance: 1e-3 } ); console.log(trainedModel.converged); console.log(trainedModel.iterations); ``` -------------------------------- ### Calculate Alpha and Beta using CAPM Source: https://context7.com/railpath/finance-toolkit/llms.txt Calculates Alpha and Beta metrics using the Capital Asset Pricing Model (CAPM). Beta measures systematic risk relative to a benchmark, while Alpha measures excess return. Requires asset and benchmark returns, risk-free rate, and pre-calculated beta for Alpha. Outputs include beta, correlation, volatilities, alpha, and expected return. ```typescript import { calculateAlpha, calculateBeta } from '@railpath/finance-toolkit'; const assetReturns = [0.02, 0.03, -0.01, 0.04, -0.02, 0.03, 0.01, -0.005]; const benchmarkReturns = [0.015, 0.025, -0.005, 0.03, -0.015, 0.025, 0.01, 0.0]; // Calculate Beta (systematic risk) const betaResult = calculateBeta({ assetReturns, benchmarkReturns }); console.log(betaResult.beta); // 1.2 (example) console.log(betaResult.correlation); // Correlation coefficient console.log(betaResult.assetVolatility); // Asset volatility console.log(betaResult.benchmarkVolatility); // Benchmark volatility // Calculate Alpha (excess return) const alphaResult = calculateAlpha({ assetReturns, benchmarkReturns, riskFreeRate: 0.02, beta: betaResult.beta }); console.log(alphaResult.alpha); // Annualized alpha console.log(alphaResult.beta); // 1.2 console.log(alphaResult.expectedReturn); // CAPM expected return console.log(alphaResult.actualReturn); // Actual average return // Interpretation if (alphaResult.alpha > 0) { console.log('Positive alpha - outperforming CAPM expected return'); } ```