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.23 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.calculatePortfolioReturns = calculatePortfolioReturns;
/**
* Calculates the portfolio returns for a given dataset of asset returns and weights.
*
* Iterates over each row of asset returns, computes the weighted return for specified assets,
* and normalizes the result if the total weight does not sum to 1. The function adds the calculated
* portfolio return, total weight, and count of valid assets to each row.
*
* @param data - Array of asset return objects, where each object represents a row of asset returns.
* @param weights - An object mapping asset column names to their respective portfolio weights.
* @param returnColumns - Array of column names representing the assets to include in the calculation.
* @param portfolioReturnColumn - (Optional) Name of the column to store the calculated portfolio return. Defaults to 'portfolio_return'.
* @returns An array of objects, each containing the original row data, the calculated portfolio return,
* the total weight used, and the number of valid assets considered.
*/
function calculatePortfolioReturns(data, weights, returnColumns, portfolioReturnColumn = 'portfolio_return') {
if (!data || data.length === 0) {
return [];
}
return data.map(row => {
let portfolioReturn = 0;
let totalWeight = 0;
let validAssets = 0;
// Calculate weighted return
returnColumns.forEach(assetColumn => {
const assetReturn = row[assetColumn];
const assetWeight = weights[assetColumn] || 0;
if (typeof assetReturn === 'number' && !isNaN(assetReturn) && assetWeight > 0) {
portfolioReturn += assetReturn * assetWeight;
totalWeight += assetWeight;
validAssets++;
}
});
// Normalize if weights don't sum to 1
if (totalWeight > 0 && totalWeight !== 1) {
portfolioReturn = portfolioReturn / totalWeight;
}
return {
...row,
[portfolioReturnColumn]: validAssets > 0 ? portfolioReturn : null,
totalWeight,
validAssets,
};
});
}