What Is a Stochastic Process? Definition and Examples
Environment
Python 3.14.6, NumPy 2.4.6, SciPy 1.18.1, Matplotlib 3.11.2 (Jupyter Notebook).
This article is a rewrite of a post from around 2021, with calculations performed in the environment described above.
Overview
A stochastic process is a collection of random variables indexed by time. To describe cumulative customer arrivals or a particle’s position, we need both the distribution at each time and the relationships between times. This article defines a stochastic process and compares Bernoulli processes, random walks, Poisson processes, and Brownian motion using equations and Python.
This article corresponds to Chapter 1, “Foundations of Stochastic Processes,” of Theory and Practice of Stochastic Processes. It assumes basic knowledge of expectation, variance, and independence.
Preparation
Run the code cells in order. Round numerical values to three significant figures only for display.
Check the environment, import libraries, and configure plots
from pathlib import Path
from pprint import pprint
import platform
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy
from scipy import stats
from IPython.display import Math, display
from matplotlib.ticker import FuncFormatter, MaxNLocator
from matplotlib_inline.backend_inline import set_matplotlib_formats
set_matplotlib_formats("svg")
def sig(value):
# 表示だけを3桁に丸める。
return "0" if value == 0 else format(float(value), "#.3g")
np.set_printoptions(formatter={"float_kind": sig})
plt.rcParams.update({"font.size": 10, "svg.fonttype": "none",
"axes.spines.top": False, "axes.spines.right": False})
cwd = Path.cwd()
base = cwd / "series/stochastic-processes/101" if (cwd / "pyproject.toml").exists() else cwd
image_dir = base / "101_nb_files"
image_dir.mkdir(parents=True, exist_ok=True)
def save(fig, name):
fig.savefig(image_dir / name, format="svg", bbox_inches="tight",
metadata={"Date": None})
plt.show()
plt.close(fig)
def ticks(ax, which="y"):
for name in which:
getattr(ax, name + "axis").set_major_formatter(
FuncFormatter(lambda value, _: sig(value)))
print("カーネル: wa-src(3.14.6)")
print("Python:", platform.python_version())
print("NumPy:", np.__version__, "SciPy:", scipy.__version__)
print("Matplotlib:", matplotlib.__version__)
assert platform.python_version() == "3.14.6"
カーネル: wa-src(3.14.6)
Python: 3.14.6
NumPy: 2.4.6 SciPy: 1.18.1
Matplotlib: 3.11.2
1. Separate Time from the Outcome
Let $(\Omega,\mathcal{F},\mathbb{P})$ be a probability space. Here, $\Omega$ is the set of possible outcomes, $\mathcal{F}$ is the collection of events to which probabilities are assigned, and $\mathbb{P}$ is the probability measure. Given a time index set $T$ and a state space $E$, a stochastic process is a family of random variables on the same probability space:
$$ X=\{X_t:t\in T\},\qquad X_t:\Omega\longrightarrow E $$
For $E=\mathbb{R}$, each $X_t$ is measurable: $\{\omega:X_t(\omega)\le a\}\in\mathcal{F}$ for every real number $a$. Chapter 1 of Shalizi’s lecture notes starts from this definition as well.
Fixing the time $t$ gives the random variable $\omega\mapsto X_t(\omega)$. Fixing the outcome $\omega$ gives one sample path, $t\mapsto X_t(\omega)$. A line drawn from one simulation usually connects observed values along this sample path.
| Time | State | Example |
|---|---|---|
| Discrete | Discrete | Coin outcomes; a random walk on the integers |
| Discrete | Continuous | A time series with Gaussian noise, $X_n=aX_{n-1}+\varepsilon_n$ |
| Continuous | Discrete | The cumulative count in a Poisson process |
| Continuous | Continuous | The position of Brownian motion |
Continuous time means that any real time in the index set can be specified. It does not imply continuous paths. The definition of a stochastic process also requires neither independence nor identical distributions.
2. A Bernoulli Process and Cumulative Counts
In independent trials, let success be $1$ and failure be $0$, with success probability $p$.
$$ \mathbb{P}(B_n=1)=p,\quad\mathbb{P}(B_n=0)=1-p,\quad C_0=0,\quad C_n=\sum_{j=1}^{n}B_j. $$
The family $\{B_n\}$ is a Bernoulli process, and $C_n$ is the cumulative number of successes. Since $B_n^2=B_n$,
$$ \begin{aligned} \mathbb{E}[B_n]&=0(1-p)+1p=p,\\ \operatorname{Var}(B_n)&=\mathbb{E}[B_n^2]-\mathbb{E}[B_n]^2=p-p^2=p(1-p),\\ \mathbb{E}[C_n]&=\sum_{j=1}^{n}p=np,\\ \operatorname{Var}(C_n)&=\sum_{j=1}^{n}p(1-p)=np(1-p). \end{aligned} $$
The last equation uses independence: the covariance between different trials is $0$. There are $\binom{n}{k}$ sequences with $k$ successes, each with probability $p^k(1-p)^{n-k}$, so
$$ \mathbb{P}(C_n=k)=\binom{n}{k}p^k(1-p)^{n-k},\qquad k=0,\ldots,n. $$
With $p=0.350$ and $n=60$, the expectation is $21.0$ and the variance is $13.7$. In the following arrays, rows represent independent repetitions and columns represent times.
rng = np.random.default_rng(101)
m, n, p = 5000, 60, 0.350
bernoulli = rng.binomial(1, p, size=(m, n))
# 時刻0を先頭に付ける。
counts = np.column_stack([np.zeros(m, dtype=int), bernoulli.cumsum(axis=1)])
time = np.arange(n + 1)
pprint({"平均(標本・理論)": (sig(counts[:, -1].mean()), sig(n * p)),
"分散(不偏・理論)": (sig(counts[:, -1].var(ddof=1)), sig(n * p * (1 - p)))})
fig, axes = plt.subplots(1, 2, figsize=(10, 3), layout="constrained")
axes[0].scatter(time[1:], bernoulli[0], s=15)
axes[0].set(xlabel="Trial n", ylabel="Success indicator", yticks=[0, 1])
axes[1].plot(time, counts[:6].T, alpha=0.600)
axes[1].plot(time, time * p, "k--", label="Mean np")
axes[1].set(xlabel="Trial n", ylabel="Cumulative successes")
axes[1].legend()
save(fig, "01_bernoulli_paths.svg")
k = np.arange(n + 1)
empirical = np.bincount(counts[:, -1], minlength=n + 1) / m
theory = stats.binom.pmf(k, n, p)
np.testing.assert_allclose(theory.sum(), 1)
fig, ax = plt.subplots(figsize=(7, 3), layout="constrained")
ax.bar(k, empirical, label="Simulation", alpha=0.600)
ax.plot(k, theory, "o-", markersize=3, label="Binomial PMF")
ax.set(xlabel="C(60)", ylabel="Probability")
ticks(ax)
ax.legend()
save(fig, "02_binomial_distribution.svg")
{'分散(不偏・理論)': ('13.8', '13.7'), '平均(標本・理論)': ('21.1', '21.0')}
$$ \displaystyle C_{60}\sim\operatorname{Bin}(60,0.350) $$
The left panel of Figure 1 shows one trial sequence; the right panel shows six cumulative paths. Figure 2 shows the final-time distribution across 5,000 paths. A time average along one path and an average across paths at a fixed time describe different quantities. Checking the rows and columns of the array helps keep them separate.
3. A Random Walk
Let the independent increments $\xi_j$ take values $-1$ and $1$, each with probability $1/2$.
$$ S_0=0,\qquad S_n=\sum_{j=1}^{n}\xi_j. $$
Since $\mathbb{E}[\xi_j]=(-1)/2+1/2=0$ and $\mathbb{E}[\xi_j^2]=1$,
$$ \mathbb{E}[S_n]=0,\qquad \operatorname{Var}(S_n)=\sum_{j=1}^{n}\operatorname{Var}(\xi_j)=n. $$
A mean of $0$ does not mean that each path stays at $0$. The standard deviation grows as $\sqrt{n}$. The increments are independent, but $S_n$ and $S_{n+1}$ share increments and are therefore dependent.
increments = 2 * rng.integers(0, 2, size=(m, n)) - 1
walk = np.column_stack([np.zeros(m, dtype=int), increments.cumsum(axis=1)])
assert np.all(np.abs(np.diff(walk, axis=1)) == 1)
pprint({"S(60)の平均": sig(walk[:, -1].mean()),
"S(60)の不偏分散": sig(walk[:, -1].var(ddof=1)), "理論分散": n})
fig, axes = plt.subplots(1, 2, figsize=(10, 3), layout="constrained")
axes[0].plot(time, walk[:6].T, alpha=0.700)
axes[0].axhline(0, color="black", linestyle="--")
axes[0].set(xlabel="Step n", ylabel="Position S(n)")
ticks(axes[0])
axes[1].plot(time, walk.var(axis=0, ddof=1), label="Sample variance")
axes[1].plot(time, time, "k--", label="Theory: n")
axes[1].set(xlabel="Step n", ylabel="Variance")
axes[1].legend()
save(fig, "03_random_walk.svg")
{'S(60)の不偏分散': '61.0', 'S(60)の平均': '0.0716', '理論分散': 60}
$$ \displaystyle \operatorname{SD}(S_{60})=\sqrt{60}\simeq7.75 $$
4. A Poisson Process
Let $\lambda>0$ be the average arrival rate per unit time. A homogeneous Poisson process $N_t$ is a right-continuous counting process starting at $N_0=0$. Its increments over disjoint intervals are independent and satisfy
$$ N_{t+h}-N_t\sim\operatorname{Poisson}(\lambda h),\qquad \mathbb{P}(N_t=k)=e^{-\lambda t}\frac{(\lambda t)^k}{k!} $$
Here, $h>0$ and $k=0,1,\ldots$. A constant arrival rate and independent increments are modeling assumptions. For real customer arrivals, we must check the effects of the time of day and congestion. MIT’s lecture notes summarize the basic properties.
Set $a=\lambda t>0$. Using the exponential series $\sum_{j=0}^{\infty}a^j/j!=e^a$ gives
$$ \begin{aligned} \mathbb{E}[N_t] &=\sum_{k=1}^{\infty}k e^{-a}\frac{a^k}{k!} =ae^{-a}\sum_{j=0}^{\infty}\frac{a^j}{j!}=a,\\ \mathbb{E}[N_t(N_t-1)] &=\sum_{k=2}^{\infty}k(k-1)e^{-a}\frac{a^k}{k!} =a^2e^{-a}\sum_{j=0}^{\infty}\frac{a^j}{j!}=a^2,\\ \operatorname{Var}(N_t)&=a^2+a-a^2=a. \end{aligned} $$
The interarrival times $W_j$ are independent exponential random variables with $\mathbb{P}(W_j>w)=e^{-\lambda w}$. Constructing arrival times $T_k=\sum_{j=1}^{k}W_j$ gives $N_t=\sum_{k\ge1}\mathbf{1}_{\{T_k\le t\}}$. Generating the arrival times directly also lets us draw jumps without rounding their times to a regular observation grid.
rate, horizon = 2, 4
fig, axes = plt.subplots(1, 2, figsize=(10, 3), layout="constrained")
for _ in range(5):
arrivals, current = [], 0
while True:
current += rng.exponential(1 / rate)
if current > horizon:
break
arrivals.append(current)
# where="post" により到着時点で値が増える右連続な経路にする。
axes[0].step([0, *arrivals, horizon],
[0, *range(1, len(arrivals) + 1), len(arrivals)], where="post")
axes[0].set(xlabel="Time t", ylabel="Count N(t)")
ticks(axes[0], "x")
# 右図は最終時刻の分布だけを独立に抽出する。経路の生成ではない。
terminal = rng.poisson(rate * horizon, size=m)
k = np.arange(max(terminal.max(), 24) + 1)
axes[1].bar(k, np.bincount(terminal, minlength=len(k)) / m, alpha=0.600,
label="Simulation")
axes[1].plot(k, stats.poisson.pmf(k, rate * horizon), "o-", markersize=3,
label="Poisson PMF")
axes[1].set(xlabel="N(4)", ylabel="Probability")
ticks(axes[1])
axes[1].legend()
pprint({"平均": sig(terminal.mean()), "不偏分散": sig(terminal.var(ddof=1)),
"理論値(平均・分散)": rate * horizon})
save(fig, "04_poisson_process.svg")
{'不偏分散': '7.94', '平均': '7.92', '理論値(平均・分散)': 8}
In Figure 4, time is continuous, but the state takes nonnegative integer values. The vertical lines are graphical symbols for jumps; the process does not pass through the intermediate values.
5. Brownian Motion
Standard Brownian motion $W_t$ starts at $W_0=0$, has independent increments over disjoint intervals, and satisfies
$$ W_{t+h}-W_t\sim\mathcal{N}(0,h) $$
Its paths are continuous almost surely. The second parameter in $\mathcal{N}(\mu,\sigma^2)$ is the variance. On a regular grid $t_j=j\Delta t$, independent $Z_j\sim\mathcal{N}(0,1)$ give
$$ \begin{aligned} \Delta W_j&=\sqrt{\Delta t}\,Z_j,\\ W_{t_k}&=\sum_{j=1}^{k}\Delta W_j,\\ \mathbb{E}[W_{t_k}]&=0,\qquad \operatorname{Var}(W_{t_k})=\sum_{j=1}^{k}\Delta t=k\Delta t=t_k. \end{aligned} $$
The standard deviation is scaled by $\sqrt{\Delta t}$, not $\Delta t$. Using the latter would give variance $k(\Delta t)^2=t_k\Delta t$, making the fluctuations disappear as the time step decreases.
steps, duration = 200, 1
dt = duration / steps
t = np.linspace(0, duration, steps + 1)
dw = rng.normal(0, np.sqrt(dt), size=(m, steps))
brownian = np.column_stack([np.zeros(m), dw.cumsum(axis=1)])
pprint({"W(1)の平均": sig(brownian[:, -1].mean()),
"W(1)の不偏分散": sig(brownian[:, -1].var(ddof=1))})
fig, axes = plt.subplots(1, 2, figsize=(10, 3), layout="constrained")
axes[0].plot(t, brownian[:6].T, alpha=0.700)
axes[0].set(xlabel="Time t", ylabel="W(t): grid values joined")
ticks(axes[0], "xy")
axes[1].hist(brownian[:, -1], bins=35, density=True, alpha=0.600,
label="Simulation")
x = np.linspace(-4, 4, 301)
axes[1].plot(x, stats.norm.pdf(x), "k-", label="Normal PDF")
axes[1].set(xlabel="W(1)", ylabel="Density")
ticks(axes[1], "xy")
axes[1].legend()
save(fig, "05_brownian_motion.svg")
{'W(1)の不偏分散': '1.06', 'W(1)の平均': '0.0119'}
$$ \displaystyle W_1\sim\mathcal{N}(0,1),\qquad\Delta t=0.00500 $$
The grid-point values in Figure 5 follow the joint distribution of Brownian motion at those times. The straight lines between points are drawing interpolations, not an exact simulation of the entire path. The vertical axis in the right panel is a probability density, unlike the probability masses in Figures 2 and 4.
Conclusion
This article defined a stochastic process and used equations and Python to compare the paths and time-specific distributions of four processes.
Specifying a stochastic process requires a time index set, a state space, and dependence across times. Cumulative counts and positions remain dependent across time even when constructed from independent increments. When reading a simulation plot, distinguish following one path from examining the distribution at a fixed time. The next article develops this distinction through sample paths and finite-dimensional distributions.
References
- Shalizi, C. R., Stochastic Processes, Chapter 1 (linked above): stochastic processes and sample paths.
- MIT OpenCourseWare, Lecture 14: The Poisson Process (linked above): counting processes and interarrival times.
- NumPy, Random Generator : random-number generation. The same seed does not guarantee identical results across library versions.