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

Pearson Correlation Calculation and Interpretation

Normalizing linear association without claiming independence.

2:33 clip4:28:08–4:30:42 in the full courseWatch on YouTube

Transcript

17 sentences · select one to jump there

Check your understanding

What should happen when one input is constant?

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.

083-pearson-correlation-calculation-and-interpretation.ts
Start from GitHub
/**
 * Fintech Math Bootcamp · Lesson 083 of 120
 * Pearson Correlation Calculation and Interpretation
 * Module 09: Dependence, Regression, and Model Foundations
 *
 * Scenario: Normalizing linear association without claiming independence
 * Rule:     Pearson r = Sxy / √(Sxx Syy)
 *
 * Try it:   What should happen when one input is constant?
 *
 * Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/dependence-regression-and-model-foundations/pearson-correlation-calculation-and-interpretation/
 * Free course:    https://courses.thefintechbuilder.com
 * Synthetic teaching example, not financial advice or a production library.
 */

export function lesson083() {
  const x=[1,2,3,4,5],y=[2,4,5,4,5];
  const avg=(a:number[])=>a.reduce((s,v)=>s+v,0)/a.length;
  const dx=x.map(v=>v-avg(x)),dy=y.map(v=>v-avg(y));
  const dot=(a:number[],b:number[])=>a.reduce((s,v,i)=>s+v*b[i],0);
  const sxx=dot(dx,dx),syy=dot(dy,dy);
  if(sxx===0||syy===0) throw new Error("Correlation undefined: zero variance");
  const result=dot(dx,dy)/Math.sqrt(sxx*syy);
  return result;
}

export const checkedResult = 0.7745966692414834;

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

Your output

Press Run to execute the code in your browser.

Expected output

0.7745966692414834

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

Lesson notes

The rule

Pearson r = Sxy / √(Sxx Syy)