Generating and Visualizing Stochastic Processes with Python
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.
Book: Theory and Practice of Stochastic Processes
Chapter 1: Foundations of Stochastic Processes
Overview
We generate random walks, Brownian motion, and Poisson processes with NumPy. In addition to sample paths, we compare fixed-time distributions, means, and variances with theory. We also distinguish what is reproduced exactly on a time grid from what is only a plotting interpolation.
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
import platform
import sys
from pathlib import Path
from pprint import pprint
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import font_manager
from matplotlib.ticker import FuncFormatter, MaxNLocator
import numpy as np
import scipy
from scipy import stats
from IPython.display import Math, SVG, display
%matplotlib inline
def sig3(value):
"""数値を有効数字3桁の表示用文字列にする。"""
return format(float(value), '#.3g').removesuffix('.')
np.set_printoptions(formatter={'float_kind': sig3}, linewidth=100)
# 日本語フォントを選び、SVGに文字の輪郭を埋め込む。
font_names = {font.name for font in font_manager.fontManager.ttflist}
for candidate in ['Hiragino Sans', 'Noto Sans CJK JP', 'IPAexGothic', 'YuGothic']:
if candidate in font_names:
plt.rcParams['font.family'] = candidate
break
plt.rcParams.update({
'font.size': 11,
'axes.spines.top': False,
'axes.spines.right': False,
'axes.unicode_minus': False,
'svg.fonttype': 'path',
'svg.hashsalt': 'stochastic-103',
})
# Notebookのフォルダー、またはリポジトリ直下から実行する。
notebook_dir = Path.cwd()
if (notebook_dir / 'pyproject.toml').is_file():
notebook_dir /= 'series/stochastic-processes/103'
figure_dir = notebook_dir / '103_nb_files'
figure_dir.mkdir(parents=True, exist_ok=True)
def save_figure(fig, filename):
# 目盛りの小数も3桁にそろえる。文字列の目盛りはそのまま使う。
formatter = FuncFormatter(
lambda value, _: str(int(value)) if float(value).is_integer() else sig3(value)
)
for ax in fig.axes:
if ax.xaxis.get_converter() is None and ax.get_xscale() == 'linear':
ax.xaxis.set_major_formatter(formatter)
if ax.yaxis.get_converter() is None and ax.get_yscale() == 'linear':
ax.yaxis.set_major_formatter(formatter)
path = figure_dir / filename
fig.savefig(path, format='svg', bbox_inches='tight', metadata={'Date': None})
plt.close(fig)
display(SVG(filename=str(path)))
print('環境名: wa-src(3.14.6)')
print(f'Python: {platform.python_version()}')
print(f'OS: {platform.system()} / {platform.machine()}')
print(f'NumPy: {np.__version__}, SciPy: {scipy.__version__}')
print(f'Matplotlib: {matplotlib.__version__}')
print(f'画像ディレクトリ: {figure_dir.name}')
assert sys.version_info[:3] == (3, 14, 6), '指定のPython環境を選択すること'
環境名: wa-src(3.14.6)
Python: 3.14.6
OS: Darwin / arm64
NumPy: 2.4.6, SciPy: 1.18.1
Matplotlib: 3.11.2
画像ディレクトリ: 103_nb_files
1. Array Axes and Random-Number Generation
A stochastic process $\{X_t\}_{t\in T}$ assigns a random variable to each time. The time series from one realization is a sample path. Here we generate $M$ independent paths and store values at times $t_0,\ldots,t_n$ in the matrix $\mathbf{X}$.
$$ \mathbf{X}\in\mathbb{R}^{M\times(n+1)},\qquad X_{r,k}=X_{t_k}^{(r)}. $$
The slice X[r, :] is one path, while X[:, k] contains samples at a fixed time. Compute means at each time with axis=0. These differ from the time average along one path.
We use default_rng for random-number generation. Recreating a generator with the same seed produces the same sequence, so resetting the same seed for every path would duplicate paths. Instead, we create one generator per process and generate samples together. See NumPy’s guide to random sampling
.
# 同一シードの再現性を、小さな配列で確認する。
sample_a = np.random.default_rng(103).normal(size=4)
sample_b = np.random.default_rng(103).normal(size=4)
np.testing.assert_array_equal(sample_a, sample_b)
pprint(sample_a)
print('同じシードから得た配列は一致した。')
array([1.10, -1.28, 0.648, -1.20])
同じシードから得た配列は一致した。
2. A Symmetric Random Walk
Let independent increments $\xi_k$ take values $+1,-1$ with probability $1/2$ each. Starting from $S_0=0$,
$$ S_n=\sum_{k=1}^n\xi_k,\qquad \mathbb{E}[\xi_k]=\frac12-\frac12=0,\qquad \operatorname{Var}(\xi_k)=\mathbb{E}[\xi_k^2]-0^2=1. $$
Linearity of expectation and independent increments give
$$ \begin{aligned} \mathbb{E}[S_n]&=\sum_{k=1}^n\mathbb{E}[\xi_k]=0,\\ \operatorname{Var}(S_n) &=\sum_{k=1}^n\operatorname{Var}(\xi_k) +2\sum_{i\lt j}\operatorname{Cov}(\xi_i,\xi_j)=n. \end{aligned} $$
If $K$ counts the occurrences of $+1$, then $K\sim\operatorname{Bin}(n,1/2)$ and $S_n=K-(n-K)=2K-n$. The endpoint distribution is therefore
$$ \mathbb{P}(S_n=s)=\binom{n}{(n+s)/2}2^{-n} \quad(s=-n,-n+2,\ldots,n) $$
When $n$ is even, the endpoint must also be even. Check this discrete distribution before comparing it with a continuous normal density.
rng_rw = np.random.default_rng(10301)
n_paths, n_steps = 6000, 160
increments = rng_rw.choice([-1, 1], size=(n_paths, n_steps))
walk = np.column_stack([np.zeros(n_paths, dtype=int), increments.cumsum(axis=1)])
steps = np.arange(n_steps + 1)
endpoints = np.arange(-n_steps, n_steps + 1, 2)
theory_pmf = stats.binom.pmf((endpoints + n_steps) // 2, n_steps, 0.500)
counts = np.bincount((walk[:, -1] + n_steps) // 2, minlength=n_steps + 1)
pprint({'配列の形': walk.shape,
'終点の平均': sig3(walk[:, -1].mean()),
'終点の不偏分散': sig3(walk[:, -1].var(ddof=1)),
'分散の理論値': n_steps}, sort_dicts=False)
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout='constrained')
axes[0].step(steps, walk[:6].T, where='post', alpha=0.800)
axes[0].set(xlabel='ステップ n', ylabel='位置', title='図1a 6本の標本経路')
axes[1].bar(endpoints, counts / n_paths, width=1.60, label='6000本の終点')
axes[1].plot(endpoints, theory_pmf, 'o', ms=3, label='二項分布による理論値')
axes[1].set(xlim=(-45, 45), xlabel='終点の位置', ylabel='確率',
title='図1b 偶数の位置だけに確率がある')
axes[1].legend()
save_figure(fig, '01_random_walk.svg')
{'配列の形': (6000, 161), '終点の平均': '0.164', '終点の不偏分散': '161', '分散の理論値': 160}
$$ \displaystyle \mathbb{E}[S_{160}]=0,\qquad \operatorname{Var}(S_{160})=160 $$
3. Generate Brownian Motion on a Grid
Standard Brownian motion $B_t$ starts at $B_0=0$, has continuous sample paths and independent increments, and satisfies $B_t-B_s\sim N(0,t-s)$ for $0\le s<t$. On a regular grid $t_k=k\Delta t$, independent $Z_k\sim N(0,1)$ give
$$ \Delta B_k=\sqrt{\Delta t}\,Z_k,\qquad B_{t_k}=\sum_{j=1}^k\Delta B_j $$
In normal, scale is the standard deviation, not the variance. The mean and variance follow as below.
$$ \begin{aligned} \mathbb{E}[B_{t_k}]&=\sum_{j=1}^k\sqrt{\Delta t}\,\mathbb{E}[Z_j]=0,\\ \operatorname{Var}(B_{t_k}) &=\sum_{j=1}^k(\sqrt{\Delta t})^2\operatorname{Var}(Z_j) =k\Delta t=t_k. \end{aligned} $$
The grid-point joint distribution agrees with Brownian motion. The lines joining those points, however, are not the actual path between grid points. A finer grid still cannot reconstruct every detail of a continuous path from finitely many points.
rng_bm = np.random.default_rng(10302)
horizon, n_grid = 2.00, 400
dt = horizon / n_grid
times = np.linspace(0, horizon, n_grid + 1)
d_brownian = rng_bm.normal(scale=np.sqrt(dt), size=(n_paths, n_grid))
brownian = np.column_stack([np.zeros(n_paths), d_brownian.cumsum(axis=1)])
pprint({'刻み幅': sig3(dt), '増分の標準偏差': sig3(np.sqrt(dt)),
'終点の平均': sig3(brownian[:, -1].mean()),
'終点の不偏分散': sig3(brownian[:, -1].var(ddof=1)),
'分散の理論値': sig3(horizon)}, sort_dicts=False)
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout='constrained')
axes[0].plot(times, brownian[:6].T, lw=1)
axes[0].set(xlabel='時刻 t', ylabel='B(t)', title='図2a 格子点を結んだ経路')
axes[1].hist(brownian[:, -1], bins=45, density=True, alpha=0.650, label='終点の標本')
x_grid = np.linspace(-5, 5, 300)
axes[1].plot(x_grid, stats.norm.pdf(x_grid, scale=np.sqrt(horizon)),
color='#c24a36', label='正規分布の密度')
axes[1].set(xlabel='B(2)', ylabel='確率密度', title='図2b 終点の分布')
axes[1].legend()
save_figure(fig, '02_brownian_motion.svg')
{'刻み幅': '0.00500',
'増分の標準偏差': '0.0707',
'終点の平均': '0.0188',
'終点の不偏分散': '1.98',
'分散の理論値': '2.00'}
$$ \displaystyle B_2\sim N(0,2) $$
4. A Poisson Process and Jump Times
For a Poisson process with constant rate $\lambda>0$, counts in disjoint time intervals are independent. The increments over intervals of length $\Delta t$ satisfy
$$ \Delta N_k\sim\operatorname{Poisson}(\lambda\Delta t),\qquad N_{t_k}=\sum_{j=1}^k\Delta N_j. $$
A Poisson variable has mean and variance $\lambda\Delta t$, so the sum of independent increments gives
$$ \mathbb{E}[N_{t_k}]=\sum_{j=1}^k\lambda\Delta t=\lambda t_k, \qquad \operatorname{Var}(N_{t_k})=\sum_{j=1}^k\lambda\Delta t=\lambda t_k. $$
At the endpoint, $\mathbb{P}(N_T=j)=e^{-\lambda T}(\lambda T)^j/j!$. An interval can contain several events, so increments must not be restricted to 0 or 1.
Counts on a grid do not reveal arrival times within each interval. If arrival times are needed, sum independent waiting times $E_j\sim\operatorname{Exp}(\lambda)$ to obtain $T_j=E_1+\cdots+E_j$. This yields the right-continuous path $N_t=\sum_j\mathbf{1}_{\{T_j\le t\}}$. For the exponential distribution, scale is the mean waiting time $1/\lambda$.
rng_poisson = np.random.default_rng(10303)
rate = 3.00
poisson_increments = rng_poisson.poisson(rate * dt, size=(n_paths, n_grid))
counts_process = np.column_stack([
np.zeros(n_paths, dtype=int), poisson_increments.cumsum(axis=1)
])
# 別の1経路では、格子を使わず到着時刻を生成する。
rng_arrival = np.random.default_rng(10304)
arrivals = []
arrival_time = rng_arrival.exponential(scale=1 / rate)
while arrival_time <= horizon:
arrivals.append(arrival_time)
arrival_time += rng_arrival.exponential(scale=1 / rate)
arrival_array = np.asarray(arrivals)
coarse_times = np.linspace(0, horizon, 9)
coarse_counts = np.searchsorted(arrival_array, coarse_times, side='right')
event_times = np.r_[0, arrival_array, horizon]
event_counts = np.r_[0, np.arange(1, len(arrivals) + 1), len(arrivals)]
pprint({'到着時刻': [sig3(t) for t in arrivals],
'終点の平均': sig3(counts_process[:, -1].mean()),
'終点の不偏分散': sig3(counts_process[:, -1].var(ddof=1)),
'平均・分散の理論値': sig3(rate * horizon)}, sort_dicts=False)
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout='constrained')
axes[0].step(event_times, event_counts, where='post', label='到着時刻から描いた経路')
axes[0].step(coarse_times, coarse_counts, where='post', linestyle='--',
label='同じ経路を粗い格子で観測')
axes[0].set(xlabel='時刻 t', ylabel='累積件数', title='図3a 格子間の到着時刻は失われる')
axes[0].yaxis.set_major_locator(MaxNLocator(integer=True))
axes[0].legend(fontsize=9)
k_values = np.arange(counts_process[:, -1].max() + 1)
empirical_pmf = np.bincount(counts_process[:, -1], minlength=len(k_values)) / n_paths
axes[1].bar(k_values, empirical_pmf, alpha=0.650, label='終点の標本')
axes[1].plot(k_values, stats.poisson.pmf(k_values, rate * horizon), 'o',
color='#c24a36', label='ポアソン分布の確率')
axes[1].set(xlabel='N(2)', ylabel='確率', title='図3b 終点の分布')
axes[1].xaxis.set_major_locator(MaxNLocator(integer=True))
axes[1].legend()
save_figure(fig, '03_poisson_process.svg')
{'到着時刻': ['0.754', '0.906', '1.17', '1.53'],
'終点の平均': '6.02',
'終点の不偏分散': '6.04',
'平均・分散の理論値': '6.00'}
$$ \displaystyle N_2\sim\operatorname{Poisson}(6) $$
5. Check Means and Variances over the Full Time Range
Fix time $t$ and calculate the mean and unbiased variance from $M$ independent paths.
$$ \bar X_t=\frac1M\sum_{r=1}^M X_t^{(r)},\qquad \widehat v_t=\frac1{M-1}\sum_{r=1}^M(X_t^{(r)}-\bar X_t)^2. $$
Independence gives $\operatorname{Var}(\bar X_t)=v_t/M$ for the variance of the sample mean. The band in Figure 4 is $\mu_t\pm1.96\sqrt{v_t/M}$, centered on the theoretical mean $\mu_t$. It approximates the variability of the sample mean at each time for a large sample. It is neither a range for individual paths nor a simultaneous band over all times. At $t=0$, all paths equal 0, so the width is also 0.
Checking both means and variances can reveal implementation errors that a few paths alone may hide. In particular, incorrectly using $\Delta t Z_k$ for Brownian increments gives endpoint variance $n(\Delta t)^2=T\Delta t$, which approaches zero as the step size decreases.
models = [
('ランダムウォーク', steps, walk, np.zeros_like(steps), steps),
('ブラウン運動', times, brownian, np.zeros_like(times), times),
('ポアソン過程', times, counts_process, rate * times, rate * times),
]
fig, axes = plt.subplots(3, 2, figsize=(11, 9), layout='constrained')
for row, (label, grid, paths, mean_theory, var_theory) in enumerate(models):
mean_sample = paths.mean(axis=0)
variance_sample = paths.var(axis=0, ddof=1)
half_width = 1.96 * np.sqrt(var_theory / n_paths)
axes[row, 0].fill_between(grid, mean_theory - half_width,
mean_theory + half_width, alpha=0.200,
label='各時刻の近似95%変動幅')
axes[row, 0].plot(grid, mean_sample, label='標本平均')
axes[row, 0].plot(grid, mean_theory, '--', color='black', label='理論平均')
axes[row, 1].plot(grid, variance_sample, label='不偏分散')
axes[row, 1].plot(grid, var_theory, '--', color='black', label='理論分散')
for col, quantity in enumerate(['平均', '分散']):
axes[row, col].set(title=f'{label}:{quantity}', xlabel='時刻 / ステップ')
axes[row, col].legend(fontsize=8)
fig.suptitle('図4 独立な6000経路から計算した平均・分散')
save_figure(fig, '04_moments.svg')
# 正しい増分と誤った増分を、同じ標準正規乱数から比較する。
wrong_terminal = (np.sqrt(dt) * d_brownian).sum(axis=1)
pprint({'正しい終点分散': sig3(brownian[:, -1].var(ddof=1)),
'誤った終点分散': sig3(wrong_terminal.var(ddof=1)),
'誤った実装の理論分散 TΔt': sig3(horizon * dt)}, sort_dicts=False)
assert np.all(np.isin(np.diff(walk, axis=1), [-1, 1]))
assert np.all(np.diff(counts_process, axis=1) >= 0)
assert np.allclose(np.diff(brownian, axis=1), d_brownian)
assert all(np.all(paths[:, 0] == 0) for paths in [walk, brownian, counts_process])
print('増分と初期値の構成を確認した。')
{'正しい終点分散': '1.98', '誤った終点分散': '0.00991', '誤った実装の理論分散 TΔt': '0.0100'}
増分と初期値の構成を確認した。
In Figure 4, the random-walk and Brownian means stay near zero, while their variances grow linearly with time. Both the mean and variance increase for the Poisson process. Finite samples leave differences between sample estimates and theory. A small difference does not by itself mean the generation method is wrong.
Conclusion
This article generated three stochastic processes by summing independent increments and checked their paths, endpoint distributions, means, and variances.
Use discrete increments for a random walk, normal increments with standard deviation $\sqrt{\Delta t}$ for Brownian motion, and Poisson increments with mean $\lambda\Delta t$ for a Poisson process. For the two continuous-time examples, distinguish grid-point distributions from the drawing between points. Checking means and variances helps catch incorrect array axes or time-step scaling.