Advertisement
Maurizio-Ciullo

Hurst Exponent

Jun 28th, 2022
820
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //@version=4
  2. study("Hurst Exponent - Detrended Fluctuation Analysis", "BA??HE (DFA)", precision = 3, max_bars_back=5000)
  3.  
  4. //Input Strings
  5. group1        = "Sample Settings"
  6. group2        = "Log Scaling"
  7. group3        = "Style"
  8. L             = "Line"
  9. CL            = "Columns"
  10. Ci            = "Circles"
  11. ON            = "On"
  12. OFF           = "Off"
  13. //Inputs{
  14.  
  15. useRange   = input("ALL",        "Date Range",                 input.string,  options = ["HOURS", "DAYS", "WEEKS", "ALL"],  inline = "Date",        group   = group1)
  16. number     = input(300,          "Number",                     input.float,   minval  = 0,                                  group = group1,         inline  = "Date", tooltip = "Select Script Calculation Date to Reduce loading time when using high lookback")
  17. len        = input(100,          "Sample Size",                input.integer, minval  = 40,                                 group   = group1,       tooltip = "lookback period for HE, Optimal Size > 50, Larger Size More Accurate and More lag")
  18. showma     = input(false,        "Show Filter",                input.bool,    inline  = "Show MA")
  19. slen       = input(18,           "Length",                     input.integer, minval  = 4,                                  inline  = "Show MA",    tooltip = "Smoothed Moving Averge of HE")
  20. Bsc        = input(8,            "Base Scale",                 input.integer, options = [4, 8, 16],                         inline  = "Base Scale", group   = group2)
  21. Msc        = input(2,            "Max Scale",                  input.integer, options = [2, 4],                             inline  = "Base Scale", group   = group2, tooltip = "Select larger Value(Max and Base scale) when Sample Size is larger")
  22. stl        = input(Ci,           "Plot Style ",                input.string,  inline  = "Plot Style",                       options = [Ci, L, CL],  group   = group3)
  23. lT         = input(1,            "Line Thickness",             input.integer, inline  = "Plot Style",                       options = [1,2,3],      group   = group3)
  24. c_ma       = input(color.orange, "MA",                         input.color,   inline  = "MA",                               group   = group3)
  25. lTma       = input(1,            "Line Thickness",             input.integer, inline  = "MA",                               options = [1,2,3],      group   = group3)
  26. c_t        = input(color.aqua,   "> 0.5",                      input.color,   inline  = "> 0.5",                            group   = group3)
  27. c_m        = input(#FF0080ff,    "< 0.5",                      input.color,   inline  = "> 0.5",                            group   = group3)
  28. c_st       = input(color.lime,   "Significant Trend",          input.color,   inline  = "Significant Trend",                group   = group3)
  29. c_sm       = input(color.yellow, "Significant Mean Reversion", input.color,   inline  = "Significant Trend",                group   = group3)
  30. c_cv       = input(color.white,  "Confidence Interval",        input.color,   inline  = "Confidence Interval",              group   = group3)
  31. c_mid      = input(color.white,  "Mid Line",                   input.color,   inline  = "Confidence Interval",              group   = group3)
  32. dt         = input(ON,           "Show Table",                 input.string,  options = [ON, OFF],                          inline  = "table",      group   = group3) == ON
  33. bg         = input(ON,           "Dark Background",            input.string,  options = [OFF,ON],                           group   = group3) == ON
  34. tsize      = input("normal",     "Size",                       input.string,  options = ["tiny", "small", "normal", "large", "huge", "auto"],       inline = "table", group = group3)
  35.  
  36. //Background Color
  37. bgcolor(bg ? color.new(#000000,20) : na, title = "Dark Background")
  38.  
  39. //Start Time Calculation (Credit to Allanster)
  40. oneHour  = 60 * 60 * 1000
  41. oneDay   = 24 * 60 * 60 * 1000
  42. oneWeek  = 7 * oneDay
  43. present  = timenow
  44. start    = useRange == "HOURS" ? present - number * oneHour:
  45.           useRange == "DAYS" ? present - number * oneDay :
  46.           useRange == "WEEKS" ? present - number * oneWeek : na
  47.  
  48. //Condition to save Computing time
  49. t = useRange == "ALL" ? true : time >= start
  50.  
  51.  
  52. //Declaration
  53. int   Min     = Bsc
  54. int   Max     = Msc
  55. var   fluc    = array.new_float(10)
  56. var   scale   = array.new_float(10)
  57. float slope   = na
  58.  
  59. //Functions
  60. ss(Series, Period) => // Super Smoother Function
  61.     var PI    = 2.0 * asin(1.0)
  62.     var SQRT2 = sqrt(2.0)
  63.     lambda = PI * SQRT2 / Period
  64.     a1     = exp(-lambda)
  65.     coeff2 = 2.0 * a1 * cos(lambda)
  66.     coeff3 = - pow(a1, 2.0)
  67.     coeff1 = 1.0 - coeff2 - coeff3
  68.     filt1  = 0.0
  69.     filt1 := coeff1 * (Series + nz(Series[1])) * 0.5 + coeff2 * nz(filt1[1]) + coeff3 * nz(filt1[2])
  70.     filt1
  71.  
  72. //}
  73.  
  74. //Calculation{
  75.  
  76. //Log Return
  77. r = log(close/close[1])
  78. //Mean of Log Return
  79. mean = sma(r,len)
  80.  
  81. //Cumulative Sum
  82. var csum = array.new_float(len)
  83. if t
  84.     sum = 0.0
  85.     for i = 0 to len-1
  86.         sum := (r[i] - mean) + sum
  87.         array.set(csum,i,sum)
  88.  
  89. //Root Mean Sum (FLuctuation) function linear trend to calculate error between linear trend and cumulative sum
  90. RMS(N1,N)=>
  91.     if t
  92.         //Slicing the array into different segments
  93.         var seq = array.new_float(N)
  94.         int count = 0
  95.         for i = 0 to N-1
  96.             count := count + 1
  97.             array.set(seq,i,count)
  98.         y = array.slice(csum,N1,N1+N)
  99.        
  100.         //Linear regression measuing trend (N/(N-1) for sample unbiased adjustedment)
  101.         sdx = array.stdev(seq)       *sqrt(N/(N-1))
  102.         sdy = array.stdev(y)         *sqrt(N/(N-1))
  103.         cov = array.covariance(seq,y)*(N/(N-1))
  104.        
  105.         //Linear Regression Root Mean Square Error (Detrend)
  106.         r2 = pow(cov/(sdx*sdy),2)
  107.         rms = sqrt(1 - r2)*sdy
  108.  
  109. //Average of Root Mean Sum Measured each block (Log Scale)
  110. Arms(bar)=>
  111.     if t
  112.         num = floor(len / bar)
  113.         sumr = 0.0
  114.         for i = 0 to num-1
  115.             sumr := sumr + RMS(i*bar,bar)
  116.         //Log Scale
  117.         avg = log10(sumr/num)
  118.  
  119. //Approximating Log Scale Function (Saves Sample Size)
  120. fs(x)=>
  121.     if t
  122.         round(Min*pow(pow(len/(Max*Min),0.1111111111),x))
  123.  
  124. if t
  125.     //Set Ten points of Root Mean Square Average along the Y log axis
  126.     array.set(fluc,0,Arms(fs(0)))
  127.     array.set(fluc,1,Arms(fs(1)))
  128.     array.set(fluc,2,Arms(fs(2)))
  129.     array.set(fluc,3,Arms(fs(3)))
  130.     array.set(fluc,4,Arms(fs(4)))
  131.     array.set(fluc,5,Arms(fs(5)))
  132.     array.set(fluc,6,Arms(fs(6)))
  133.     array.set(fluc,7,Arms(fs(7)))
  134.     array.set(fluc,8,Arms(fs(8)))
  135.     array.set(fluc,9,Arms(fs(9)))
  136.    
  137.     //Set Ten Points of data scale along the X log axis
  138.     for i = 0 to 9
  139.         array.set(scale,i,log10(fs(i)))
  140.  
  141.     //SLope Measured From RMS and Scale on Log log plot using linear regression
  142.     slope := array.covariance(scale,fluc) / array.variance(scale)
  143.  
  144. //Moving Average Smoothed Hurst Exponent
  145. smooth = showma ? ss(slope,slen)  : na
  146.  
  147. //Critical Value based on Confidence Interval (95% Confidence)
  148. ci = 1.645 * (0.3912 / pow(len,0.3))
  149. //Expected Value plus Crtical Value
  150. cu = 0.5 + ci
  151. cd = 0.5 - ci
  152.  
  153. //}
  154.  
  155. //Plots{
  156.  
  157. //plotstyle
  158. pstyle  = stl == L ? plot.style_linebr :
  159.          stl == CL ? plot.style_columns :
  160.          stl == Ci ? plot.style_circles :
  161.          plot.style_line
  162.  
  163. //Color of HE
  164. c  = slope > cu ? c_st : slope >= 0.5 ? c_t : slope < cd ? c_sm  : slope < 0.5 ?  c_m : na
  165. //Text of Table
  166. text = slope > cu ? "Significant Trend" : slope >= 0.5 ? "Trend" : slope < cd ? "Significant Mean Reversion" : slope < 0.5 ? "Mean Reversion" : na
  167.  
  168. //Plotting
  169. plot(slope, "Hurst Exponent", color=c, style = pstyle, linewidth = lT)
  170.  
  171. plot(cu, "Confidence Interval", color = c_cv, trackprice = true, show_last = 1)
  172. plot(cd, "Confidence Interval", color = c_cv, trackprice = true, show_last = 1)
  173.  
  174. plot(smooth, "MA", color=c_ma, linewidth = lTma)
  175.  
  176. //0.5 Mid Level
  177. line mid = na
  178. if barstate.islast
  179.     mid := line.new(bar_index-1, 0.5, bar_index, 0.5, xloc.bar_index, extend.left, color=c_mid, style = line.style_dashed )
  180.     line.delete(mid[1])
  181.  
  182. //Table
  183. var table htable = table.new(position.middle_right,2 , 2, bgcolor = color.new(color.black,100), frame_color = #000000, frame_width = 2, border_color = color.new(color.black,100), border_width = 3)
  184. if barstate.islast and dt
  185.     table.cell(htable, column = 0, row = 0, text = "Hurst Exponent:",        text_color = color.white, bgcolor = color.new(color.gray,50), text_size = tsize)
  186.     table.cell(htable, column = 1, row = 0, text = tostring(round(slope,3)), text_color = c,           bgcolor = color.new(c,85),          text_size = tsize)
  187.     table.cell(htable, column = 0, row = 1, text = "State:",                 text_color = color.white, bgcolor = color.new(color.gray,50), text_size = tsize)
  188.     table.cell(htable, column = 1, row = 1, text = text,                     text_color = c,           bgcolor = color.new(c,85),          text_size = tsize)
  189. //}
  190.  
  191.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement