fintech-algorithms
Using a coding agent? Give it the skill: npx skills add IslamBaraka90/Fintech-Algorithms-Library What it does →

Ranks, Ties, and Percentile Rank

Install and import#

bash
npm install fintech-algorithms
ts
import { ranksTiesAndPercentileRank } from "fintech-algorithms/foundations/location-ranking-and-exploratory-summaries/ranks-ties-and-percentile-rank";

Signature#

ranksTiesAndPercentileRank(input)

Assigns each observation its position in the sorted series, giving tied observations the average of the positions they span, and rescales those ranks onto a 0-to-100 percentile scale.

Parameters#

NameTypeNotes
input{ values: number[] }The observations to rank, under the key values. Ranks are returned in the caller's original order, not in sorted order.

Returns#

{ ranks: number[]; percentileRanks: number[]; tieCount: number }

ranks holds one-based average ranks aligned to the input order, percentileRanks maps each rank onto 0 to 100 as (rank - 1) / (n - 1) * 100, and tieCount is how many observations are duplicates of a value already seen.

Errors#

  • When input is null, an array, or not an object — throws TypeError
  • When values is missing, is not an array, or is empty — throws RangeError
  • When any entry of values does not coerce to a finite number — throws RangeError
  • When values holds fewer than two observations, which would make the percentile scale divide by zero — throws RangeError

Complexity: time O(n log n), space O(n).

Worked example#

verified This is the worked example published in the article, replayed by the test suite on every run. The output cannot drift.

Input#

input
{
  "values": [1, 2, 2, 4, 9],
  "weights": [1, 1, 2, 1, 1],
  "trimProportion": 0.2,
  "bins": 4
}

Call#

ranksTiesAndPercentileRank(input)

Returns#

object with 2 fields: ranks, percentileRanks

{
  "ranks": [1, 2.5, 2.5, 4, 5],
  "percentileRanks": [0, 37.5, 37.5, 75, 100]
}

Diagrams#

Ranks, Ties, and Percentile Rank — article hero
Ranks, Ties, and Percentile Rank — calculation ledger
Ranks, Ties, and Percentile Rank — comparison map
Ranks, Ties, and Percentile Rank — concept anatomy
Ranks, Ties, and Percentile Rank — mistake contrast
Ranks, Ties, and Percentile Rank — scenario map

How it works#

This page states the contract — how to call it correctly. The article explains the concept: why it works, and where it breaks.

Read the article →

References#

  • rankdata
  • Historical-example decision

The rest of the Location, Ranking, and Exploratory Summaries family#