Linear Regression Slope Annualized with R-squared Histogram


SUBMITTED BY: trior

DATE: Jan. 4, 2021, 4:14 p.m.

FORMAT: JavaScript

SIZE: 1.7 kB

HITS: 328

  1. //@version=4
  2. // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
  3. // Linear Regression Slope Annualized with R-squared Histogram
  4. // by SparkyFlary
  5. study(title="Linear Regression Slope Annualized with R-squared Histogram", shorttitle="Linear Regression Slope", overlay=false)
  6. length = input(80, title="Slope length")
  7. rSquaredThreshold = input(0.0, title="R-squared threshold", minval=0, maxval=1)
  8. withAnnualize = input(true, title="Annualize slope?")
  9. daysInYear = input(240, title="Number of bars in a year(if slope is annualized)")
  10. src = input(close, title="Source")
  11. slopeCalcMethod = input("wma-sma", options=["wma-sma", "(linreg-linreg[length])/length"])
  12. nlPrice = log(src)
  13. slope = slopeCalcMethod=="wma-sma" ? 6*(wma(nlPrice, length) - sma(nlPrice, length))/(length-1) : (linreg(nlPrice,length,0)-linreg(nlPrice,length,0)[length])/length
  14. rSquared = pow(correlation(cum(1), nlPrice, length), 2)
  15. slopeAnnualized = (pow(exp(slope),daysInYear)-1) * (rSquared) * 100
  16. mult = withAnnualize ? slopeAnnualized * rSquared : slope * rSquared
  17. trend = rSquared>rSquaredThreshold
  18. rising = mult>mult[1]
  19. falling = mult<mult[1]
  20. up = mult>0
  21. down = mult<0
  22. up_rising_color = color.new(color.green, 0)
  23. up_falling_color = color.new(color.green, 50)
  24. down_falling_color = color.new(color.red, 0)
  25. down_rising_color = color.new(color.red, 50)
  26. c = trend and up and rising?up_rising_color:trend and up and falling?up_falling_color:trend and down and falling?down_falling_color:trend and down and rising?down_rising_color : color.gray
  27. plot(mult, title="Annualized slope x R-squared", style=plot.style_histogram, color = c, linewidth=3)

comments powered by Disqus