quantitivecalc
Version:
A TypeScript library providing advanced quantitative finance functions for risk analysis, performance metrics, and technical indicators. (Currently in development)
52 lines (51 loc) • 2.53 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.calculateDailyReturns = calculateDailyReturns;
/**
* Calculates the daily returns for a given array of data objects.
*
* The function computes the daily return for each row based on the specified `sourceColumn`.
* The daily return is calculated as `(current - previous) / previous` for each consecutive row.
* The result is stored in a new column specified by `resultColumn` (default: `'dailyReturn'`).
* The first row's daily return is set to `initialValue` (default: `0`).
* If the required values are not valid numbers or the previous value is zero, the daily return is set to `null`.
*
* @param data - Array of data objects containing the source values.
* @param sourceColumn - The key in each object from which to read the value for return calculation.
* @param resultColumn - The key under which to store the calculated daily return (default: `'dailyReturn'`).
* @param initialValue - The value to assign as the daily return for the first row (default: `0`).
* @returns A new array of data objects with the daily returns added in the specified result column.
*/
function calculateDailyReturns(data, sourceColumn, resultColumn = 'dailyReturn', initialValue = 0) {
if (!data || data.length === 0) {
return [];
}
// Create a copy of the data to avoid mutating the original
const result = data.map(row => ({ ...row }));
// Calculate daily returns for each row starting from index 1
for (let i = 0; i < result.length; i++) {
if (i === 0) {
// First row has no previous value, so daily return is null/undefined
result[i][resultColumn] = initialValue;
}
else {
const currentValue = result[i][sourceColumn];
const previousValue = result[i - 1][sourceColumn];
// Check if both values are valid numbers
if (typeof currentValue === 'number' &&
typeof previousValue === 'number' &&
previousValue !== 0 &&
!isNaN(currentValue) &&
!isNaN(previousValue)) {
// Daily return formula: (current - previous) / previous
const dailyReturn = (currentValue - previousValue) / previousValue;
result[i][resultColumn] = dailyReturn;
}
else {
// Invalid data - set to null
result[i][resultColumn] = null;
}
}
}
return result;
}