Skip to content

Instantly share code, notes, and snippets.

@IceCreamYou
Last active November 17, 2022 01:54
Show Gist options
  • Save IceCreamYou/6ffa1b18c4c8f6aeaad2 to your computer and use it in GitHub Desktop.
Save IceCreamYou/6ffa1b18c4c8f6aeaad2 to your computer and use it in GitHub Desktop.
Utility functions to calculate percentiles and percent ranks in a JavaScript array.
// Returns the value at a given percentile in a sorted numeric array.
// "Linear interpolation between closest ranks" method
function percentile(arr, p) {
if (arr.length === 0) return 0;
if (typeof p !== 'number') throw new TypeError('p must be a number');
if (p <= 0) return arr[0];
if (p >= 1) return arr[arr.length - 1];
var index = (arr.length - 1) * p,
lower = Math.floor(index),
upper = lower + 1,
weight = index % 1;
if (upper >= arr.length) return arr[lower];
return arr[lower] * (1 - weight) + arr[upper] * weight;
}
// Returns the percentile of the given value in a sorted numeric array.
function percentRank(arr, v) {
if (typeof v !== 'number') throw new TypeError('v must be a number');
for (var i = 0, l = arr.length; i < l; i++) {
if (v <= arr[i]) {
while (i < l && v === arr[i]) i++;
if (i === 0) return 0;
if (v !== arr[i-1]) {
i += (v - arr[i-1]) / (arr[i] - arr[i-1]);
}
return i / l;
}
}
return 1;
}
@ityoung2016
Copy link

There seems to be a real bug in this program. Use arr = [1,2,3,18,19,27] and p = ½. The result should be 21/2 = 11.5 but the program gives 18. Then try arr = [1,2,3,18,19,22,27] with p = ½. The answer should be 18 but the program gives 18.5.

@markmelville
Copy link

@ityoung2016 Agreed, but 21/2 is 10.5, not 11.5. If line 9 is changed to: var index = (arr.length - 1) * p, then it passes both your tests.

@scottlingran
Copy link

Alternative percentile rank, closer to python's scipy.stats.percentileofscore

function percentRank(array, n) {
    var L = 0;
    var S = 0;
    var N = array.length

    for (var i = 0; i < array.length; i++) {
        if (array[i] < n) {
            L += 1
        } else if (array[i] === n) {
            S += 1
        } else {

        }
    }

    var pct = (L + (0.5 * S)) / N

    return pct
}

@AbuSufyan
Copy link

AbuSufyan commented Dec 15, 2016

Hi,
Thanks for your valuable contribution to writing such a nice code. I had found an issue when we calculate Percentile of decimal values. It's not calculated accurately because resulted value is not matched with Excel resulted value. We need to sort the array before going to perform operations on it. I had added sorting functionality in the following code. Now resulted value is matched with Excel value.

function percentile(arr, p) {
if (arr.length === 0) return 0;
if (typeof p !== 'number') throw new TypeError('p must be a number');
if (p <= 0) return arr[0];
if (p >= 1) return arr[arr.length - 1];

arr.sort(function (a, b) { return a - b; });
var index = (arr.length - 1) * p
    lower = Math.floor(index),
    upper = lower + 1,
    weight = index % 1;

if (upper >= arr.length) return arr[lower];
return arr[lower] * (1 - weight) + arr[upper] * weight;
}

@superzadeh
Copy link

superzadeh commented Jan 25, 2018

I've ported the function rank method from numpy's percentileofscore.

You need to have ramda as dependency, but chances are if you need this function, you already use ramda to facilitate functional programming:

const R = require('ramda')
const percentileOfScore = (array, value) => {
  let originalLength = array.length
  let a = [...array]
  let alen
  const equalsValue = v => v === value

  if (!R.any(equalsValue, array)) {
    a.push(value)
    alen = range(a.length)
  } else {
    alen = range(a.length + 1)
  }
  const sortedArray = R.sort((a, b) => a - b, array)
  const idx = R.map(equalsValue, sortedArray)
  const alenTrue = R.filter((v, i) => {
    return idx[alen.indexOf(v)] === true
  }, alen)
  const mean = R.mean(alenTrue)
  const percent = mean / originalLength
  return percent
}

@ovaris
Copy link

ovaris commented Feb 8, 2018

@superzadeh Thanks for the function! Here's modified version that uses Lodash (to get the mean) and it expects array to be already sorted (to avoid n * sorting):

const percentileOfScore = (array, value) => {
    const originalLength = array.length;
    const a = [...array];
    let alen;
    const equalsValue = v => v === value;

    if (!array.some(equalsValue)) {
        a.push(value);
        alen = range(a.length)
    } else {
        alen = range(a.length + 1)
    }
    const idx = array.map(equalsValue);
    const alenTrue = alen.filter((v) => idx[alen.indexOf(v)]);
    const meanVal = mean(alenTrue);
    const percent = meanVal / originalLength;
    return Math.round( percent * 100) / 100;
};

@IceCreamYou
Copy link
Author

I don't know why I didn't see all these comments for years, but thanks for the contributions. I updated line 9.

@25yeht
Copy link

25yeht commented Sep 16, 2021


@brandonros
Copy link

// sort + filter by open interest
  {
    filteredBacktestResults.sort((a, b) => a.open_interest - b.open_interest)
    const values = filteredBacktestResults.map(backtestResult => backtestResult.open_interest)
    for (let i = 0; i < filteredBacktestResults.length; ++i) {
      filteredBacktestResults[i].open_interest_rank_percentile = percentRank(values, filteredBacktestResults[i].open_interest)
    }
    filteredBacktestResults = filteredBacktestResults.filter(backtestResult => {
      const openInterestTooLow = backtestResult.open_interest_rank_percentile <= 0.25 // bottom 25%
      if (openInterestTooLow === true) {
        return false
      }
      return true
    })
  }

hopefully this example helps somebody else on Google of how to use this, thank you @IceCreamYou + others who helped make it better

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment