0

I'm trying to find the Nth highest/lowest value of a ratio within Pine v5. This is ultimately part of a process to try and determine the top/bottom 1% values of a ratio to find extreme outliers. My current thought process is to store all ratio values within an array, sort and find the relevant ID based on the total bars from the bar_index; but I'm experiencing errors and feel I may be going the wrong route...

Here's my current code, replaced the ratio I'm using with just some generic place holder:

ratio = high / low

n_bar = 10

length = bar_index + 1
ratio_array = array.new_float(length)

for i = 0 to length - 1
    array.push(ratio_array, ratio)
ranked_ratio = array.sort(ratio_array, order.ascending)
tenth_highest = array.get(ranked_ratio, n_bar)

Currently getting a 'Void expression cannot be assigned to a variable' error.

Any help would be greatly appreciated, thanks in advance!

Oxelo
  • 7
  • 2

1 Answers1

0

array.sort() function returns a void expression that cannot be assigned to a variable (ranked_ratio).

array.sort(id, order) → void

Simply call the sort function and reference the sorted array in the array.get():

for i = 0 to length - 1
    array.push(ratio_array, ratio)
    
array.sort(ratio_array, order.ascending)
tenth_highest = ratio_array.size() > n_bar ? array.get(ratio_array, n_bar) : 0
plot(tenth_highest)
e2e4
  • 3,428
  • 6
  • 18
  • 30
  • This unfortunately gives a error on bar 0 when trying to add - potentially as the actual ratio I'm using requires a few bars to calculate? Also do you have any ideas on how we could potentially alter finding the Nth highest to finding the ratio value that only say 5% of the entire candles history surpasses? – Oxelo Jun 27 '23 at 13:51
  • Updated the example and added an explicit check of the array size before calling `get` function, so the `tenth_highest` will return 0 if the size of the array is less than 10. – e2e4 Jun 27 '23 at 17:03
  • As for checking the history, you currently loop through the entire history on the chart (`for i = 0 to bar_index+1`), use, for example, a constant value of 100/500 candles instead of `bar_index` to reduce the loop size. – e2e4 Jun 27 '23 at 17:05
  • I managed to solve my solution with your help! Especially considering my comment of trying to identify outliers by percentage of history: `code` var array ratio_rank = array.new() if not na(ratio) array.unshift(ratio_rank, ratio) upper_bound = array.percentile_nearest_rank(ratio_rank, 95) lower_bound = array.percentile_nearest_rank(ratio_rank, 5) `code` Thanks for your help! – Oxelo Jun 28 '23 at 04:57