Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

ML coding · Statistics in code

Spearman rank correlation (the information coefficient)

Medium · Target 15 minutes · Python and NumPy

Given two equal-length lists x and y, neither constant, return Spearman's rank correlation: replace each list by its ranks, giving tied values the average of the ranks they span, and return the Pearson correlation of the two rank vectors.

Examples

Input x = [1, 2, 3, 4], y = [10, 20, 30, 40]

Output 1

Perfectly monotone: 1.

Input x = [1, 2, 3, 4], y = [1, 8, 27, 1000]

Output 1

Pearson is below 1 here; Spearman ignores the scale and gives 1.

Input x = [1, 2, 2, 3], y = [4, 3, 3, 1]

Output -1

Ties share the average rank 2.5. Perfectly reversed: −1.

Constraints

  • 2 ≤ n ≤ 10⁵
  • Neither list is constant
  • Checked to a relative tolerance of 10⁻⁹

Hints

Hint 1

Write one function that ranks a list, and call it on both inputs.

Hint 2

Sort once; a block of equal values occupying sorted positions i..j all get rank (i + j)/2 + 1.

Hint 3

Centre both rank vectors, then r = Σ(ab)/√(Σa² · Σb²).

Where candidates go wrong

  • Using 1 − 6Σd²/(n(n² − 1)). It is exact only without ties, and the third example has them.
  • Ranking with argsort(argsort(·)), which gives tied values distinct ranks.
  • Computing Pearson on the raw values.
Console⌘/Ctrl + Enter runs

Python runs in your browser with NumPy. The first run downloads the runtime, which takes a few seconds.


Why interviewers ask it

In systematic trading, a signal is judged by its information coefficient, the rank correlation between its value today and returns tomorrow. Quant research interviews ask for it because it tests ranking with ties and the difference between Pearson and Spearman in one short function.

The theory behind it is in the lesson Statistics coding questions: variance, AUC and rank correlation.


Keep going