Hi Forum,
I’d like to plot the long term trend of SPX on a monthly chart using a script. (It’s easy enough to use the Trend Line drawing tool when the chart has a logarithmic scale, but I’d like to be able to mathematically calculate the long term trend value month-by-month, so I have a value each month to work with in other scripts).
I’ve developed a script that almost gets there, but not quite. Here it is:
// Calculation of compound monthly growth rates of SPX // Use Compound Monthly Growth Rate (CMGR) to be able to plot growth rate on SPX monthly chart. // @constant {integer} The average number of days per month. daysPerMonth = Abs(365.25 / 12); // @constant {integer} The starting date for the CMGR calculation, being Friday 6 January 1950. startDate = Abs(18269); // @constant {integer} The ending date for the CMGR calculation, being Friday 28 June 2019. endDate = Abs(43644); // @constant {number} The closing price of the market on the starting date. startValue = Abs(16.98); // @constant {number} The closing price of the market on the ending date. endValue = Abs(2941.76); // {number} The duration in months between the starting and ending dates. numberOfMonths = (endDate - startDate) / daysPerMonth; // {number} The power value to be used in the CMGR calculation. $powerValue = 1 / numberOfMonths; // {number} The Compound Monthly Growth Rate calculation: CMGR = (endValue / startValue) ^ (1 / numberOfMonths). CMGR = POWER(endValue / startValue, POWER=$powerValue); // {number} The number of months between the current BARDATE and January 1950, to be used as the power value in the month-by-month growth path of SPX. $months = FLOOR((BARDATE() - startDate) / daysPerMonth) + 1; // {number} The month-by-month value of the compounding monthly growth rate of SPX. startValue * POWER(CMGR, POWER=$months);
I think the issue is in the last line, where the bar value ($months) in the POWER function is dynamic, that is, it changes with each month. Just prior to the last line I used a bar value ($powerValue) in the POWER function but it is static (always being the same value regardless of date), and that seemed to work OK.
A show plot on the script gives a horizontal line that is equivalent to the variable endValue in the script. This sort of suggests that the last line of the script always evaluates as if BARDATE() is today’s date, not the value of the date at that specific point in the chart.
Has anyone had any experience with using the POWER function with a dynamic power value that changes as the date changes? Or is there another clever way to achieve the same?
Many thanks, Dean