Module 12 · Statistical Computing and Reproducibility Lesson 114 of 120

Batch, Rolling, and Streaming Statistic Equivalence

Making different execution styles compute the same statistic.

2:41 clip6:09:21–6:12:03 in the full courseWatch on YouTube

Transcript

17 sentences · select one to jump there

Check your understanding

Should the final rolling mean equal the full-history mean here?

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.

114-batch-rolling-and-streaming-statistic-equivalence.ts
Start from GitHub
/**
 * Fintech Math Bootcamp · Lesson 114 of 120
 * Batch, Rolling, and Streaming Statistic Equivalence
 * Module 12: Statistical Computing and Reproducibility
 *
 * Scenario: Making different execution styles compute the same statistic
 * Rule:     equivalence requires the same observations, policy, and convention
 *
 * Try it:   Should the final rolling mean equal the full-history mean here?
 *
 * Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/statistical-computing-and-reproducibility/batch-rolling-and-streaming-statistic-equivalence/
 * Free course:    https://courses.thefintechbuilder.com
 * Synthetic teaching example, not financial advice or a production library.
 */

export function lesson114() {
  const values=[1,2,3,4,5],w=3;
  let sum=0;const queue:number[]=[];const rolling:(number|null)[]=[];
  for(const x of values){queue.push(x);sum+=x;
    if(queue.length>w) sum-=queue.shift()!;
    rolling.push(queue.length===w?sum/w:null);}
  const batchTail=values.slice(-w).reduce((s,x)=>s+x,0)/w;
  const result={rolling,batchTail,streamTail:rolling.at(-1)!};
  return result;
}

export const checkedResult = {"rolling":[null,null,2,3,4],"batchTail":4,"streamTail":4};

// Run this file directly: npx tsx lessons/12-statistical-computing-and-reproducibility/114-batch-rolling-and-streaming-statistic-equivalence.ts
if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop()!)) {
  console.log(JSON.stringify(lesson114(), null, 2));
}

Your output

Press Run to execute the code in your browser.

Expected output

{
  "rolling": [
    null,
    null,
    2,
    3,
    4
  ],
  "batchTail": 4,
  "streamTail": 4
}

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

Lesson notes

The rule

equivalence requires the same observations, policy, and convention