Module 7 · Probability Distributions and Simulation Basics Lesson 67 of 120
Student-t Distribution and Heavy Tails
Allowing heavier tails without assuming all moments exist.
Transcript
19 sentences · select one to jump thereCheck your understanding
Can a finite sample SD prove a t population has finite variance?
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 067 of 120
* Student-t Distribution and Heavy Tails
* Module 07: Probability Distributions and Simulation Basics
*
* Scenario: Allowing heavier tails without assuming all moments exist
* Rule: standard t variance = ν/(ν−2), only for ν>2
*
* Try it: Can a finite sample SD prove a t population has finite variance?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/probability-distributions-and-simulation-basics/student-t-distribution-and-heavy-tails/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*/
export function lesson067() {
const variance=(nu:number):number|null => nu>2 ? nu/(nu-2) : null;
const result={df3:variance(3),df5:variance(5),df2:variance(2),
meanExistsAt1:1>1};
return result;
}
export const checkedResult = {"df3":3,"df5":1.6666666666666667,"df2":null,"meanExistsAt1":false};
// Run this file directly: npx tsx lessons/07-probability-distributions-and-simulation-basics/067-student-t-distribution-and-heavy-tails.ts
if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop()!)) {
console.log(JSON.stringify(lesson067(), null, 2));
}
Your output
Press Run to execute the code in your browser.
Expected output
{
"df3": 3,
"df5": 1.6666666666666667,
"df2": null,
"meanExistsAt1": false
}"""
Fintech Math Bootcamp · Lesson 067 of 120
Student-t Distribution and Heavy Tails
Module 07: Probability Distributions and Simulation Basics
Scenario: Allowing heavier tails without assuming all moments exist
Rule: standard t variance = ν/(ν−2), only for ν>2
Try it: Can a finite sample SD prove a t population has finite variance?
Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/probability-distributions-and-simulation-basics/student-t-distribution-and-heavy-tails/
Free course: https://courses.thefintechbuilder.com
Synthetic teaching example, not financial advice or a production library.
"""
import json
def variance(nu):
"""Variance of a standard Student-t, defined only for nu > 2."""
return nu / (nu - 2) if nu > 2 else None
def mean_exists(nu):
"""A Student-t mean exists only for nu > 1."""
return nu > 1
def lesson_067():
return {
"df3": variance(3),
"df5": variance(5),
"df2": variance(2),
"meanExistsAt1": mean_exists(1),
}
if __name__ == "__main__":
print(json.dumps(lesson_067(), indent=2))
Your output
Press Run to execute the code in your browser.
Expected output
{
"df3": 3,
"df5": 1.6666666666666667,
"df2": null,
"meanExistsAt1": false
}// Fintech Math Bootcamp - Lesson 067 of 120
// Student-t Distribution and Heavy Tails
// Module 07: Probability Distributions and Simulation Basics
//
// Scenario: Allowing heavier tails without assuming all moments exist
// Rule: standard t variance = nu/(nu-2), only for nu>2
//
// Try it: Can a finite sample SD prove a t population has finite variance?
//
// Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/probability-distributions-and-simulation-basics/student-t-distribution-and-heavy-tails/
// 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 {
// Variance of a standard Student-t; null when nu <= 2 because it does not exist.
static Double variance(double nu) {
return nu > 2 ? Double.valueOf(nu / (nu - 2)) : null;
}
// A Student-t mean exists only for nu > 1.
static boolean meanExists(double nu) {
return nu > 1;
}
static Map<String, Object> lesson067() {
Map<String, Object> result = new LinkedHashMap<String, Object>();
result.put("df3", variance(3));
result.put("df5", variance(5));
result.put("df2", variance(2));
result.put("meanExistsAt1", meanExists(1));
return result;
}
public static void main(String[] args) {
System.out.println(toJson(lesson067(), ""));
}
// 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
{
"df3": 3,
"df5": 1.6666666666666667,
"df2": null,
"meanExistsAt1": false
}// Fintech Math Bootcamp · Lesson 067 of 120
// Student-t Distribution and Heavy Tails
// Module 07: Probability Distributions and Simulation Basics
//
// Scenario: Allowing heavier tails without assuming all moments exist
// Rule: standard t variance = ν/(ν−2), only for ν>2
//
// Try it: Can a finite sample SD prove a t population has finite variance?
//
// Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/probability-distributions-and-simulation-basics/student-t-distribution-and-heavy-tails/
// Free course: https://courses.thefintechbuilder.com
// Synthetic teaching example, not financial advice or a production library.
package main
import (
"encoding/json"
"fmt"
)
type Lesson067Result struct {
Df3 *float64 `json:"df3"`
Df5 *float64 `json:"df5"`
Df2 *float64 `json:"df2"`
MeanExistsAt1 bool `json:"meanExistsAt1"`
}
// variance of a standard Student-t; nil when nu <= 2 because it does not exist.
func variance(nu float64) *float64 {
if nu > 2 {
v := nu / (nu - 2)
return &v
}
return nil
}
// meanExists reports whether a Student-t mean exists: only for nu > 1.
func meanExists(nu float64) bool {
return nu > 1
}
func lesson067() Lesson067Result {
return Lesson067Result{
Df3: variance(3),
Df5: variance(5),
Df2: variance(2),
MeanExistsAt1: meanExists(1),
}
}
func main() {
out, err := json.MarshalIndent(lesson067(), "", " ")
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
{
"df3": 3,
"df5": 1.6666666666666667,
"df2": null,
"meanExistsAt1": false
}// Fintech Math Bootcamp · Lesson 067 of 120
// Student-t Distribution and Heavy Tails
// Module 07: Probability Distributions and Simulation Basics
//
// Scenario: Allowing heavier tails without assuming all moments exist
// Rule: standard t variance = ν/(ν−2), only for ν>2
//
// Try it: Can a finite sample SD prove a t population has finite variance?
//
// Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/probability-distributions-and-simulation-basics/student-t-distribution-and-heavy-tails/
// 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 ? "}" : "]");
}
// Variance of a standard Student-t; empty when nu <= 2 because it does not exist.
std::optional<double> variance(double nu) {
if (nu > 2) return nu / (nu - 2);
return std::nullopt;
}
// A Student-t mean exists only for nu > 1.
bool meanExists(double nu) { return nu > 1; }
Json optionalNumber(const std::optional<double>& value) {
return value ? Json(*value) : Json();
}
Json lesson067() {
return jsonObject({
{"df3", optionalNumber(variance(3))},
{"df5", optionalNumber(variance(5))},
{"df2", optionalNumber(variance(2))},
{"meanExistsAt1", meanExists(1)},
});
}
int main() {
std::cout << toJson(lesson067()) << '\n';
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
{
"df3": 3,
"df5": 1.6666666666666667,
"df2": null,
"meanExistsAt1": false
}// Fintech Math Bootcamp · Lesson 067 of 120
// Student-t Distribution and Heavy Tails
// Module 07: Probability Distributions and Simulation Basics
//
// Scenario: Allowing heavier tails without assuming all moments exist
// Rule: standard t variance = ν/(ν−2), only for ν>2
//
// Try it: Can a finite sample SD prove a t population has finite variance?
//
// Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/probability-distributions-and-simulation-basics/student-t-distribution-and-heavy-tails/
// 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
}
/// Variance of a standard Student-t; None when nu <= 2 because it does not exist.
fn variance(nu: f64) -> Option<f64> {
if nu > 2.0 {
Some(nu / (nu - 2.0))
} else {
None
}
}
/// A Student-t mean exists only for nu > 1.
fn mean_exists(nu: f64) -> bool {
nu > 1.0
}
fn optional_number(value: Option<f64>) -> Json {
value.map_or(Json::Null, Json::Num)
}
fn lesson_067() -> Json {
Json::obj(vec![
("df3", optional_number(variance(3.0))),
("df5", optional_number(variance(5.0))),
("df2", optional_number(variance(2.0))),
("meanExistsAt1", Json::Bool(mean_exists(1.0))),
])
}
fn main() {
println!("{}", lesson_067().pretty(""));
}
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
{
"df3": 3,
"df5": 1.6666666666666667,
"df2": null,
"meanExistsAt1": false
}// Fintech Math Bootcamp · Lesson 067 of 120
// Student-t Distribution and Heavy Tails
// Module 07: Probability Distributions and Simulation Basics
//
// Scenario: Allowing heavier tails without assuming all moments exist
// Rule: standard t variance = ν/(ν−2), only for ν>2
//
// Try it: Can a finite sample SD prove a t population has finite variance?
//
// Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/probability-distributions-and-simulation-basics/student-t-distribution-and-heavy-tails/
// 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(Lesson067(), options));
// Variance of a standard Student-t; null when nu <= 2 because it does not exist.
static double? Variance(double nu) => nu > 2 ? nu / (nu - 2) : null;
// A Student-t mean exists only for nu > 1.
static bool MeanExists(double nu) => nu > 1;
static object Lesson067()
{
return new
{
df3 = Variance(3),
df5 = Variance(5),
df2 = Variance(2),
meanExistsAt1 = MeanExists(1),
};
}
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
{
"df3": 3,
"df5": 1.6666666666666667,
"df2": null,
"meanExistsAt1": false
}Prefer your own machine? Every file is in the course repository · open it in Codespaces.
Lesson notes
The rule
standard t variance = ν/(ν−2), only for ν>2