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.13 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.calculateMaxDrawdown = calculateMaxDrawdown;
/**
* Calculates the maximum drawdown for a time series of values.
*
* The function iterates through the provided data array, tracking the peak value and computing the drawdown
* at each point. The maximum drawdown observed up to each row is stored in the specified result column.
*
* @param data - An array of objects representing the time series data.
* @param sourceColumn - The key in each object from which to read the numeric value for drawdown calculation.
* @param resultColumn - The key in which to store the calculated maximum drawdown for each row (default: 'maxDrawdown').
* @returns A new array of objects, each including the calculated maximum drawdown in the specified result column.
*
* @remarks
* - If the value in `sourceColumn` is not a valid number, the previous row's drawdown value is used.
* - The drawdown is calculated as `(peak - value) / peak`, where `peak` is the highest value observed so far.
* - If the input data is empty or undefined, an empty array is returned.
*/
function calculateMaxDrawdown(data, sourceColumn, resultColumn = 'maxDrawdown') {
if (!data || data.length === 0) {
return [];
}
const result = data.map(row => ({ ...row }));
let peak = -Infinity;
let maxDrawdown = 0;
for (let i = 0; i < result.length; i++) {
const value = result[i][sourceColumn];
if (typeof value === 'number' && !isNaN(value)) {
// Update peak if current value is higher
if (value > peak) {
peak = value;
}
// Calculate current drawdown
const currentDrawdown = (peak - value) / peak;
// Update max drawdown if current is larger
if (currentDrawdown > maxDrawdown) {
maxDrawdown = currentDrawdown;
}
result[i][resultColumn] = maxDrawdown;
}
else {
result[i][resultColumn] = i > 0 ? result[i - 1][resultColumn] : 0;
}
}
return result;
}