quantitivecalc
Version:
A TypeScript library providing advanced quantitative finance functions for risk analysis, performance metrics, and technical indicators. (Currently in development)
48 lines (47 loc) • 2 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.calculateAnnualizedReturns = calculateAnnualizedReturns;
/**
* Calculates annualized returns for each row in the provided data array.
*
* @param data - Array of objects containing return values.
* @param returnsColumn - The key in each object representing the periodic return value.
* @param resultColumn - The key where the calculated annualized return will be stored.
* @param frequency - The frequency of the returns ('daily', 'weekly', or 'monthly'). Defaults to 'daily'.
* @param method - The method used for annualization ('compound' or 'simple'). Defaults to 'compound'.
* - 'compound': Uses the formula (1 + return)^periods - 1.
* - 'simple': Uses the formula return * periods.
* @returns A new array of objects with annualized returns added under the specified result column.
*/
function calculateAnnualizedReturns(data, returnsColumn, resultColumn, frequency = 'daily', method = 'compound') {
if (!data || data.length === 0) {
return [];
}
const result = data.map(row => ({ ...row }));
// Periods per year based on frequency
const periodsPerYear = {
daily: 252, // Trading days
weekly: 52,
monthly: 12,
};
const periods = periodsPerYear[frequency];
for (let i = 0; i < result.length; i++) {
const returnValue = result[i][returnsColumn];
if (typeof returnValue === 'number' && !isNaN(returnValue)) {
let annualizedReturn;
if (method === 'compound') {
// Compound: (1 + return)^periods - 1
annualizedReturn = Math.pow(1 + returnValue, periods) - 1;
}
else {
// Simple: return * periods
annualizedReturn = returnValue * periods;
}
result[i][resultColumn] = annualizedReturn;
}
else {
result[i][resultColumn] = null;
}
}
return result;
}