xmd79

Function - Array Transform Box-Cox

Jun 20th, 2022 (edited)
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 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. // © RicardoSantos
  3.  
  4. //@version=5
  5. indicator(title='Function - Array Transform Box-Cox')
  6. // https://www.statology.org/box-cox-transformation-excel/
  7. // https://www.geeksforgeeks.org/box-cox-transformation-using-python/
  8. // https://github.com/business-science/timetk/blob/master/R/vec-box_cox.R
  9. // https://frost-lee.github.io/box-cox-linear-model/
  10. // https://otexts.com/fpp2/transformations.html
  11. //
  12.  
  13. array_transform_boxcox_regular(_sample, _lambda) =>
  14. int _size = array.size(id=_sample)
  15. if _size > 0
  16. _X = array.copy(id=_sample)
  17. for _i = 0 to _size - 1 by 1
  18. _xi = array.get(id=_X, index=_i)
  19. if _lambda == 0
  20. array.set(id=_X, index=_i, value=math.log(_xi))
  21. else
  22. array.set(id=_X, index=_i, value=math.sign(_xi) * (math.pow(math.abs(_xi), _lambda) - 1) / _lambda)
  23. _X
  24.  
  25. array_transform_boxcox_inverse(_sample, _lambda) =>
  26. int _size = array.size(id=_sample)
  27. if _size > 0
  28. _X = array.copy(id=_sample)
  29. for _i = 0 to _size - 1 by 1
  30. _xi = array.get(id=_X, index=_i)
  31. if _lambda == 0
  32. array.set(id=_X, index=_i, value=math.exp(_xi))
  33. else
  34. _xe = _lambda * _xi + 1.0
  35. array.set(id=_X, index=_i, value=math.sign(_xe) * math.pow(math.abs(_xe), 1.0 / _lambda))
  36. _X
  37.  
  38. lambda = input(0.5225)
  39. sample_data = array.from(4.0, 5.0, 2.0, 3.0, 3.0, 2.0, 2.0, 3.0, 2.0, 3.0, 4.0, 3.0, 8.0, 6.0)
  40. Y = array_transform_boxcox_regular(sample_data, lambda)
  41. iY = array_transform_boxcox_inverse(Y, lambda)
  42. var label la = label.new(bar_index, 0.0, '')
  43. label.set_xy(la, bar_index, 0.0)
  44. label.set_text(la, 'sample: ' + str.tostring(sample_data) + '\ninverse: ' + str.tostring(iY) + '\nregular: ' + str.tostring(Y))
  45. plot(array.get(Y, bar_index % array.size(Y)))
  46.  
  47.  
Add Comment
Please, Sign In to add comment