Module 9 · Dependence, Regression, and Model Foundations Lesson 86 of 120
Simple Ordinary Least Squares Regression
Fitting a line to paired operational measurements.
Transcript
19 sentences · select one to jump thereCheck your understanding
Which distances does ordinary y-on-x OLS square?
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.
/**
* 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
]
}"""
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.
"""
import json
def average(values):
total = 0
for v in values:
total += v
return total / len(values)
def lesson_086():
x, y = [1, 2, 3, 4, 5], [2, 4, 5, 4, 5]
mx, my = average(x), average(y)
sxx = 0
for v in x:
sxx += (v - mx) ** 2
if sxx == 0:
raise ValueError("Slope undefined: no spread in x")
sxy = 0
for xi, yi in zip(x, y):
sxy += (xi - mx) * (yi - my)
slope = sxy / sxx
intercept = my - slope * mx
return {
"slope": slope,
"intercept": intercept,
"predictions": [intercept + slope * v for v in x],
}
if __name__ == "__main__":
print(json.dumps(lesson_086(), indent=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
]
}// 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: b1=Sxy/Sxx; b0=ybar-b1*xbar
//
// 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.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Main {
static double average(double[] values) {
double total = 0;
for (double v : values) total += v;
return total / values.length;
}
static Map<String, Object> lesson086() {
double[] x = {1, 2, 3, 4, 5}, y = {2, 4, 5, 4, 5};
double mx = average(x), my = average(y);
double sxx = 0;
for (double v : x) sxx += Math.pow(v - mx, 2);
if (sxx == 0) throw new ArithmeticException("Slope undefined: no spread in x");
double sxy = 0;
for (int i = 0; i < x.length; i++) sxy += (x[i] - mx) * (y[i] - my);
double slope = sxy / sxx, intercept = my - slope * mx;
double[] predictions = new double[x.length];
for (int i = 0; i < x.length; i++) predictions[i] = intercept + slope * x[i];
Map<String, Object> result = new LinkedHashMap<String, Object>();
result.put("slope", slope);
result.put("intercept", intercept);
result.put("predictions", predictions);
return result;
}
public static void main(String[] args) {
System.out.println(toJson(lesson086(), ""));
}
// Minimal JSON writer: two-space indent, whole numbers without a decimal point, NaN as null.
static String toJson(Object value, String indent) {
if (value == null) return "null";
if (value instanceof Boolean) return value.toString();
if (value instanceof Number) return formatNumber(((Number) value).doubleValue());
if (value instanceof String) return quote((String) value);
if (value instanceof double[]) {
List<Object> boxed = new ArrayList<Object>();
for (double d : (double[]) value) boxed.add(d);
return toJson(boxed, indent);
}
if (value instanceof Object[]) return toJson(Arrays.asList((Object[]) value), indent);
String inner = indent + " ";
StringBuilder out = new StringBuilder();
if (value instanceof Map) {
Map<?, ?> map = (Map<?, ?>) value;
if (map.isEmpty()) return "{}";
out.append("{\n");
int i = 0;
for (Map.Entry<?, ?> entry : map.entrySet()) {
out.append(inner).append(quote(entry.getKey().toString())).append(": ")
.append(toJson(entry.getValue(), inner));
out.append(++i < map.size() ? ",\n" : "\n");
}
return out.append(indent).append("}").toString();
}
List<?> list = (List<?>) value;
if (list.isEmpty()) return "[]";
out.append("[\n");
for (int i = 0; i < list.size(); i++) {
out.append(inner).append(toJson(list.get(i), inner));
out.append(i + 1 < list.size() ? ",\n" : "\n");
}
return out.append(indent).append("]").toString();
}
static String formatNumber(double x) {
if (Double.isNaN(x) || Double.isInfinite(x)) return "null";
if (x == Math.rint(x) && Math.abs(x) < 1e15) return Long.toString((long) x);
return Double.toString(x);
}
static String quote(String s) {
StringBuilder out = new StringBuilder("\"");
for (char c : s.toCharArray()) {
if (c == '"' || c == '\\') out.append('\\').append(c);
else if (c == '\n') out.append("\\n");
else if (c < 0x20) out.append(String.format("\\u%04x", (int) c));
else out.append(c);
}
return out.append('"').toString();
}
}
No browser runner for Java yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"slope": 0.6,
"intercept": 2.2,
"predictions": [
2.8000000000000003,
3.4000000000000004,
4,
4.6,
5.2
]
}// 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.
package main
import (
"encoding/json"
"errors"
"fmt"
"math"
"os"
)
type Lesson086Result struct {
Slope float64 `json:"slope"`
Intercept float64 `json:"intercept"`
Predictions []float64 `json:"predictions"`
}
func average(values []float64) float64 {
total := 0.0
for _, v := range values {
total += v
}
return total / float64(len(values))
}
func lesson086() (Lesson086Result, error) {
x := []float64{1, 2, 3, 4, 5}
y := []float64{2, 4, 5, 4, 5}
mx, my := average(x), average(y)
sxx := 0.0
for _, v := range x {
sxx += math.Pow(v-mx, 2)
}
if sxx == 0 {
return Lesson086Result{}, errors.New("slope undefined: no spread in x")
}
sxy := 0.0
for i, v := range x {
sxy += (v - mx) * (y[i] - my)
}
slope := sxy / sxx
intercept := my - slope*mx
predictions := make([]float64, len(x))
for i, v := range x {
predictions[i] = intercept + slope*v
}
return Lesson086Result{Slope: slope, Intercept: intercept, Predictions: predictions}, nil
}
func main() {
result, err := lesson086()
if err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
out, err := json.MarshalIndent(result, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(out))
}
No browser runner for Go yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"slope": 0.6,
"intercept": 2.2,
"predictions": [
2.8000000000000003,
3.4000000000000004,
4,
4.6,
5.2
]
}// 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.
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <optional>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
// A minimal JSON value, enough to print this lesson's result.
struct Json {
enum class Kind { Null, Bool, Number, String, Array, Object };
Kind kind = Kind::Null;
bool flag = false;
double number = 0.0;
std::string text;
std::vector<std::string> keys; // object keys, parallel to items
std::vector<Json> items; // array elements or object values
Json() = default;
Json(bool value) : kind(Kind::Bool), flag(value) {}
Json(int value) : kind(Kind::Number), number(value) {}
Json(double value) : kind(Kind::Number), number(value) {}
Json(const char* value) : kind(Kind::String), text(value) {}
Json(const std::string& value) : kind(Kind::String), text(value) {}
Json(const std::vector<double>& values) : kind(Kind::Array) {
for (double v : values) items.push_back(Json(v));
}
};
Json jsonArray(const std::vector<Json>& values) {
Json array;
array.kind = Json::Kind::Array;
array.items = values;
return array;
}
Json jsonObject(const std::vector<std::pair<std::string, Json>>& fields) {
Json object;
object.kind = Json::Kind::Object;
for (const auto& field : fields) {
object.keys.push_back(field.first);
object.items.push_back(field.second);
}
return object;
}
// Shortest decimal form that reads back as the same double.
std::string formatNumber(double x) {
if (!std::isfinite(x)) return "null";
char buffer[32];
if (x == std::floor(x) && std::fabs(x) < 1e15) {
std::snprintf(buffer, sizeof buffer, "%.0f", x);
return buffer;
}
for (int precision = 1; precision <= 17; ++precision) {
std::snprintf(buffer, sizeof buffer, "%.*g", precision, x);
if (std::strtod(buffer, nullptr) == x) break;
}
return buffer;
}
std::string quote(const std::string& s) {
std::string out = "\"";
for (char c : s) {
if (c == '"' || c == '\\') { out += '\\'; out += c; }
else if (c == '\n') out += "\\n";
else out += c;
}
return out + "\"";
}
std::string toJson(const Json& value, const std::string& indent = "") {
switch (value.kind) {
case Json::Kind::Null: return "null";
case Json::Kind::Bool: return value.flag ? "true" : "false";
case Json::Kind::Number: return formatNumber(value.number);
case Json::Kind::String: return quote(value.text);
default: break;
}
const bool isObject = value.kind == Json::Kind::Object;
if (value.items.empty()) return isObject ? "{}" : "[]";
const std::string inner = indent + " ";
std::string out = isObject ? "{\n" : "[\n";
for (std::size_t i = 0; i < value.items.size(); ++i) {
out += inner;
if (isObject) out += quote(value.keys[i]) + ": ";
out += toJson(value.items[i], inner);
out += i + 1 < value.items.size() ? ",\n" : "\n";
}
return out + indent + (isObject ? "}" : "]");
}
double average(const std::vector<double>& values) {
double total = 0.0;
for (double v : values) total += v;
return total / values.size();
}
Json lesson086() {
const std::vector<double> x = {1, 2, 3, 4, 5}, y = {2, 4, 5, 4, 5};
const double mx = average(x), my = average(y);
double sxx = 0.0;
for (double v : x) sxx += std::pow(v - mx, 2);
if (sxx == 0) throw std::domain_error("Slope undefined: no spread in x");
double sxy = 0.0;
for (std::size_t i = 0; i < x.size(); ++i) sxy += (x[i] - mx) * (y[i] - my);
const double slope = sxy / sxx, intercept = my - slope * mx;
std::vector<double> predictions;
for (double v : x) predictions.push_back(intercept + slope * v);
return jsonObject({
{"slope", slope},
{"intercept", intercept},
{"predictions", predictions},
});
}
int main() {
try {
std::cout << toJson(lesson086()) << '\n';
} catch (const std::exception& error) {
std::cerr << "Error: " << error.what() << '\n';
return 1;
}
return 0;
}
No browser runner for C++ yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"slope": 0.6,
"intercept": 2.2,
"predictions": [
2.8000000000000003,
3.4000000000000004,
4,
4.6,
5.2
]
}// 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.
/// A minimal JSON value, enough to print this lesson's result.
#[allow(dead_code)]
enum Json {
Null,
Bool(bool),
Num(f64),
Str(String),
Arr(Vec<Json>),
Obj(Vec<(String, Json)>),
}
#[allow(dead_code)]
impl Json {
fn obj(fields: Vec<(&str, Json)>) -> Json {
Json::Obj(fields.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
}
fn nums(values: &[f64]) -> Json {
Json::Arr(values.iter().map(|&v| Json::Num(v)).collect())
}
/// Pretty-prints with two-space indentation.
fn pretty(&self, indent: &str) -> String {
let inner = format!("{} ", indent);
match self {
Json::Null => "null".to_string(),
Json::Bool(b) => b.to_string(),
Json::Num(x) => format_number(*x),
Json::Str(s) => quote(s),
Json::Arr(items) if items.is_empty() => "[]".to_string(),
Json::Obj(fields) if fields.is_empty() => "{}".to_string(),
Json::Arr(items) => {
let body: Vec<String> = items
.iter()
.map(|v| format!("{}{}", inner, v.pretty(&inner)))
.collect();
format!("[\n{}\n{}]", body.join(",\n"), indent)
}
Json::Obj(fields) => {
let body: Vec<String> = fields
.iter()
.map(|(k, v)| format!("{}{}: {}", inner, quote(k), v.pretty(&inner)))
.collect();
format!("{{\n{}\n{}}}", body.join(",\n"), indent)
}
}
}
}
fn format_number(x: f64) -> String {
if !x.is_finite() {
"null".to_string()
} else if x == x.trunc() && x.abs() < 1e15 {
format!("{}", x as i64)
} else {
format!("{}", x)
}
}
fn quote(s: &str) -> String {
let mut out = String::from("\"");
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
c => out.push(c),
}
}
out.push('"');
out
}
fn average(values: &[f64]) -> f64 {
values.iter().fold(0.0_f64, |s, v| s + v) / values.len() as f64
}
fn lesson_086() -> Result<Json, String> {
let x = [1.0_f64, 2.0, 3.0, 4.0, 5.0];
let y = [2.0_f64, 4.0, 5.0, 4.0, 5.0];
let (mx, my) = (average(&x), average(&y));
let sxx = x.iter().fold(0.0_f64, |s, v| s + (v - mx).powf(2.0));
if sxx == 0.0 {
return Err("Slope undefined: no spread in x".to_string());
}
let sxy = x
.iter()
.zip(y.iter())
.fold(0.0_f64, |s, (xi, yi)| s + (xi - mx) * (yi - my));
let slope = sxy / sxx;
let intercept = my - slope * mx;
let predictions: Vec<f64> = x.iter().map(|v| intercept + slope * v).collect();
Ok(Json::obj(vec![
("slope", Json::Num(slope)),
("intercept", Json::Num(intercept)),
("predictions", Json::nums(&predictions)),
]))
}
fn main() {
match lesson_086() {
Ok(result) => println!("{}", result.pretty("")),
Err(message) => {
eprintln!("Error: {}", message);
std::process::exit(1);
}
}
}
No browser runner for Rust yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"slope": 0.6,
"intercept": 2.2,
"predictions": [
2.8000000000000003,
3.4000000000000004,
4,
4.6,
5.2
]
}// 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
var options = new JsonSerializerOptions { WriteIndented = true };
Console.WriteLine(JsonSerializer.Serialize(Lesson086(), options));
static double Average(double[] values) => values.Aggregate(0.0, (s, v) => s + v) / values.Length;
static object Lesson086()
{
double[] x = { 1, 2, 3, 4, 5 }, y = { 2, 4, 5, 4, 5 };
double mx = Average(x), my = Average(y);
double sxx = x.Aggregate(0.0, (s, v) => s + Math.Pow(v - mx, 2));
if (sxx == 0) throw new InvalidOperationException("Slope undefined: no spread in x");
double sxy = x.Select((v, i) => (v - mx) * (y[i] - my)).Aggregate(0.0, (s, p) => s + p);
double slope = sxy / sxx, intercept = my - slope * mx;
return new
{
slope,
intercept,
predictions = x.Select(v => intercept + slope * v).ToArray(),
};
}
No browser runner for C# yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
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̄