Python蒙特卡洛模拟 # Python蒙特卡洛模拟 - 完整代码示例# 蒙特卡洛方法通过随机采样解决数值问题广泛应用于金融工程、物理模拟和优化import numpy as npimport matplotlib.pyplot as pltfrom scipy import stats# 1. 蒙特卡洛估算圆周率 Pi# 基本原理在单位正方形内随机投点统计落在内切圆中的比例# 圆面积/正方形面积 π/4因此 π ≈ 4 * (圆内点数/总点数)np.random.seed(42) # 固定随机种子保证可重复性n_points 10000 # 采样点数# 在 [-1, 1] x [-1, 1] 正方形内生成均匀随机点x np.random.uniform(-1, 1, n_points)y np.random.uniform(-1, 1, n_points)# 判断点是否在单位圆内x² y² 1inside_circle x**2 y**2 1pi_estimate 4 * np.sum(inside_circle) / n_pointsprint(f估算的 Pi 值: {pi_estimate:.6f})print(f真实 Pi 值: {np.pi:.6f})print(f误差: {abs(pi_estimate - np.pi):.6f})# 2. 蒙特卡洛数值积分计算 f(x) x² 在 [0, 1] 上的积分# 解析解为 ∫₀¹ x² dx 1/3 ≈ 0.3333def mc_integrate(f, a, b, n50000):使用蒙特卡洛方法计算函数 f 在 [a,b] 上的定积分x_samples np.random.uniform(a, b, n) # 在区间内均匀采样y_samples f(x_samples)# 积分值 区间长度 * 函数值的平均值integral (b - a) * np.mean(y_samples)return integralf_square lambda x: x**2result mc_integrate(f_square, 0, 1)print(f\n蒙特卡洛积分 ∫₀¹ x² dx {result:.6f} (理论值: 0.333333))# 3. 误差分析与收敛性# 蒙特卡洛方法的误差与 1/√n 成正比增加采样点可降低误差def estimate_error(n_trials100):重复实验评估蒙特卡洛方法的误差estimates []for _ in range(n_trials):est mc_integrate(f_square, 0, 1, n5000)estimates.append(est)return np.std(estimates), np.mean(estimates)std_err, mean_val estimate_error()print(f重复实验均值: {mean_val:.6f}, 标准差: {std_err:.6f})print(f95% 置信区间: [{mean_val - 1.96*std_err:.6f}, {mean_val 1.96*std_err:.6f}])# 4. 金融模拟期权定价简化欧式期权# 几何布朗运动模拟资产价格路径def simulate_asset_price(S0, mu, sigma, T, n_steps, n_paths10000):使用几何布朗运动模拟资产价格路径dt T / n_steps# 生成标准正态随机数矩阵z np.random.normal(0, 1, (n_paths, n_steps))# 计算价格路径向量化版本returns (mu - 0.5 * sigma**2) * dt sigma * np.sqrt(dt) * zprice_paths S0 * np.exp(np.cumsum(returns, axis1))return price_paths# 模拟参数S0, K, mu, sigma, T 100, 105, 0.05, 0.2, 1.0 # 初始价、行权价、收益率、波动率、到期时间n_sim 50000 # 模拟路径数# 模拟到期日资产价格z_final np.random.normal(0, 1, n_sim)ST S0 * np.exp((mu - 0.5 * sigma**2) * T sigma * np.sqrt(T) * z_final)# 欧式看涨期权 payoff max(ST - K, 0)payoff np.maximum(ST - K, 0)# 期权价格 折现后 payoff 的期望值option_price np.exp(-mu * T) * np.mean(payoff)print(f\n欧式看涨期权价格: {option_price:.4f})print(f实值期权比例: {np.mean(ST K)*100:.1f}%)# 5. 方差减小技术对偶变量法# 通过使用负相关的随机变量对来降低方差def antithetic_option_pricing(S0, K, mu, sigma, T, n_sim25000):使用对偶变量法降低期权定价方差z np.random.normal(0, 1, n_sim)# 生成一对负相关的随机变量ST1 S0 * np.exp((mu - 0.5*sigma**2)*T sigma*np.sqrt(T)*z)ST2 S0 * np.exp((mu - 0.5*sigma**2)*T sigma*np.sqrt(T)*(-z))payoff1 np.maximum(ST1 - K, 0)payoff2 np.maximum(ST2 - K, 0)# 使用两个路径的平均值payoff_avg (payoff1 payoff2) / 2price np.exp(-mu * T) * np.mean(payoff_avg)price_std np.std(payoff_avg) / np.sqrt(n_sim)return price, price_stdprice_av, std_av antithetic_option_pricing(S0, K, mu, sigma, T)print(f\n对偶变量法期权价格: {price_av:.4f}, 标准差: {std_av:.4f})print(f方差减小比例: {(1 - (std_av / (np.std(payoff)/np.sqrt(n_sim)))**2)*100:.1f}%)print(\n蒙特卡洛模拟小结通过随机采样解决确定性问题)print(核心在于收敛速度 O(1/√n) 和方差减小技术的应用)