Yo, posting it for the whole internet, took the whole day to find / to design the actual working solution for weighted percentile 'nearest rank' algorithm, almost no reliable info online and a lot of library-style/textbook-style solutions that don't provide on real world production level.
3) say we wanna find 50th percentile, get a threshold value: n = 50 thres = weights_sum / 100 * n 7.5 = 15 / 100 * 50
4) iterate through weights_cum until you find a value that >= the threshold: for i = 0 to size - 1 2 >= 7.5 ? nah 7 >= 7.5 ? nah 10 >= 7.5 ? aye
5) take the iteration index that resulted "aye", and find the data value with the same index, that's gonna be the resulting percentile. i = 2 data = 33
This one is not an approximation, not an estimator, it's the actual weighted percentile nearest rank as it is.
I tested the thing extensively and it works perfectly. For the skeptics, check lines 40, 41, 69 in the code, you can comment/uncomment dem to switch for unit (1) weights, resulting in the usual non-weighted percentile nearest rank that ideally matches the TV's built-in function.
Shoutout for @wallneradam for the sorting function mane ... Live Long and Prosper
In true TradingView spirit, the author of this script has published it open-source, so traders can understand and verify it. Cheers to the author! You may use it for free, but reuse of this code in publication is governed by House rules. You can favorite it to use it on a chart.
Want to use this script on a chart?
Disclaimer
The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.