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

R-Squared and Adjusted R-Squared

Comparing a regression with a mean-only baseline.

2:33 clip4:43:47–4:46:20 in the full courseWatch on YouTube

Transcript

18 sentences · select one to jump there

Check your understanding

Can out-of-sample R² be negative?

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.

089-r-squared-and-adjusted-r-squared.ts
Start from GitHub
/**
 * Fintech Math Bootcamp · Lesson 089 of 120
 * R-Squared and Adjusted R-Squared
 * Module 09: Dependence, Regression, and Model Foundations
 *
 * Scenario: Comparing a regression with a mean-only baseline
 * Rule:     R²=1−SSE/SST; adjusted R²=1−(1−R²)(n−1)/(n−p−1)
 *
 * Try it:   Can out-of-sample R² be negative?
 *
 * Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/dependence-regression-and-model-foundations/r-squared-and-adjusted-r-squared/
 * Free course:    https://courses.thefintechbuilder.com
 * Synthetic teaching example, not financial advice or a production library.
 */

export function lesson089() {
  const sse=2.4,sst:number=6,n=5,p=1;
  if(sst===0) throw new Error("R-squared undefined: constant target");
  if(n-p-1<=0) throw new Error("Adjusted R-squared needs n > p+1");
  const r2=1-sse/sst;
  const adjusted=1-(1-r2)*(n-1)/(n-p-1);
  const result={r2,adjusted};
  return result;
}

export const checkedResult = {"r2":0.6000000000000001,"adjusted":0.4666666666666668};

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

Your output

Press Run to execute the code in your browser.

Expected output

{
  "r2": 0.6000000000000001,
  "adjusted": 0.4666666666666668
}

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

Lesson notes

The rule

R²=1−SSE/SST; adjusted R²=1−(1−R²)(n−1)/(n−p−1)