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

Simple Ordinary Least Squares Regression

Fitting a line to paired operational measurements.

2:36 clip4:35:58–4:38:35 in the full courseWatch on YouTube

Transcript

19 sentences · select one to jump there

Check your understanding

Which distances does ordinary y-on-x OLS square?

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.

086-simple-ordinary-least-squares-regression.ts
Start from GitHub
/**
 * Fintech Math Bootcamp · Lesson 086 of 120
 * Simple Ordinary Least Squares Regression
 * Module 09: Dependence, Regression, and Model Foundations
 *
 * Scenario: Fitting a line to paired operational measurements
 * Rule:     b₁=Sxy/Sxx; b₀=ȳ−b₁x̄
 *
 * Try it:   Which distances does ordinary y-on-x OLS square?
 *
 * Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/dependence-regression-and-model-foundations/simple-ordinary-least-squares-regression/
 * Free course:    https://courses.thefintechbuilder.com
 * Synthetic teaching example, not financial advice or a production library.
 */

export function lesson086() {
  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 sxx=x.reduce((s,v)=>s+(v-mx)**2,0);
  if(sxx===0) throw new Error("Slope undefined: no spread in x");
  const sxy=x.reduce((s,v,i)=>s+(v-mx)*(y[i]-my),0);
  const slope=sxy/sxx,intercept=my-slope*mx;
  const result={slope,intercept,predictions:x.map(v=>intercept+slope*v)};
  return result;
}

export const checkedResult = {"slope":0.6,"intercept":2.2,"predictions":[2.8000000000000003,3.4000000000000004,4,4.6,5.2]};

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

Your output

Press Run to execute the code in your browser.

Expected output

{
  "slope": 0.6,
  "intercept": 2.2,
  "predictions": [
    2.8000000000000003,
    3.4000000000000004,
    4,
    4.6,
    5.2
  ]
}

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

Lesson notes

The rule

b₁=Sxy/Sxx; b₀=ȳ−b₁x̄