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

Sample Covariance Calculation and Interpretation

Constructing a covariance rather than trusting a matrix cell.

2:27 clip4:25:41–4:28:08 in the full courseWatch on YouTube

Transcript

19 sentences · select one to jump there

Check your understanding

Why is covariance sensitive to the units of x?

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.

082-sample-covariance-calculation-and-interpretation.ts
Start from GitHub
/**
 * Fintech Math Bootcamp · Lesson 082 of 120
 * Sample Covariance Calculation and Interpretation
 * Module 09: Dependence, Regression, and Model Foundations
 *
 * Scenario: Constructing a covariance rather than trusting a matrix cell
 * Rule:     sample covariance = Σ(x−x̄)(y−ȳ)/(n−1)
 *
 * Try it:   Why is covariance sensitive to the units of x?
 *
 * Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/dependence-regression-and-model-foundations/sample-covariance-calculation-and-interpretation/
 * Free course:    https://courses.thefintechbuilder.com
 * Synthetic teaching example, not financial advice or a production library.
 */

export function lesson082() {
  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 mx=avg(x),my=avg(y);
  const products=x.map((v,i)=>(v-mx)*(y[i]-my));
  const result={products,covariance:products.reduce((s,v)=>s+v,0)/(x.length-1)};
  return result;
}

export const checkedResult = {"products":[4,0,0,0,2],"covariance":1.5};

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

Your output

Press Run to execute the code in your browser.

Expected output

{
  "products": [
    4,
    0,
    0,
    0,
    2
  ],
  "covariance": 1.5
}

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

Lesson notes

The rule

sample covariance = Σ(x−x̄)(y−ȳ)/(n−1)