Advertisement
xmd79

Hybrid EMA AlgoLearner

Aug 31st, 2023
352
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
  2. // © Uldisbebris
  3.  
  4. //@version=5
  5. indicator("Hybrid EMA AlgoLearner", shorttitle="Hybrid EMA AlgoLearner", overlay=false)
  6.  
  7. // Parameters for EMAs
  8. shortTermPeriod = 50
  9. longTermPeriod = 200
  10.  
  11. // k-NN parameter
  12. k = input.int(5, 'K - Number of neighbors')
  13.  
  14. // Calculate EMAs
  15. shortTermEma = ta.ema(close, shortTermPeriod)
  16. longTermEma = ta.ema(close, longTermPeriod)
  17.  
  18. // Custom k-NN Algorithm for weighted EMA
  19. var float[] distances = array.new_float(0)
  20. array.clear(distances)
  21. for i = 1 to 100by 1 // Loop through past 100 data points
  22. distance = math.abs(shortTermEma - longTermEma[i])
  23. array.push(distances, distance)
  24. array.sort(distances)
  25.  
  26. k_distances = array.new_float(0)
  27. for i = 0 to k - 1 by 1
  28. array.push(k_distances, array.get(distances, i))
  29.  
  30. // Calculate weighted EMA based on closest k distances
  31. weightShortTermEma = 0.0
  32. totalWeight = 0.0
  33. for i = 0 to k - 1 by 1
  34. weight = array.get(k_distances, i)
  35. weightShortTermEma += shortTermEma[i] * weight
  36. totalWeight += weight
  37. weightShortTermEma /= totalWeight
  38.  
  39. // Scale weightShortTermEma between 0 - 100
  40. var float minEma = na
  41. var float maxEma = na
  42. // Instead of all the history, only look at the last N bars.
  43. lookbackPeriod = input.int(400, 'lookbackPeriod')
  44. minEma := ta.lowest(weightShortTermEma, lookbackPeriod)
  45. maxEma := ta.highest(weightShortTermEma, lookbackPeriod)
  46. scaledWeightShortTermEma = (weightShortTermEma - minEma) / (maxEma - minEma) * 100
  47.  
  48. //== plot
  49. emaplot = plot(scaledWeightShortTermEma, title='Scaled Weighted Short-Term EMA', color = color.new(#a6a8a3, 0), linewidth = 1)
  50. midLinePlot = plot(50, color = na, editable = false, display = display.none)
  51.  
  52. // Fill between plots and add horizontal lines
  53. fill(emaplot, midLinePlot, 105, 85, top_color = color.new(#057ec4, 0), bottom_color = color.new(#6ca800, 100), title = "Overbought Gradient Fill")
  54. fill(emaplot, midLinePlot, 15, -5, top_color = color.new(#a83c91, 100), bottom_color = color.new(#fcf801, 0), title = "Oversold Gradient Fill")
  55. hline(15, color = color.new(#8b3131, 50))
  56. hline(50, color = color.new(color.gray, 50))
  57. hline(85, color = color.new(#2c5c2e, 50))
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement