开启左侧

蒙特卡洛模拟的代码

发表于:昨天 15:19 25
  1. import numpy as np
  2. import matplotlib.pyplot as plt

  3. def monte_carlo_simulation(
  4.     S0: float,
  5.     mu: float,
  6.     sigma: float,
  7.     T: float,
  8.     n_sim: int,
  9.     n_steps: int
  10. ) -> np.ndarray:
  11.     """
  12.     使用几何布朗运动(GBM)对资产价格进行蒙特卡洛模拟。

  13.     参数
  14.     ----------
  15.     S0 : float
  16.         初始资产价格。
  17.     mu : float
  18.         年化预期收益率(无风险利率或历史漂移率)。
  19.     sigma : float
  20.         年化波动率。
  21.     T : float
  22.         模拟期限(年)。
  23.     n_sim : int
  24.         模拟路径数量。
  25.     n_steps : int
  26.         每条路径的时间步数。

  27.     返回
  28.     -------
  29.     paths : np.ndarray, shape (n_sim, n_steps + 1)
  30.         模拟价格矩阵,每一行是一条路径,每一列是一个时间点。
  31.     """

  32.     dt = T / n_steps
  33.     # 布朗运动的漂移项修正(伊藤引理)
  34.     drift = (mu - 0.5 * sigma ** 2) * dt
  35.     # 随机冲击的标准差
  36.     vol = sigma * np.sqrt(dt)

  37.     # 生成标准正态随机数 (n_sim, n_steps)
  38.     Z = np.random.standard_normal((n_sim, n_steps))

  39.     # 对数收益率
  40.     log_returns = drift + vol * Z

  41.     # 累积对数收益率
  42.     log_returns_cum = np.cumsum(log_returns, axis=1)

  43.     # 将初始价格添加到第一列,构建完整路径
  44.     paths = np.zeros((n_sim, n_steps + 1))
  45.     paths[:, 0] = S0
  46.     paths[:, 1:] = S0 * np.exp(log_returns_cum)

  47.     return paths


  48. # --------------
  49. # 示例使用与可视化
  50. # --------------
  51. if __name__ == "__main__":
  52.     # 参数设置
  53.     S0 = 100      # 初始价格
  54.     mu = 0.05     # 预期收益率 5%
  55.     sigma = 0.2   # 波动率 20%
  56.     T = 1.0       # 模拟1年
  57.     n_sim = 1000  # 1000条路径
  58.     n_steps = 252 # 252个交易日

  59.     # 运行模拟
  60.     price_paths = monte_carlo_simulation(S0, mu, sigma, T, n_sim, n_steps)

  61.     # 期末价格统计
  62.     final_prices = price_paths[:, -1]
  63.     print(f"期末价格均值: {final_prices.mean():.2f}")
  64.     print(f"期末价格标准差: {final_prices.std():.2f}")
  65.     print(f"5% VaR (历史法): {S0 - np.percentile(final_prices, 5):.2f}")

  66.     # 可视化部分路径
  67.     plt.figure(figsize=(10, 6))
  68.     plt.plot(price_paths.T[:, :100], alpha=0.1, color='blue')
  69.     plt.axhline(y=S0, linestyle='--', color='red', alpha=0.5, label='Initial Price')
  70.     plt.title("Monte Carlo Simulation of Asset Prices (GBM)")
  71.     plt.xlabel("Time Steps")
  72.     plt.ylabel("Price")
  73.     plt.legend()
  74.     plt.show()

  75.     # 期末价格分布直方图
  76.     plt.figure(figsize=(8, 5))
  77.     plt.hist(final_prices, bins=50, alpha=0.7, color='skyblue', edgecolor='black')
  78.     plt.axvline(x=S0, linestyle='--', color='red', label='Initial Price')
  79.     plt.title("Distribution of Final Prices")
  80.     plt.xlabel("Price")
  81.     plt.ylabel("Frequency")
  82.     plt.legend()
  83.     plt.show()
复制代码


收藏
送赞
分享
123.png
345.png

发表回复