This page initially started as notes for my students in Elementary Statistics, Spring 2022.
It now serves as a general probability & statistics
reference.
Probability
Probability Space
A Probability Space is a triple $(\Omega, \mathcal{F}, P)$ where
$\Omega$ is a sample space (a set of outcomes)
$\mathcal{F}$ is a sigma-algebra (a collection of subsets of $\Omega$)
$P$ is a probability measure (a function from $\mathcal{F}$ to $[0,1]$)
For events $E_1, E_2\in \mc{F}$, $E_1$ and $E_2$ are independent if
$$P(E_1\cap E_2)=P(E_1)P(E_2)$$
The
conditional probability $\mb{P}(E_1|E_2)$, is defined as
$$P(E_1|E_2)= \frac{P(E_1\cap E_2)}{P(E_2)}$$
assuming $E_2$ has non-zero probability.
If $$|\Omega|<\infty ,\quad \mathcal{F}=2^{\Omega}, \quad P(E)=\frac{|E|}{|\Omega|}$$ then $(\Omega,
\mathcal{F}, P)$ is a probability space.
Let $$\Omega=\{x_1x_2\cdots x_n :x_i\in \{0,1\} \},\quad\ \mc{F}=\sigma(\Omega)$$
$$ P(x_1x_2\cdots x_n)=p^j(1-p)^{n-j},\quad j = |\{x_i:x_i=1 \}|$$
then $(\Omega, \mathcal{F}, P)$ is a probability space.
Random Variables
A Random Variable is a measurable function
$$X: \Omega \to (R,\mc{R}) $$
where $(R,\mc{R})$ is a measurable space.
The probability that $X$ takes on a value in a measurable set $E\in \mc{R}$ is written
as
$$
\P{E}= P(X^{-1} E)
$$
If the range $R$ is countable, then $X$ is a discrete random variable
$$\P{E}=\sum_{x\in E} \P{X=x}$$
If $X$ has a density (below), then $X$ is a
continuous random variable.
The density of $X$ is a measurable function $f_X$ such that
$$\P{X \in E}=\int_{X^{-1} E} d P=\int_E f_X(x)\ d x$$
Standard normal density $\phi(z)$. The green band is the
probability between your bounds; the red tails are the rest.
$\mb{P}($ $< Z<$
$)\simeq$
If $$\Omega=\{1,2,\cdots,n\}^2,\quad\P{E}=\dfrac{|E|}{n^2} $$ $$
X(\omega)=\sum_{i=1}^2 \omega_i$$ then $X$ is a random variable.
$$\P{X\in (-\pi,\pi)} = \frac{|\{(1,1),(1,2),(2,1) \}|}{n^2}=\dfrac{3}{n^2}$$
Let $$\Omega=\{x_1x_2\cdots x_n :x_i\in \{0,1\} \},\quad\ \mc{F}=\sigma(\Omega)$$
$$ P(x_1x_2\cdots x_n)=p^j(1-p)^{n-j},\quad j = |\{x_i:x_i=1 \}|$$
$$
X(\omega)=\sum_{i=1}^n \omega_i$$ then $X$ is a random variable, known as binomial random
variable,
with
$$\P{X=k}=\left(\begin{array}{l}
n \\
k
\end{array}\right) p^k (1-p)^{n-k}, \qquad k\in\{0,1,\cdots,n\}$$
The probability density function
$$f(x)=\frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{(x-\mu)^2}{2\sigma^2}}, \qquad x\in \R$$
defines the Gaussian Random Variable with mean $\mu$ and variance $\sigma^2$.
Moments
The set of all random variables
$$
\{X :\Omega \to \R \}
$$ is a vector space under the trivial addition and scalar multiplication operations.
We can always enlarge $\Omega$ to accommodate new random variables.
Thus $\Omega$ is often omitted when talking about random variables.
Denote
$$
\ms{L}_2= \{ X:\Omega \to \R \mid \E[X^2]< \infty \} $$ then $\ms{L}_2$ is a Hilbert Space with the inner
product
$$
\langle X,Y \rangle = \E[XY]:= \iint_{\mathbb{R^2}} xy\ f_{X,Y}\ d x d y
$$
$$
\norm{X}^2=\langle X,X \rangle
$$
This also allows us to view probability problems geometrically.
The $k$-th moment of $X$ is defined as
$$\mu_k=\E[X^k]:= \int_\Omega X(\omega)^k P(d\omega)=\int_\R x^k \P{dx}= \int_{\mathbb{R}} x^k f_X d x$$
$\mu_1$ is the mean of $X$, will also be denoted as $\mu_X$.
$\mu_2 - \mu_1^2$ is the variance of $X$, will also be denoted as $\sigma_X^2$.
$\sigma_X$ is the standard deviation of $X$.
If $X\sim \operatorname{Bin}(n,p)$, with $q=1-p$, then $$\mb{E}(X)=np$$
$$\sigma^2(X)=npq$$
Let $X:\Omega\to \R^{\ge 0}$
$$\E[X]= \int_0^\infty \P{(X\ge x)}\ d x$$
More generally, for any $n\in \N$, $X:\Omega\to \R$
$$\E[|X|^n] = \int_0^\infty \P{(|X|^n\ge x)}\ d x$$
$$
\begin{aligned}
\E[X]&= \int_\Omega X \ dP \\
&= \int_\Omega\left(\int_0^\infty 1[X>y] \ dy\right) \ dP\\
&= \int_0^\infty \int_\Omega 1[X>y] \ d P \ dy\\
&= \int_0^\infty \P{(X\ge y)}\ d y
\end{aligned}
$$
Moments, Computed
The definitions above become estimates by the plug-in rule
(the method of moments): replace the expectation by a sample average,
$\hat\mu_k = \frac1n \sum_{i=1}^n x_i^k$, and the section's variance formula gets
hats, $\hat\sigma^2 = \hat\mu_2 - \hat\mu_1^2$. The demo runs the plug-in on three
distributions whose moments are known in closed form — the standard normal
($\mu = 0, 1, 0, 3$), the exponential ($\mu_k = k!$), and the uniform on $[0, 1]$
($\mu_k = 1/(k+1)$) — one seeded stream of $2{,}000$ draws each. The chart plots
the error $|\hat\mu_k - \mu_k|$ against $n$ on log-log axes. By the central limit
theorem applied to $X^k$ itself, every error decays at the same rate $1/\sqrt{n}$ —
but with constant $\sqrt{\mu_{2k} - \mu_k^2}/\sqrt{n}$, the standard deviation of
$X^k$: the rate is shared, the constants are not, and they grow
fast with $k$.
μ̂₁ errorμ̂₂ errorμ̂₃ errorμ̂₄ error2/√n (the rate)
The three streams grade the plug-in very differently. The uniform, bounded and
light-tailed, is essentially exact by $n = 2{,}000$: all four errors under
$0.002$. The normal is honest but slower at the top: $\hat\mu_4 = 2.826$ against
$3$, an error of $0.174$ — ten times $\hat\mu_1$'s $0.017$, at the same $1/\sqrt n$
rate. The exponential's fourth moment is the hard case: $\hat\mu_4 = 21.30$
against $24$ after $2{,}000$ draws, because the estimator's own standard error is
$\sqrt{\mu_8 - \mu_4^2}/\sqrt{n} \approx \sqrt{39{,}744}/\sqrt{n} \approx 4.5$ at
this $n$ — estimating a fourth moment is a second-moment problem about $X^4$,
whose scale is set by the eighth moment. That recursion is why the
geometry at the top of this section is built on the second moment alone: $L^2$ is
where estimation, not just definition, stays tame. One seeded stream per
distribution, as always — the constants are the theorem's, the exact errors
belong to these streams.
Joint Distribution
Let $X=(x_1,x_2)$ where $x_1$ and $x_2$ are two real-valued random variables,
then the joint distribution of $X$ is characterized by
$$
\P[X]{ [a,b]\times [c,d]} = \P{x_1\in [a,b], x_2\in [c,d]}
$$
The expectation of $f(X)$ is defined as
$$
\E[f(X)]=\int_{\R^2} f(x_1,x_2) \P[X]{dx_1 dx_2}
$$
The covariance of $X$ and $Y$ is defined as
$$\mathtt{Cov}(X, Y)=\mb{E}[(X-\mu_X)(Y-\mu_Y)]=\Inn{X-\mu_X}{Y-\mu_Y}$$
The correlation of $X$ and $Y$ is defined as
$$\rho(X,Y) =\frac{\mathtt{Cov}(X, Y)}{\norm{X-\mu_X}\norm{Y-\mu_Y}} \color{blue}= \cos( \angle(X-\mu_X,Y-\mu_Y))$$
Common Distributions
Exponential Family
$$y_i \sim \text{Exponential}(\mu_i, \phi)$$
Where $\mu_i$ is the mean and $\phi$ is the dispersion
parameter.
In dispersion form, every member of the family has a density
$$f(y;\theta,\phi)=\exp\left\{\frac{y\theta-b(\theta)}{a(\phi)}+c(y,\phi)\right\}$$
for a canonical parameter $\theta$ and a known function $b$. One
differentiation gives both moments:
$$\E[Y]=b'(\theta)=\mu,\qquad \mathrm{Var}(Y)=b''(\theta)\,a(\phi),$$
and the data enter the likelihood only through $\sum_i y_i$ — the sample mean
is sufficient, which is why this one shape covers so much of practice:
Family
$\theta$
$b(\theta)$
$a(\phi)$
Normal $(\mu,\sigma^2)$
$\mu$
$\theta^2/2$
$\phi=\sigma^2$
Poisson $(\mu)$
$\log\mu$
$e^\theta$
$1$
Binomial $(m,p)$
$\log\frac{p}{1-p}$
$m\log(1+e^\theta)$
$1$
Geometric $(p)$
$\log(1-p)$
$-\log(1-e^\theta)$
$1$
Negative binomial $(r,p)$
$\log(1-p)$
$-r\log(1-e^\theta)$
$1$
Gamma $(\mu,\phi)$
$-1/\mu$
$-\log(-\theta)$
$\phi$
(Geometric and negative binomial count the failures before the first, resp.
$r$-th, success, with $r$ known.) Generalized linear models are regressions
built on exactly this table: a link function ties $\mu_i$ to the predictors,
and $b$ does the rest.
Statistics
Moments
Central tendency
Mean:
$$\mu(X) = \frac{1}{n} \sum_{i=1}^n x_i$$
Median: assume the data is sorted
$$\mathtt{Med}(X)= \begin{cases}X_{\lceil \frac{n}{2}\rceil} & \text { if } \mathrm{n} \text { is odd } \\
\frac{X_{\lceil\frac{n-1}{2}\rceil}+X_{\lceil\frac{n+1}{2}\rceil}}{2} & \text { if } \mathrm{n} \text
{ is even }\end{cases}$$
Skewness:
$$\gamma_1(X) = \frac{1}{n}\sum_{i=1}^n (\frac{x_i-\mu}{\sigma})^3$$
Zero for any symmetric distribution; the cube gives the farthest points the loudest voice, so small samples estimate it badly.
Shape
Kurtosis:
$$\gamma_2(X) = \frac{1}{n}\sum_{i=1}^n (\frac{x_i-\mu}{\sigma})^4$$
Three for a normal distribution. The fourth power makes it a statement about the tails — the part of a distribution a sample reveals last.
For a standard normal distribution,
The mean is 0
The variance is 1
The skewness is 0
The kurtosis is 3
Skewness & Kurtosis, Computed
The four statistics above, computed on data. Each is a mean of powers of the
standardized values $(x_i - \mu)/\sigma$ — and the third and fourth powers are what
make $\gamma_1$ and $\gamma_2$ fragile: a single draw at three standard deviations
contributes $27$ to the $\hat\gamma_1$ sum and $81$ to the $\hat\gamma_2$ sum, where
a typical draw contributes about $1$. Pick a distribution, then drag $n$: the
histogram of the first $n$ draws fills toward the blue population curve while the
table grades the sample statistics against their population values. One seeded
stream of $2{,}000$ draws per distribution; the slider shows its first $n$.
sample histogrampopulation density (scaled to counts)
Read the crawl, not just the endpoints. The exponential's $\hat\gamma_2$ climbs
$3.98 \to 5.95 \to 6.64 \to 7.67$ as $n$ runs $25 \to 100 \to 500 \to 2000$ and is
still $1.33$ short of $9$ — twelve times the normal yardstick $\sqrt{24/2000} \approx
0.11$ at that $n$ — while its $\hat\gamma_1$ is already within $0.10$ of $2$. The
uniform invents skewness at small $n$ ($\hat\gamma_1 = -0.55$ at $n = 25$, for a
symmetric law) and then behaves: every gap under $0.02$ by $n = 2000$. Even the
normal's own kurtosis is only within $0.14$ of $3$ at $n = 2000$ — about $1.3$
yardsticks, exactly the wobble the yardstick predicts. And the bimodal mixture's
slow statistic is the variance (gap $1.29$ at $n = 25$): two humps take data to fill
in. The pattern across all four distributions is the definitions' own arithmetic —
each statistic is a mean of one higher power of the standardized values, and higher
powers hand the microphone to the rarest draws.
Transformations to Normal
Data are said to be right-skewed if the skewness is positive, and
left-skewed if the skewness is negative.
Box-Cox Transformation
The Box-Cox Transformation is defined as
$$
Y = \begin{cases}
\frac{X^\lambda-1}{\lambda} & \text{if } \lambda \neq 0 \\
\log(X) & \text{if } \lambda = 0
\end{cases}
$$
where $\lambda$ is a parameter, and
$X$ is positive.
$\lambda$ is chosen to maximize the log-likelihood function.
If $X$ is not positive, then a shift $$X\mapsto X-\min(X)+1$$ is needed.
boxcoximport numpy as np
from scipy.stats import boxcox
import matplotlib.pyplot as plt
# Sample data (positive values only)
data = np.random.exponential(scale=0.1, size=1000)
# Apply Box-Cox transformation
transformed_data, lambda_opt = boxcox(data)
print(f"Optimal lambda: {lambda_opt}")
# Plot original vs transformed data
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
ax[0].hist(data, bins=30, color='skyblue', edgecolor='black')
ax[0].set_title("Original Data")
ax[1].hist(transformed_data, bins=30, color='lightgreen', edgecolor='black')
ax[1].set_title("Box-Cox Transformed Data")
plt.show()
Normal Approximation
100 draws from $\ms N(50,\,20^2)$ — each dot is one draw, stacked
where draws pile up. The bands are $\mu \pm 2\sigma$ (outer) and $\mu \pm \sigma$
(inner) of this sample; the chips count how many draws the bands caught —
the empirical rule, measured instead of quoted.
$$\begin{cases} \mathtt{P}(-1< Z < 1) \simeq 0.68\\ \mathtt{P}(-2 < Z < 2) \simeq 0.95\\ \mathtt{P}(-3 < Z < 3)
\simeq 0.997 \end{cases}$$ The probability of getting a value between $-1$ and $1$ is more than half, and it
is
very unlikely to be outside of $(-2, 2)$.
Any computation for $ \mathscr{N}(\mu,\sigma)$ can be
converted
to a computation for $ \mathscr{N}(0,1)$ by
$$Z = \frac{X-\mu}{\sigma}$$
Results can be converted back to $ \mathscr{N}(\mu,\sigma)$ by
$$X = Z*\sigma + \mu$$
The Central Limit Theorem
Let $X_1,\ldots,X_n$ be independent copies of a random variable $X$ with
$\E X=\mu$ and $\mathrm{Var}(X)=\sigma^2<\infty$, and let
$\bar X_n=\frac{1}{n}\sum_{i=1}^n X_i$ be the sample mean.
Then
$$\frac{\sqrt{n}\,(\bar X_n-\mu)}{\sigma}\ \xrightarrow{d}\ \ms N(0,1)
\qquad\text{as } n\to\infty,$$
that is, for large $n$ the sample mean itself is approximately normal,
$\bar X_n\approx\ms N\!\left(\mu,\ \dfrac{\sigma^2}{n}\right)$ — whatever the
shape of $X$.
The standard deviation of the mean is $\sigma/\sqrt n$, not $\sigma$: averaging
$n$ observations divides the spread by $\sqrt n$, so halving the error bars costs
four times the data. It is called the standard error of
the mean, and the empirical rule above applies to $\bar X_n$ itself — about $95\%$
of sample means land within $2\sigma/\sqrt n$ of $\mu$.
The demo makes the theorem visible. Pick a population — none of the three is
normal: one is flat, one is skewed, one has a hole in the middle — choose the sample
size $n$, and draw $2{,}000$ sample means. At $n=1$ the histogram is the
population (the dashed outline); as $n$ grows it lets go of the population's shape
and settles onto the normal curve $\ms N(\mu,\,\sigma^2/n)$, while its spread shrinks
like $\sigma/\sqrt n$.
Density histogram of $2{,}000$ sample means (amber). Dashed: the population
density itself. Blue: $\ms N(\mu,\,\sigma^2/n)$, the central limit theorem's prediction.
Draws are seeded (seed $1234$ for the first picture), so the figure is reproducible;
each redraw advances the seed.
Three remarks. Speed. The convergence comes with a rate: the Berry–Esseen
theorem bounds the error of the normal approximation by $C\rho/(\sigma^3\sqrt n)$,
where $\rho=\E|X-\mu|^3$ and $C<0.48$ is a universal constant — the approach
runs at rate $1/\sqrt n$, and a skewed or heavy-tailed population (large $\rho$)
pays for it in the $n$ it needs; that is the exponential above still leaning
right at $n=10$. Finite variance matters. If $\sigma^2=\infty$ the theorem
simply fails: the mean of $n$ Cauchy variables has exactly the same distribution as
a single one of them, at every $n$ — no bell ever forms. How large is large
enough? There is no universal $n$. The folklore $n\ge 30$ is serviceable for
mildly skewed populations — drag the slider and watch the exponential lose its
lean around there — but a symmetric population is most of the way to normal by
$n=5$, and a strongly skewed or heavy-tailed one can need hundreds. The readout's
inside-the-band percentage is the check to watch: it should settle near $95\%$
as the shape does. Why the theorem sits
here. Everything after it leans on it: the $z$- and $t$-tests in Hypothesis
Testing read tail probabilities for $\bar X_n$ off the normal (or $t$) curve, and
the bootstrap replaces this theorem's curve with a simulated one when the population
is unknown.
Covariance & Correlation
50 points with population correlation $
ho$ — the line is the
least-squares fit of $y$ on $x$ for the points drawn. Points are seeded
(the first picture is reproducible); each Generate advances the seed.
The correlation coefficient is defined by the following
formula
$$\rho(X,Y)=\mb{E}\{ \frac{X-\mu_X}{\sigma_X} \frac{Y-\mu_Y}{\sigma_Y}\} = \frac{1}{n}
\sum_{i=1}^{n}\left(\frac{X_{i}-\mu_X}{\sigma_{X}}\right)\left(\frac{Y_{i}-\mu_Y}{\sigma_{Y}}\right) $$
A different, but equivalent, way to introduce the correlation coefficient, is to first define
covariance and consider correlation as a normalized version of it.
Regression
Regression Line
The regression line is the line passing through $(\mu_X,\mu_Y)$ with slope
$$\frac{\rho \cdot \sigma_Y}{\sigma_X}$$
Since this is a 100 level introductory class for students from all majors, we will not go into the
technical
details.
If interested, see the page on Linear Regression for
the
general case.
RMS Error for Regression
Root Mean Square Error (RMS) is a measure of the error between the predicted value and the actual value.
$$\mathtt{RMS} = \sqrt{\frac{\sum_{i=1}^n(\hat{y_i}-y_i)^2}{\mathtt{n}}}$$
Among all lines, the one that makes the smallest RMS error in predicting $y$ from $x$ is
the
regression line.
Hypothesis Testing
t-test / z-test : One sample
Normal & Student-T distribution
The Student $t$ density on $
u$ degrees of freedom against the
standard normal it converges to. The tail chip is the price of the heavy
tails: $\mb P(|T| > 1.96)$ against the normal's $0.050$.
Given a set of points, $$x_1,\cdots,x_n$$ drawn from the normal distribution
$\ms{N}(\mu,\sigma^2)$,
then $$\frac{\bar{X}-\mu}{\sigma/\sqrt{n}}\sim\ms{N}(0,1) $$
and $$\frac{\bar{X}-\mu}{S/\sqrt{n}}\sim\mathtt{T}(n-1)$$ Where $S^{2}=\frac{1}{n-1}
\sum_{i=1}^{n}\left(x_{i}-\bar{x}\right)^{2} $ is the sample variance.
The second result is especially useful, since in practice $\sigma$ is often unknown, and we have to estimate
it
with the sample standard deviation, $S$.
As can be seen from the demo above, when $n>30$, the Student-T distribution is very close to
that
of the
Standard
Normal. Thus in practice, if $n>30$ then we use the $Z$-test regardless of whether $\sigma$ is known.
Given a set of points, $$x_1,\cdots,x_n$$ drawn from the normal distribution
$\ms{N}(\mu,\sigma^2)$,
we want to test the hypothesis
$$H_0: \mu=\mu_0\qquad \color{lightgray} H_0: \mu\le \mu_0$$
$$H_1: \mu\neq \mu_0 \qquad \color{lightgray} H_1: \mu> \mu_0$$
The test statistic is
$$T=\frac{\bar{X}-\mu_0}{S/\sqrt{n}}$$
If $H_0$ is true, then $T\sim \mathtt{T}(n-1)$
The p-value is the probability of getting a value more extreme than $T$
$$
\text{p} = \P{|T|> |t|} = 2(1-\P{T\le |t|})\qquad \color{lightgray} \text{p} = \P{T> t} = 1-\P{T\le t}
$$
Given a set of points, $$x_1,\cdots,x_n$$ drawn from the normal distribution
$\ms{N}(\mu,\sigma^2)$,
we want to test the hypothesis
$$H_0: \mu=\mu_0\qquad \color{lightgray} H_0: \mu\le \mu_0$$
$$H_1: \mu\neq \mu_0 \qquad \color{lightgray} H_1: \mu> \mu_0$$
The test statistic is
$$Z = \frac{\bar{X}-\mu_0}{\sigma/\sqrt{n}}$$
If $H_0$ is true, then $Z\sim \ms{N}(0,1)$
The p-value is the probability of getting a value more extreme than $Z$
$$
\text{p} = \P{|Z|> |z|} = 2(1-\P{Z\le |z|})\qquad \color{lightgray} \text{p} = \P{Z> z} = 1-\P{Z\le z}
$$
Bootstrap Method for Hypothesis Testing
Given a set of points, $$x_1,\cdots,x_n$$
we want to test the hypothesis
$$H_0: T=T_0\qquad \color{lightgray} H_0: T\le T_0$$
$$H_1: T\neq T_0 \qquad \color{lightgray} H_1: T> T_0$$
Shift the data so that the null hypothesis is true, e.g. for $T=\mu$, $\mu_0=0$ we shift the data by $\bar{x}$,
$$x_1',\cdots,x_n'$$
after this step, the null hypothesis is true, i.e. $\bar{x}'=0$
Resample with replacement from the shifted data to get a new set of points, $$x_1^*,\cdots,x_n^*$$ repeat $B$
times.
Calculate the test statistic for each of the $B$ sets of points, $$T_1,\cdots,T_B$$
Use the $T_1,\cdots,T_B$ to create a sampling distribution for $T$.
This is the distribution of $T$ under the assumption that $H_0$ is true.
Compare the observed value of $T$ with the sampling distribution of $T$ to get the p-value.
e.g. for $H_1: T> T_0$, the p-value is
$$\text{p} = \P{T> T_0} = \frac{|\{i : T_i > T_0\}|}{B}$$
The algorithm above spends the resampling distribution on a p-value. The same
machinery also measures: resample the observed sample itself — no shift, since no
null is being imposed — and the spread of the resampled means estimates the standard
error of $\bar x$ from the one sample in hand, with no normality assumption and no
$\sigma$ to know. The middle $95\%$ of the bootstrap distribution is the
percentile confidence interval. It is the simulated counterpart of the Central
Limit Theorem demo's $\sigma/\sqrt n$ curve, for the common case where the population
is unknown and only the sample exists.
One fixed sample of $n = 40$ skewed values (top; drawn once from
$\mathrm{Exponential}(1)$ under a seed, then held fixed). Each resample draws
$40$ values from the sample, with replacement, and recomputes the mean;
the histogram collects those means, and the shaded middle $95\%$ is the percentile
interval. Resampling is seeded too, so the accumulation is reproducible; Reset
restarts the stream.
Confidence Intervals and Coverage
The bootstrap section above built one interval from one sample. The claim made for
any such interval — $\bar x \pm t^* s/\sqrt n$ at the $95\%$ level — is not about
that one interval, which either contains $\mu$ or does not. It is a promise about the
procedure: over repeated samples, $95\%$ of the intervals it produces cover the
true mean. That promise is countable. The simulator draws sample after sample from a
population whose $\mu$ is known, builds the interval each time, and stacks the last
$30$, coloured by whether they cover — the running coverage frequency against the
nominal $95\%$ is the frequentist meaning of "confidence", made visible.
covers μmissestrue μ
Each row is one fresh sample's $95\%$ interval, newest on top, with a dot
at its $\bar x$; the dashed line is the population's true $\mu$. Green covers,
red misses. Drawing is seeded, and changing any control reseeds and restarts the
count, so every configuration is reproducible.
0%nominal 95%100%
Normality
The
Shapiro-Wilk test
is a test of normality
The null hypothesis is that the data is normally distributed.
with the test statistic given by $$W=\frac{\left(\sum_{i=1}^{n} a_{i}
x_{(i)}\right)^{2}}{\sum_{i=1}^{n}\left(x_{i}-\bar{x}\right)^{2}}$$
where $x_{(i)}$ is the $i$-th smallest value of $x$.
Random Processes
Wiener
process
$\left(W_t,t\in \R_+\right)$ is called a Wiener
process if
$W_0=0$
$W_t-W_s\sim \ms{N}(0,t-s)$ for all $t>s$
$W_t$ has independent increments
$W_t$ has continuous paths
A Wiener process is continuous everywhere but nowhere differentiable.
Martingale
A martingale is a stochastic process $X_t$ such that
$$\E\{X_t\mid X_u,\ u\le s\} = X_s$$
for all $t>s$: the best prediction of a future value, given the whole history
to date, is the current value.
A Wiener process is a martingale.
Stock Price
$$\color{royalblue}\bf
dS_t = \mu S_t dt + \underbrace{\overbrace{\sigma}^{fluctuation} S_t dW_t}_{uncertainty}, \qquad S_0>0
\implies \color{blue} S_t = S_0 + \int_0^t \mu S_u du + \underbrace{\int_0^t \sigma S_u dW_u}_{\text{ito integral}}
\implies \color{darkblue}\bf S_t = S_0 e^{(\mu-\frac{1}{2}\sigma^2)t + \sigma W_t} \sim lognormal(\ln S_0+\mu t -
\frac{1}{2}\sigma^2 t, \sigma^2 t)
$$
If $B_t$ is the value of a savings account at time $t$, then
$$B_t = B_0 \exp(\mu t), \qquad dB_t = \mu B_t dt$$
where $\mu$ is the interest rate.
Discounted Stock Price
Discounting measures the stock in units of the savings account: with $B_0 = 1$,
$$\tilde{S}_t = S_t/B_t = \exp(-\mu t)S_t.$$
Substituting the geometric Brownian motion solution from the Stock Price section,
the drift cancels exactly:
$$\tilde{S}_t = S_0 \exp\left(-\tfrac{1}{2}\sigma^2 t + \sigma W_t\right).$$
This is a martingale in the sense of the Martingale section
above: for $t > s$, the increment $W_t - W_s$ is independent of the history to $s$ and
$\E\{e^{\sigma (W_t - W_s)}\} = e^{\frac{1}{2}\sigma^2 (t-s)}$ (the normal
moment-generating function), so
$$\E\{\tilde{S}_t \mid \tilde{S}_u,\ u \le s\} = \tilde{S}_s \cdot
e^{-\frac{1}{2}\sigma^2 (t-s)} \E\{e^{\sigma (W_t - W_s)}\} = \tilde{S}_s.$$
The $-\frac{1}{2}\sigma^2 t$ Itô correction is exactly what the normal mgf
undoes — discounting at the drift turns the stock into a fair game. In
particular $\E\{\tilde{S}_t\} = S_0$ at every $t$: the bank account is the yardstick
the stock's average keeps pace with.
Two honest qualifications. First, the cancellation used that the discount rate is
the drift $\mu$ itself — this page's savings account pays the same $\mu$ as the
stock earns. Discounting at a general rate $r$ leaves
$\E\{S_t/B_t\} = S_0 e^{(\mu - r)t}$: flat only when $r = \mu$, compounding when
$r < \mu$, decaying when $r > \mu$. Second, the martingale is a statement about the
mean, not the typical path: the median discounted path is
$S_0 e^{-\frac{1}{2}\sigma^2 t}$, which decays, so most paths sit below $S_0$ and a
minority of large ones carry the average. The demo below shows both facts at once.
Discounted Price, Computed
Discount rate $r$:
30 discounted pathsmean of 600 ± 2 MC s.e.median paththeory $\E\{\tilde{S}_t\}$
Six hundred seeded geometric Brownian motion paths ($S_0 = 100$,
$\mu = 0.08$, $\sigma = 0.30$, $t \in [0, 4]$ years, monthly steps), each divided
by $e^{rt}$. The theory line is $\E\{\tilde{S}_t\} = 100\,e^{(\mu - r)t}$; it is
flat at $S_0$ only when $r = \mu$. Paths are drawn clipped to the plot window.
New paths redraws from the next seed, so the picture is reproducible.
Bayesian Statistics
Bayesian Theorem
The Bayesian Theorem is the following formula
$$ \begin{align*}
\underbrace{\P{A|D}}_{\text{Posterior}} =
\frac{\overbrace{\P{D|A}}^{\text{Likelihood}}\overbrace{\P{A}}^{\text{Prior}}}{\underbrace{\P{D}}_{\text{Evidence}}}
&\propto \P{D|A}\P{A} \qquad \small \color{blue} D=\{d_1,\cdots,d_n\} \quad (n\text{ data points})
\\& = \P{d_1|A}\P{d_2|A,d_1}\cdots\P{d_n|A,d_1,\cdots,d_{n-1}}\P{A}
\\ {\small \color{red} (\text{Naive independent Assumption})} &= \P{d_1|A}\P{d_2|A}\cdots\P{d_n|A}\P{A}
\end{align*}$$
The sections above treat the parameter as a fixed unknown and the data as
random. The Bayesian reading reverses the emphasis: the data are fixed once
observed, and the posterior $\P{A\mid D}$ is a
probability distribution over the parameter itself, summarising what the data,
combined with what was believed beforehand, now say about it. Each factor has a
job: the prior $\P{A}$ states the belief before
this data set, the likelihood $\P{D\mid A}$ is
the sampling model read backwards, and the evidence
$\P{D}$ is only the normalising constant that makes the posterior integrate
to one — which is why the working form of the theorem is the
proportionality posterior $\propto$ likelihood $\times$ prior.
Updating is sequential for free: when more data arrive, today's posterior is
tomorrow's prior, and the result is the same as if all the data had arrived at
once.
Conjugate Priors: The Beta–Binomial
Bayes' theorem is one line; using it means choosing a prior and computing the
normalising integral. Both become easy when the prior is
conjugate to the likelihood: the posterior then lies
in the same family as the prior, and updating is arithmetic on the family's
parameters. The canonical pair is a proportion. Let $\theta\in(0,1)$ be an
unknown success rate — a coin's bias, a click-through rate, a defect
rate — and suppose $s$ successes are seen in $n$ independent
trials. The likelihood is
$$ \P{D\mid\theta} \propto \theta^{s}(1-\theta)^{\,n-s}, $$
and the $\mathrm{Beta}(\alpha,\beta)$ prior, whose density is proportional
to $\theta^{\alpha-1}(1-\theta)^{\beta-1}$, has exactly the same shape in
$\theta$. Multiplying the two and reading off the exponents,
$$ \theta\mid D \;\sim\; \mathrm{Beta}(\alpha+s,\;\beta+n-s): $$
a Beta prior plus binomial data is a Beta posterior — count the
successes into $\alpha$ and the failures into $\beta$. The prior's
parameters act as pseudo-counts from $\alpha+\beta$ imaginary earlier
trials, and the posterior mean splits accordingly,
$$ \E[\theta\mid D] = \frac{\alpha+s}{\alpha+\beta+n}
= \frac{\alpha+\beta}{\alpha+\beta+n}\cdot\frac{\alpha}{\alpha+\beta}
+ \frac{n}{\alpha+\beta+n}\cdot\frac{s}{n}, $$
a weighted average of the prior mean and the sample rate, with weights set by
pseudo-count against real count. As $n$ grows the second term takes over:
enough data washes any fixed prior out, which is the precise sense
in which Bayesian conclusions become prior-independent. Other standard pairs
work the same way — a normal prior for a normal mean with known
variance, a gamma prior for a Poisson rate. Outside the conjugate families the
posterior has no closed form and is computed instead, by the sampling methods
(MCMC) that made modern Bayesian work practical.
The Posterior Explorer
The conjugacy above, made manipulable. Choose a prior, set the data, and the
posterior is recomputed in closed form: the grey dashed curve is the prior, the
amber dotted curve is the likelihood renormalised as a density in
$\theta$ — the posterior a uniform prior would produce — and
the blue curve is the posterior itself, with its equal-tailed $95\%$
credible band shaded. The three preset buttons hold the sample rate at
$0.70$ while the sample grows: watch a strong prior hold the posterior near
$0.54$ at $n = 10$ and lose to the data by $n = 200$.
Conjugate updating is exact arithmetic, not simulation: every curve
is the closed-form Beta density, recomputed on every control change, so
every state of this demo is reproducible.
Credible Intervals
A posterior distribution answers interval questions directly. The equal-tailed
$95\%$ credible interval
$[q_{0.025},\,q_{0.975}]$ cuts $2.5\%$ of the posterior mass from each
tail, and its reading is the one the confidence interval is so often misread as
making: given the data and the prior, the probability that $\theta$
lies in this interval is $0.95$. The coverage simulator in Hypothesis
Testing shows what the frequentist interval promises instead — a
$95\%$ success rate of the procedure over repeated samples, with any
one interval simply covering or not. Neither statement is the other. They also
behave differently where it matters: the credible interval moves when the
prior moves (at small $n$, visibly — the skeptical prior above turns
$7$ successes in $10$ trials into a posterior mean of $0.45$, not
$0.70$), while the confidence interval's coverage can sag below its nominal
level on skewed populations at small $n$, as the simulator's exponential
rows show. With a weak prior and a moderate sample the two intervals nearly
coincide numerically; what differs is the claim each one makes.
Applications to Finance
Portfolio Theory
CAPM
The Capital Asset Pricing Model (CAPM) is the following linear regression model:
$$
(R_p-R_f)=\alpha_p+\beta_{p}(R_m-R_f)
$$
$R_p$ is the return of a portfolio $p$
$R_f, R_m$ is the return of the risk-free asset and the market portfolio
$\alpha_p$ is the alpha of the portfolio $p$.
$\beta_{p}$ is the beta of the portfolio $p$.
Let $R_p, \sigma_p$ be the return and volatility of a portfolio.
The beta of portfolio $p$ with respect to the market is given by
$$\beta_{p}=\frac{\mathrm{Cov}(R_p,R_m)}{\sigma_m^2}= \frac{\rho_{p,m}\sigma_p}{\sigma_m}$$
Sharpe Ratio
Let $R_a, \sigma_a$ be the return and volatility of an asset, and $R_f$ be mean return of the risk-free
asset.
Then the Sharpe ratio of the portfolio is defined as
$$S_a=\frac{\E{R_a-R_f}}{\sigma_a}$$
The Sharpe ratio can be viewed as a standardized measure of expected return
$$
\text{Treynor ratio} = \frac{\E{R_a-R_f}}{\beta_a}
$$
$$
\text{Generalized Sharpe ratio} = \frac{\E{[R_a-R_b]}}{\sigma_a}
$$
Efficient Frontier
The Efficient Frontier is the collection of risk-return pairs $$
\{(\sigma_P,\E R_P) \mid\ \nexists P'\ :\ \E R_{P'} \ge \E R_P \wedge \sigma_{P'} \le \sigma_P,\ \text{at least one strict} \}$$:
the portfolios no other portfolio beats on both axes at once.
Let $P$ be a risky portfolio, and $R_f$ be the return of the risk-free asset.
Let $C$ be a combination of $P$ and the risk-free asset.
The collection of all risk-return pair $$ (\sigma_C, \E(R_C) )$$
for all possible combinations $C$ gives the Capital Allocation Line (CAL).
For a given risky portfolio $P$, the CAL is given by the line
$$\E(R_C)=R_f+\sigma_C S_P$$
Let $CAL_T$ be the CAL tangent to the efficient frontier.
Let $P$ be the corresponding portfolio.
Then $P$ is the Tangency portfolio, and
$P$ has the highest Sharpe ratio among all portfolios.
Risks
VaR and CVaR
For a portfolio loss $L$, $\VaR_{\alpha}(L)$
value at risk
at confidence level $\alpha$ is:
Casella & Berger, Statistical Inference, 2nd ed., Duxbury, 2002 — the standard graduate treatment behind most of this page: probability spaces, random variables, common distributions, moments, estimation, hypothesis testing and Bayesian inference.
Berger, Statistical Decision Theory and Bayesian Analysis, 2nd ed., Springer, 1985 — the decision-theoretic foundation of Bayesian inference: priors, posteriors, and what is lost by choosing wrongly.
Gelman, Carlin, Stern, Dunson, Vehtari & Rubin, Bayesian Data Analysis, 3rd ed., CRC Press, 2013 — the modern applied treatment behind this section: conjugate updating, posterior simulation, and credible intervals in practice.
Wasserman, All of Statistics: A Concise Course in Statistical Inference, Springer, 2004 — a compact modern route through the same material, including the normal approximation and regression.
Karatzas & Shreve, Brownian Motion and Stochastic Calculus, 2nd ed., Springer, 1991 — the Wiener process, martingales and the Itô integral behind the geometric Brownian motion stock model above.
Markowitz, Portfolio selection, Journal of Finance 7(1), 1952, 77–91 — mean–variance analysis and the efficient frontier.
Sharpe, Capital asset prices: A theory of market equilibrium under conditions of risk, Journal of Finance 19(3), 1964, 425–442 — the CAPM and the beta formula used above.
Sharpe, The Sharpe ratio, Journal of Portfolio Management 21(1), 1994, 49–58 — the (generalized) Sharpe ratio as mean differential return over its standard deviation, against a benchmark.
Rockafellar & Uryasev, Optimization of conditional value-at-risk, Journal of Risk 2, 2000, 21–41 — CVaR / expected shortfall, defined and made optimizable.
Roy, Safety first and the holding of assets, Econometrica 20(3), 1952, 431–449 — the downside-first view of risk that the partial-moments section develops.