UNPKG

quantitivecalc

Version:

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

37 lines (36 loc) 2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.calculateCompoundReturns = calculateCompoundReturns; /** * Calculates compound returns over a dataset and adds the result to each row. * * Iterates through the provided data array, compounding the specified returns column * and storing the result in a new column for each row. The compounding formula used is: * `compoundValue = previousValue * (1 + dailyReturn)`. The result column will contain * `compoundValue - 1 + addValue` for each row. * * @param data - Array of objects representing the dataset. Each object should contain the returns column. * @param returnsColumn - The key in each object representing the daily return value. Defaults to `'dailyReturn'`. * @param resultColumn - The key to store the calculated compound return in each object. * @param initialValue - The initial value to start compounding from. Defaults to `1`. * @param addValue - A constant value to add to the final compound return for each row. Defaults to `1`. * @returns A new array of objects with the compound return added to each row under `resultColumn`. */ function calculateCompoundReturns(data, returnsColumn = 'dailyReturn', resultColumn, initialValue = 1, addValue = 1) { if (!data || data.length === 0) { return []; } // Create a copy of the data to avoid mutating the original const result = data.map(row => ({ ...row })); let compoundValue = initialValue; for (let i = 0; i < result.length; i++) { const dailyReturn = result[i][returnsColumn]; if (typeof dailyReturn === 'number' && !Number.isNaN(dailyReturn)) { // Compound formula: previous_value * (1 + daily_return) compoundValue = compoundValue * (1 + dailyReturn); } // If daily return is null/invalid, keep the same compound value result[i][resultColumn] = compoundValue - 1 + addValue; // Add a constant value if specified } return result; }