Momentum
The Momentum indicator measures the rate of change in a security’s price over a specified period. It is calculated by subtracting the closing price from n periods ago from the current closing price. Traders use this to gauge the strength of a trend and identify potential reversal points.
MOMENTUM
=MOMENTUM(data, period) Example Usage
=MOMENTUM(A2:F500, 14)
Parameters
| Parameter | Type | Description | Status |
|---|---|---|---|
data | Range | The input range of columns containing the Date, Open, High, Low, Close, and Volume data. | Required |
period | Number | The number of periods for the calculation. Default is 14. | Optional |
Returns
A two-column array of dates and their corresponding Momentum values.
Source Code
Copy the following code into your Apps Script editor (Extensions > Apps Script) to use the MOMENTUM function in your spreadsheet.
momentum.js
/**
* Calculates the Momentum indicator for a specified period.
* Momentum measures the change in price between the current price and the price n periods ago.
*
* @param {array} data - The input range. Can be a multi-column range (Date, Open, High, Low, Close, Volume) or a two-column range (Date, Value).
* @param {number} period - The number of periods to look back (e.g., 10).
* @returns {array} A two-column array with headers "Date" and "Momentum".
* @customfunction
*/
function MOMENTUM(data, period) {
checkPremium();
// Argument validation
if (arguments.length !== 2) {
throw new Error(`Wrong number of arguments. Expected 2, but got ${arguments.length}.`);
}
if (typeof period !== 'number' || period <= 0 || !Number.isInteger(period)) {
throw new Error(`Invalid period. The period must be a positive integer. Got: ${period}`);
}
const processedData = getData(data);
// --- NEW: Function-level validation ---
const columnCount = processedData[0].length;
if (columnCount > 2 && columnCount < 5) {
throw new Error(`Invalid data structure for Momentum. For multi-column data, expected at least 5 columns (Date, O, H, L, C), but got ${columnCount}. For simple data, expected 2 columns (Date, Value).`);
}
// --- END of validation ---
const dates = processedData.slice(1).map(row => row[0]);
const values = getValues(processedData);
if (period >= values.length) {
throw new Error(`Invalid period. The period (${period}) cannot be greater than or equal to the number of data points (${values.length}).`);
}
const results = [["Date", `Momentum(${period})`]];
for (let i = period; i < values.length; i++) {
const momentum = values[i] - values[i - period];
results.push([dates[i], momentum]);
}
return results;
}