Skip to content

Instantly share code, notes, and snippets.

@viadean
Created February 8, 2025 14:41
Show Gist options
  • Save viadean/b4a608d62232458b42023def36523da0 to your computer and use it in GitHub Desktop.
Save viadean/b4a608d62232458b42023def36523da0 to your computer and use it in GitHub Desktop.
Wiener Square Expectation Rule | Mathematical Finance and Computational Methods
import numpy as np
import matplotlib.pyplot as plt
# Parameters
dt = 0.01 # Small time step
T = 1.0 # Total time
N = int(T / dt) # Number of steps
num_paths = 5 # Number of random paths to simulate
# Simulate Wiener process paths
np.random.seed(42) # For reproducibility
dW = np.sqrt(dt) * np.random.randn(num_paths, N) # dW = ξ sqrt(dt)
W = np.cumsum(dW, axis=1) # Compute Wiener process by summing increments
# Compute dW^2 and its expectation (should be close to dt)
dW_squared = dW**2
expected_dW_squared = np.mean(dW_squared, axis=0) # Average over paths
# Plot Wiener process realizations
plt.figure(figsize=(12, 5))
# Wiener process paths
plt.subplot(1, 2, 1)
for i in range(num_paths):
plt.plot(np.linspace(0, T, N), W[i], alpha=0.7)
plt.xlabel("Time")
plt.ylabel("$W(t)$")
plt.title("Sample Paths of Wiener Process")
# Expectation of dW^2
plt.subplot(1, 2, 2)
plt.plot(np.linspace(dt, T, N), expected_dW_squared, label=r"$\mathbb{E}[dW^2]$")
plt.axhline(dt, color="r", linestyle="--", label="Expected: $dt$")
plt.xlabel("Time")
plt.ylabel("$\mathbb{E}[dW^2]$")
plt.title("Verification of $\mathbb{E}[dW^2] = dt$")
plt.legend()
plt.tight_layout()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment