Module 9 · Dependence, Regression, and Model Foundations Lesson 84 of 120

Spearman Rank Correlation and Kendall Tau

Comparing monotone rankings and pair ordering.

2:40 clip4:30:42–4:33:23 in the full courseWatch on YouTube

Transcript

18 sentences · select one to jump there

Check your understanding

Is the Kendall convention in this course tau-b?

Choose one answer

Code lab

Run it yourself

The lesson source in 7 languages. Edit it, run TypeScript and Python right here, and compare with the expected output.

084-spearman-rank-correlation-and-kendall-tau.ts
Start from GitHub
/**
 * Fintech Math Bootcamp · Lesson 084 of 120
 * Spearman Rank Correlation and Kendall Tau
 * Module 09: Dependence, Regression, and Model Foundations
 *
 * Scenario: Comparing monotone rankings and pair ordering
 * Rule:     Spearman = Pearson(ranks); Kendall tau-a=(C−D)/choose(n,2)
 *
 * Try it:   Is the Kendall convention in this course tau-b?
 *
 * Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/dependence-regression-and-model-foundations/spearman-rank-correlation-and-kendall-tau/
 * Free course:    https://courses.thefintechbuilder.com
 * Synthetic teaching example, not financial advice or a production library.
 */

export function lesson084() {
  const x=[1,2,3,4,5], y=[2,4,5,4,5];
  const ranks=(a:number[])=>a.map(v=>1+a.filter(z=>z<v).length+(a.filter(z=>z===v).length-1)/2);
  const n=x.length, rx=ranks(x), ry=ranks(y), m=(n+1)/2; // mean rank
  const cross=rx.reduce((s,v,i)=>s+(v-m)*(ry[i]-m),0);
  const ss=(a:number[])=>a.reduce((s,v)=>s+(v-m)**2,0);
  let signedPairs=0;
  for(let i=0;i<n;i++) for(let j=i+1;j<n;j++)
    signedPairs+=Math.sign((x[j]-x[i])*(y[j]-y[i]));
  const result={rx,ry,spearman:cross/Math.sqrt(ss(rx)*ss(ry)),tauA:signedPairs/(n*(n-1)/2)};
  return result;
}

export const checkedResult = {"rx":[1,2,3,4,5],"ry":[1,2.5,4.5,2.5,4.5],"spearman":0.7378647873726218,"tauA":0.6};

// Run this file directly: npx tsx lessons/09-dependence-regression-and-model-foundations/084-spearman-rank-correlation-and-kendall-tau.ts
if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop()!)) {
  console.log(JSON.stringify(lesson084(), null, 2));
}

Your output

Press Run to execute the code in your browser.

Expected output

{
  "rx": [
    1,
    2,
    3,
    4,
    5
  ],
  "ry": [
    1,
    2.5,
    4.5,
    2.5,
    4.5
  ],
  "spearman": 0.7378647873726218,
  "tauA": 0.6
}

Prefer your own machine? Every file is in the course repository · open it in Codespaces.

Lesson notes

The rule

Spearman = Pearson(ranks); Kendall tau-a=(C−D)/choose(n,2)