UNPKG

quantitivecalc

Version:

A TypeScript library providing advanced quantitative finance functions for risk analysis, performance metrics, and technical indicators. (Currently in development)

54 lines (53 loc) 2.46 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.calculateVolatility = calculateVolatility; /** * Calculates rolling volatility (standard deviation) of returns over a specified window size. * * @param data - Array of data objects containing return values. * @param returnsColumn - The key in each data object representing the return value. * @param resultColumn - The key to store the calculated volatility in each data object. * @param windowSize - The number of periods to use for the rolling window (default is 20). * @param annualize - Whether to annualize the volatility (default is true, assumes 252 trading days per year). * @returns A new array of data objects with the calculated volatility added under `resultColumn`. * * @remarks * - If there are not enough data points to fill the window, the volatility is set to `null`. * - Only numeric and non-NaN return values are considered in the calculation. */ function calculateVolatility(data, returnsColumn, resultColumn, windowSize = 20, annualize = true) { if (!data || data.length === 0) { return []; } const result = data.map(row => ({ ...row })); for (let i = 0; i < result.length; i++) { if (i < windowSize - 1) { result[i][resultColumn] = null; } else { // Get returns for the window const windowReturns = []; for (let j = i - windowSize + 1; j <= i; j++) { const returnValue = result[j][returnsColumn]; if (typeof returnValue === 'number' && !isNaN(returnValue)) { windowReturns.push(returnValue); } } if (windowReturns.length > 1) { // Calculate standard deviation const mean = windowReturns.reduce((sum, val) => sum + val, 0) / windowReturns.length; const variance = windowReturns.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / (windowReturns.length - 1); let volatility = Math.sqrt(variance); // Annualize if requested (assuming daily data) if (annualize) { volatility = volatility * Math.sqrt(252); // 252 trading days per year } result[i][resultColumn] = volatility; } else { result[i][resultColumn] = null; } } } return result; }