Module 10 · Financial Time-Series Foundations Lesson 94 of 120

Rolling and Expanding Windows

Choosing how much history a monitoring statistic remembers.

2:26 clip5:03:51–5:06:18 in the full courseWatch on YouTube

Transcript

20 sentences · select one to jump there

Check your understanding

Why is the final rolling mean six while the expanding mean is five?

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.

094-rolling-and-expanding-windows.ts
Start from GitHub
/**
 * Fintech Math Bootcamp · Lesson 094 of 120
 * Rolling and Expanding Windows
 * Module 10: Financial Time-Series Foundations
 *
 * Scenario: Choosing how much history a monitoring statistic remembers
 * Rule:     rolling: last w observations; expanding: all observations so far
 *
 * Try it:   Why is the final rolling mean six while the expanding mean is five?
 *
 * Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/financial-time-series-foundations/rolling-and-expanding-windows/
 * Free course:    https://courses.thefintechbuilder.com
 * Synthetic teaching example, not financial advice or a production library.
 */

export function lesson094() {
  const x=[2,4,6,8],w=3;
  const avg=(a:number[])=>a.reduce((s,v)=>s+v,0)/a.length;
  const rolling=x.map((_,i)=>i+1<w?null:avg(x.slice(i-w+1,i+1)));
  const expanding=x.map((_,i)=>avg(x.slice(0,i+1)));
  const result={rolling,expanding};
  return result;
}

export const checkedResult = {"rolling":[null,null,4,6],"expanding":[2,3,4,5]};

// Run this file directly: npx tsx lessons/10-financial-time-series-foundations/094-rolling-and-expanding-windows.ts
if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop()!)) {
  console.log(JSON.stringify(lesson094(), null, 2));
}

Your output

Press Run to execute the code in your browser.

Expected output

{
  "rolling": [
    null,
    null,
    4,
    6
  ],
  "expanding": [
    2,
    3,
    4,
    5
  ]
}

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

Lesson notes

The rule

rolling: last w observations; expanding: all observations so far