期权定价的概念
利用数学模型,如二项式模型计算期权的公允价值,价格由内在价值和时间价值组成,受标的资产价格、波动率、到期日、行权价、无风险利率影响,核心是基于对冲和无套利定价原理。
import numpy as np
import matplotlib.pyplot as plt
# === 1. 上帝参数 ===
K = 100 # 你的行权价 (比如挖矿成本)
premium = 10 # 期权费 (你买这个权利花的定金,比如建设矿山的沉没成本)
# 生成一堆可能的市场价格 (从 50 到 150)
S = np.linspace(50, 150, 100)
# === 2. 核心逻辑 (这就是 ReLU !) ===
# Payoff (行权收益): 只看赚不赚,不看本金
# 如果 S < K,收益是 0;如果 S > K,收益是 S - K
payoff = np.maximum(0, S - K)
# Profit (净利润): 减去你一开始付的定金
profit = payoff - premium
# === 3. 画图 (曲棍球棒) ===
plt.figure(figsize=(10, 6))
# 画出"零轴"
plt.axhline(0, color='black', lw=1)
# 画出"行权收益" (Payoff) - 纯正的曲棍球棒
plt.plot(S, payoff, 'b-', linewidth=3, label='Payoff (Value of Option)')
# 画出"净利润" (Profit) - 考虑了成本的虚线
plt.plot(S, profit, 'r--', linewidth=2, label='Net Profit (Minus Cost)')
# === 视觉装饰 ===
plt.fill_between(S, profit, 0, where=(profit > 0), color='green', alpha=0.1, label='Profit Zone')
plt.fill_between(S, profit, 0, where=(profit < 0), color='red', alpha=0.1, label='Loss Zone')
plt.title(f"Call Option Payoff Diagram (Strike Price K={K})")
plt.xlabel("Future Asset Price (S)")
plt.ylabel("Profit / Loss")
plt.legend()
plt.grid(True)
# 标出拐点 (K)
plt.annotate('Strike Price (K)', xy=(K, 0), xytext=(K+10, 10),
arrowprops=dict(facecolor='black', shrink=0.05))
plt.show()数学模型
随机过程
几何布朗运动(Geometric Brownian Motion)
适用于股票,按照百分比变化,保证价格永远是正数,具有复利效应。
这是金融学最经典的假设。它假设价格变化是连续的,且服从正态分布。
数学公式:
$dS_t = \mu S_t dt + \sigma S_t dW_t$
$St$:当前价格
$μ$:漂移项 (长期趋势,比如通胀)
$σ$:波动率 (震荡幅度)
$dWt$:维纳过程 (真随机噪音,布朗运动)
CS视角:就是一个带有随机因子的
Update()函数,每一帧都在当前位置基础上加一个随机偏移。
确定的趋势(Drift)+随机的扰动(Shock)+原则(Geometric)
这是 GBM 的微分方程形式,你是 CS 背景,把它看作是每一帧 (Frame) 的更新逻辑:
$$ \frac{dS_t}{S_t} = \underbrace{\mu dt}{\text{确定的趋势}} + \underbrace{\sigma dW_t}{\text{随机的扰动}} $$
我们像拆代码一样拆解它:
- $dS_t/S_t$:收益率(百分比变化)。
- 为什么除以 $S_t$?因为价格越高,波动的绝对值越大(1000块跌1%是10块,10块跌1%是1毛)。我们要模拟的是“幅度”。
- $dt$:时间步长。
- 比如你想模拟10年,每一步是一天,那 $dt = 1/365$。
- $\mu$ (Mu):漂移率 (Drift)。
- 预期的年化收益率。比如铜价长期看涨 5%,$\mu = 0.05$。这是“醉汉爬山”的坡度。
- $\sigma$ (Sigma):波动率 (Volatility)。
- 这就是之前说的“熵”。$\sigma$ 越大,那个醉汉醉得越厉害,步子晃得越宽。
- $dW_t$:维纳过程 (Wiener Process)。
- 这是全公式里唯一的随机源。
- 在代码里,它就是一个服从正态分布 $N(0, dt)$ 的随机数。
在计算机里跑模拟时,我们不能用微分 ($d$),要用差分 ($\Delta$)。
根据 伊藤引理 (Itō's Lemma) (不管是啥,先不管推导,只记结论),上面的公式在离散时间下会变成这行代码:
$$ S_{t+1} = S_t \cdot \exp \left( (\mu - \frac{1}{2}\sigma^2)\Delta t + \sigma \sqrt{\Delta t} Z \right) $$
- 注:那个 $-\frac{1}{2}\sigma^2$ 是一个数学上的修正项,不用深究,照写就行。
- $Z$:一个标准正态分布随机数(均值0,方差1)。
import numpy as np
import matplotlib.pyplot as plt
# === 1. 设定参数 (上帝参数) ===
S0 = 100 # 初始价格 (比如现在的铜价)
mu = 0.05 # 预期年化收益率 (5%)
sigma = 0.2 # 波动率 (20%,越大概率越狂野)
T = 1.0 # 模拟时间 (1年)
dt = 1/252 # 时间步长 (假设一年252个交易日)
N = int(T/dt) # 总步数
# === 2. 模拟一条路径 (造一个宇宙) ===
# 生成 N 个符合正态分布的随机数 (这就是那个 dW)
Z = np.random.normal(0, 1, N)
# 初始化价格数组
prices = np.zeros(N+1)
prices[0] = S0
# === 3. 核心公式循环 (虽然numpy可以向量化,但为了理解逻辑我们写循环) ===
for t in range(1, N+1):
# 这一行就是 GBM 的离散公式
drift = (mu - 0.5 * sigma**2) * dt
shock = sigma * np.sqrt(dt) * Z[t-1]
# 今天的价格 = 昨天的价格 * e^(趋势 + 随机)
prices[t] = prices[t-1] * np.exp(drift + shock)
# === 4. 画图 ===
plt.plot(prices)
plt.title(f"Geometric Brownian Motion Simulation (Sigma={sigma})")
plt.xlabel("Days")
plt.ylabel("Price")
plt.grid(True)
plt.show()年化5%并不意味着100->105,而是说如果有 10,000 个平行宇宙,所有宇宙的最终价格加起来取平均值,是 105。
漂移率 (μ) 决定了长期的命运(只要时间足够长,正收益总会显现)。
波动率 (σ) 决定了短期的命运(短期内,运气比努力重要)。
import numpy as np
import matplotlib.pyplot as plt
# === 参数 ===
S0 = 100
mu = 0.05 # 期望涨 5%
sigma = 0.2 # 波动 20%
T = 1.0
dt = 1/252
N = int(T/dt)
num_paths = 50 # 我们这次生成 50 个平行宇宙!
# === 模拟 (向量化编程,一次生成50列) ===
# 形状是 (N, num_paths)
Z = np.random.normal(0, 1, (N, num_paths))
# 初始化价格矩阵
prices = np.zeros((N+1, num_paths))
prices[0] = S0
# 循环生成
for t in range(1, N+1):
drift = (mu - 0.5 * sigma**2) * dt
shock = sigma * np.sqrt(dt) * Z[t-1]
prices[t] = prices[t-1] * np.exp(drift + shock)
# === 画图 ===
plt.figure(figsize=(10, 6))
# 画出所有 50 条细线
plt.plot(prices, lw=1, alpha=0.6)
# 画出理论期望值(完美的 5% 上涨线)
expected_path = S0 * np.exp(mu * np.linspace(0, T, N+1))
plt.plot(expected_path, 'k--', lw=3, label='Expected Return (5%)')
plt.title(f"50 Monte Carlo Paths (Mu=0.05, Sigma=0.2)")
plt.xlabel("Days")
plt.ylabel("Price")
plt.legend()
plt.grid(True)
plt.show()--``[1;36m Cell [1;32mIn[3], line 41[1;36m[0m [1;33m plt.show()--``[0m [1;37m ^[0m [1;31mSyntaxError[0m[1;31m:[0m invalid syntax
均值回归模型(Ornstein-Uhlenbeck Process)
$$dX_t = \underbrace{\theta(\mu - X_t)dt}{\text{橡皮筋拉力}} + \underbrace{\sigma dW_t}{\text{随机扰动}}$$
请看第一项 $\theta(\mu - X_t)$,这是灵魂所在:
- $\mu$ (Mu):锚点。 长期来看,铜价应该在 60,000 左右。
- $X_t$:当前位置。
- $\mu - X_t$:偏差距离。 离家越远,拉力越大。
- $\theta$ (Theta):橡皮筋的硬度(回归速度)。 $\theta$ 越大,价格越难跑偏,刚跑出去就被拽回来了。
有一根看不见的橡皮筋进行约束
适用于大宗商品、汇率、利率
股票可能会涨到天上去,但矿产(铜、金)不会。价格太高了产能就会增加,把价格打下来;价格太低了矿企倒闭,价格又会回去。
- 核心逻辑:价格像被一根橡皮筋拉着,总是试图回到长期的平均成本线。
价格太高 → 产能过剩 → 价格下跌;价格太低 → 矿山倒闭 → 价格上涨
import numpy as np
import matplotlib.pyplot as plt
# === 1. 上帝参数 ===
S0 = 100 # 初始价格
T = 2.0 # 模拟2年
dt = 1/252 # 每天一步
N = int(T/dt)
# GBM 参数 (无脑上涨)
mu_gbm = 0.1 # 期望年化 10%
sigma = 0.3 # 波动率 30%
# OU 参数 (有橡皮筋)
mu_ou = 100 # 长期均值 (锚点设在 100)
theta = 2.0 # 回归速度 (橡皮筋挺硬的)
sigma_ou = 0.3 # 同样的波动率
# === 2. 初始化 ===
time = np.linspace(0, T, N+1)
gbm_path = np.zeros(N+1); gbm_path[0] = S0
ou_path = np.zeros(N+1); ou_path[0] = S0
# 生成随机噪音 (两个模型共用同一套运气,方便对比)
Z = np.random.normal(0, 1, N)
# === 3. 模拟循环 ===
for t in range(N):
# --- 模型 A: GBM (只管冲) ---
# S_new = S_old * exp(...)
drift_gbm = (mu_gbm - 0.5 * sigma**2) * dt
shock = sigma * np.sqrt(dt) * Z[t]
gbm_path[t+1] = gbm_path[t] * np.exp(drift_gbm + shock)
# --- 模型 B: OU (带橡皮筋) ---
# S_new = S_old + 拉力 + 随机
# 欧拉离散化: dS = theta*(mu - S)*dt + sigma*dW
pull = theta * (mu_ou - ou_path[t]) * dt
shock_ou = sigma_ou * np.sqrt(dt) * Z[t] # 这里简化处理,直接加
ou_path[t+1] = ou_path[t] + pull + shock_ou * ou_path[t] # 乘S[t]是为了让波动率按比例
# === 4. 画图对比 ===
plt.figure(figsize=(12, 6))
plt.plot(time, gbm_path, 'r-', alpha=0.6, label='GBM (Stock-like: Drifts away)')
plt.plot(time, ou_path, 'b-', linewidth=2, label='OU Process (Commodity-like: Mean Reverting)')
# 画出 OU 的锚点线
plt.axhline(mu_ou, color='black', linestyle='--', label=f'Long-term Mean ({mu_ou})')
plt.title("Physics Engine Comparison: GBM vs. Ornstein-Uhlenbeck")
plt.xlabel("Years")
plt.ylabel("Price")
plt.legend()
plt.grid(True)
plt.show()定价模型
Black-Scholes-Merton(BSM)模型
期权价格 = (未来的预期收入) - (未来的预期成本)
期权价格 = (未来的预期收入) - (未来的预期成本)
$$C = \underbrace{S_0 \cdot N(d_1)}{\text{你将得到的资产价值}} - \underbrace{K \cdot e^{-rT} \cdot N(d_2)}{\text{你务必支付的成本}}$$
我们像拆代码一样拆解这两个部分:
第一部分:$S_0 \cdot N(d_1)$ —— “收入项”
- $S_0$:当前的矿产/股价。
- $N(d_1)$:这是一个概率系数(0 到 1 之间)。
- 它衡量的是:“在这个资产真的涨上去的那些平行宇宙里,它的平均价值折算回今天是多少?”
- 你可以把它理解为**“资产的有效含金量”**。
第二部分:$K \cdot e^{-rT} \cdot N(d_2)$ —— “成本项”
- $K$:行权价(比如你的挖矿成本)。
- $e^{-rT}$:折现因子。
- 未来的 100 块钱不如现在的 100 块钱值钱。这个因子把未来的成本打个折,算出“现值”。
- $N(d_2)$:行权概率。
- 这代表了**“你在到期日那天,真的会去挖矿(也就是 $S > K$)的概率是多少?”**
- 如果 $N(d_2) = 0.1$,说明只有 10% 的概率你会开工,90% 的概率你会停工烂在那。
import numpy as np
from scipy.stats import norm
def black_scholes_call(S, K, T, r, sigma):
"""
S: 当前标的价格
K: 行权价格 (成本)
T: 距离到期时间 (年)
r: 无风险利率 (比如 0.03)
sigma: 波动率 (比如 0.2)
"""
# 1. 计算 d1 和 d2 (中间变量,不用深究推导)
d1 = (np.log(S / K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T))
d2 = d1 - sigma * np.sqrt(T)
# 2. 查表 (计算正态分布的累积概率)
# norm.cdf 就是那个 N(...) 函数
call_price = S * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2)
return call_price
# === 测试一下 ===
# 现在的铜价 S=100, 挖矿成本 K=100
# 虽然现在看着没赚没赔,但因为有波动率(0.2)和时间(1年),
# 这张"挖矿许可证"是有价值的!
price = black_scholes_call(S=100, K=100, T=1.0, r=0.05, sigma=0.2)
print(f"BSM模型算出的期权价值: {price:.2f}")BSM模型算出的期权价值: 10.45
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import lognorm
# === 1. 上帝参数 ===
S0 = 100 # 起点
mu = 0.05 # 趋势
sigma = 0.2 # 波动
T = 1.0 # 1年
num_paths = 10000 # 1万个平行宇宙
# === 2. 瞬间生成 10,000 个最终结果 (不用循环,直接公式算终点) ===
# 理论公式:S_T = S0 * exp( (mu - 0.5*sigma^2)*T + sigma*sqrt(T)*Z )
# Z 是 10000 个标准正态分布随机数
Z = np.random.normal(0, 1, num_paths)
final_prices = S0 * np.exp((mu - 0.5 * sigma**2) * T + sigma * np.sqrt(T) * Z)
# === 3. 画图:直方图 vs 理论曲线 ===
plt.figure(figsize=(10, 6))
# A. 画直方图 (模拟结果)
# bins=100 表示把价格切成100份
count, bins, ignored = plt.hist(final_prices, bins=100, density=True,
color='skyblue', alpha=0.7, label='Monte Carlo Simulation')
# B. 画理论曲线 (BSM 依赖的数学真理)
# 创建一个完美的对数正态分布曲线
shape = sigma * np.sqrt(T)
scale = S0 * np.exp((mu - 0.5 * sigma**2) * T)
x = np.linspace(min(final_prices), max(final_prices), 100)
pdf = lognorm.pdf(x, shape, scale=scale)
plt.plot(x, pdf, 'r-', lw=3, label='Theoretical Log-Normal Distribution')
# C. 标出"赚钱区域" (BSM 算的就是这块面积!)
K = 100 # 成本线
plt.axvline(K, color='k', linestyle='--', linewidth=2, label=f'Strike Price (K={K})')
# 给 > K 的部分涂色
# 这块红色的面积,大概对应着 N(d2),即"行权概率"
plt.fill_between(x, 0, pdf, where=(x > K), color='red', alpha=0.3, label='Profit Zone (In-the-Money)')
plt.title(f"Distribution of Final Prices (T={T} Year)\nFrom Chaos (10k Paths) to Order (Bell Curve)")
plt.xlabel("Final Asset Price")
plt.ylabel("Probability Density")
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()如果非要在图上画出 10.45,它其实是**“利润 x 概率”的积分面积**。
- 图片里的红面积:代表的是概率(Probability)。
- 10.45:代表的是价值(Value)。
$$\text{Value} = \int_{100}^{\infty} \underbrace{(S - 100)}{\text{赚的钱}} \times \underbrace{P(S)}{\text{概率(图上的高度)}} dS$$
- 最后还要乘上 $e^{-rT}$(折现因子),因为那是明年的钱,换算成现在的价值会稍微打个折(除以 1.05 左右)。
最小二乘蒙特卡洛(LSM)(Least Squares Monte Carlo)
解决什么痛点:传统的蒙特卡洛只能算一条路跑到黑的情况。但矿主是聪明的,如果第3年铜价大跌,矿主会选择“停工等待”。传统的模拟器不知道什么时候该停。
核心逻辑:它结合了 模拟 (Simulation) 和 回归分析 (Regression)。在模拟的每一步,它都用“最小二乘法”去拟合一个函数,判断:“我现在是把矿挖了换钱划算(行权),还是留着以后挖划算(继续持有)?”
CS视角:这是一个动态规划 (Dynamic Programming) 问题,利用反向归纳法 (Backward Induction) 从未来推导现在。
Step 1: 正向造世 (Forward Pass)
先用物理引擎 (OU/GBM) 生成所有宇宙的完整历史。
数据结构:一个
[5000, 10]的大矩阵(5000个宇宙,10年)。
Step 2: 逆向归纳 (Backward Induction) —— 核心! 我们站在第 9 年(倒数第二天)。 对于每一个宇宙,你都要问自己一个灵魂问题:
“我是现在就把矿挖了换钱(落袋为安),还是再忍一年看看(搏一搏)?”
选项 A:立即行权 (Immediate Exercise)
- 这是已知的。$$ \text{Profit} = S_t - K $$。
选项 B:继续持有 (Continuation Value)
- 这是未知的。因为你不知道第 10 年会发生什么。
Step 3: AI 预测 (The "Least Squares" Magic) 既然不知道未来,LSM 说:“我们用机器学习预测!”
训练集 (X):第 9 年的当前价格。
标签 (Y):第 10 年的折现收益(因为我们是倒着算的,第10年的结果已经知道了)。
训练模型:跑一个线性回归 (Linear Regression)。
model.fit(X, Y)
预测:用模型算出如果我再等一年,理论上能赚多少钱。
Step 4: 决策与更新
如果
立即拿钱 > 预测的等待收益→ 行权! 更新这个宇宙的现金流为现在的钱。如果
立即拿钱 < 预测的等待收益→ 等待! 现金流保持不变(还是未来的钱)。
Step 5: 循环 回到第 8 年,重复 Step 2-4,直到回到第 0 年。
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
# === 1. 准备假数据 (模拟环境) ===
# 假设有 5 个平行宇宙,模拟 3 天 (t=0, 1, 2)
# 价格矩阵 (行=宇宙, 列=时间)
simulations = np.array([
[100, 110, 150], # 宇宙1: 暴涨
[100, 100, 100], # 宇宙2: 横盘
[100, 90, 80 ], # 宇宙3: 暴跌
[100, 105, 120], # 宇宙4: 缓涨
[100, 95, 85 ] # 宇宙5: 缓跌
])
K = 100 # 行权成本
r = 0.05 # 无风险利率
dt = 1 # 时间步长 (假设1年)
discount_factor = np.exp(-r * dt) # 折现因子
# 初始化现金流矩阵 (先把最后一天的行权收益算出来)
# 只有最后一天价格 > K 才有钱,否则是 0
cash_flows = np.maximum(simulations[:, -1] - K, 0)
# === 2. LSM 核心倒推逻辑 ===
# 从倒数第二天 (T-1) 开始,退回到第1天
# simulations.shape[1] 是总天数
T = simulations.shape[1] - 1
print(f"初始(最后一天)现金流: {cash_flows}\n")
for t in range(T - 1, 0, -1):
print(f"--- 正在回溯第 {t} 天 ---")
# A. 拿到当天的价格
prices_t = simulations[:, t]
# B. 找出"价内路径" (In-the-Money)
# 只有当前价格 > K (比如105, 110) 的宇宙,才需要纠结是现在挖还是等
# 如果现在价格是 90 (亏本),那肯定不动,不用算
itm_indices = np.where(prices_t > K)[0]
if len(itm_indices) == 0:
print("没有路径在价内,跳过")
continue
# X: 当天的价格 (Feature)
X_itm = prices_t[itm_indices].reshape(-1, 1) # sklearn要求2D数组
# Y: 这些宇宙对应的"未来"现金流 (折现到今天)
Y_future = cash_flows[itm_indices] * discount_factor
# C. 训练 AI (多项式回归)
# 用 pipeline 组合: 先把 X 变成 [1, x, x^2],再做线性回归
model = make_pipeline(PolynomialFeatures(degree=2), LinearRegression())
model.fit(X_itm, Y_future)
# D. 预测"继续持有价值" (Continuation Value)
continuation_value = model.predict(X_itm)
# E. 现在的行权收益 (Immediate Exercise)
exercise_value = prices_t[itm_indices] - K
# F. 决策:谁大听谁的
# 如果 (现在挖 > 等着),则应该行权
should_exercise = exercise_value > continuation_value
print(f"价内宇宙索引: {itm_indices}")
print(f"预测的等待价值: {continuation_value}")
print(f"立即行权价值: {exercise_value}")
print(f"决策结果(True挖): {should_exercise}")
# G. 更新现金流
# 只有那些决定"现在挖"的宇宙,现金流要被截断更新为 exercise_value
# 决定"等"的宇宙,现金流保持不变 (还是未来的钱 * discount)
# update_indices 是那些真正决定行权的宇宙在总表中的位置
update_indices = itm_indices[should_exercise]
cash_flows[update_indices] = exercise_value[should_exercise]
# 关键点:对于这一步没有行权的宇宙,它们的 cash_flows 应该折现一步吗?
# 在标准算法里,cash_flows 向量里存的永远是"那个宇宙在未来某个最佳时刻拿到的钱"
# 我们只需要在最后总算账时统一折现,或者在每一步循环结束时对所有 cash_flows 乘 discount_factor
# 简便起见,通常在 Y_future 那一步乘一次即可,或者每退一步全员折现。
# 这里为了演示清晰,我们选择在 Y_future 局部折现用于比较,
# 并在循环结束时全员折现准备给下一步用:
cash_flows = cash_flows * discount_factor
# === 3. 最终估值 ===
option_value = np.mean(cash_flows)
print(f"\n最终算出的期权价值 (LSM): {option_value:.4f}")初始(最后一天)现金流: [50 0 0 20 0] --- 正在回溯第 1 天 --- 价内宇宙索引: [0 3] 预测的等待价值: [47.56147123 19.02458849] 立即行权价值: [10 5] 决策结果(True挖): [False False] 最终算出的期权价值 (LSM): 13.3172
机器学习
LSTM(长短期记忆网络)(Long Short-Term Memory)/GRU
- 用途:处理时间序列数据。
- 输入:过去30天的铜价、美元指数、通胀率。
- 输出:预测未来的价格趋势 ($\mu$) 或 波动率 ($\sigma$)。
- 结合点:把 LSTM 预测出来的 $\sigma_t$ 喂给上面的 GBM 或 LSM 模型,这就叫“基于深度学习参数估计的实物期权定价”。
相较于一般神经网络(DNN/CNN),LSTM可以记住重要的内容(如“现在是经济下行时期”),遗忘噪音(如“昨天下午的瞬间波动”)
LSTM 通过三个门(Gates) ——其实就是三个 Sigmoid 函数(0到1的开关)——来控制记忆的读写。
A. 遗忘门 (Forget Gate)
功能:决定要丢弃什么旧信息。
逻辑:f_t = \sigma(W_f \cdot [h_{t-1}, x_t])
CS 翻译:
if (history_info == "outdated") delete();场景:比如模型之前记住了“现在是牛市”,但今天突然暴跌,遗忘门开启,把“牛市”这个状态忘掉。
B. 输入门 (Input Gate)
功能:决定要把什么新信息存进内存。
逻辑:
write_permission * new_contentCS 翻译:
if (new_info == "important") save_to_memory();场景:今天美联储宣布加息,这是一个极其重要的信号,输入门完全打开,把这个变量写入长期记忆。
C. 输出门 (Output Gate)
功能:基于当前的记忆和输入,决定输出什么预测值。
CS 翻译:
return current_state * filter;场景:结合长期记忆(熊市)和今天输入(微跌),输出预测结果:明天的波动率依然很高。
import torch
import torch.nn as nn
import numpy as np
# === 1. 定义 LSTM 模型类 (上帝的先知) ===
class VolatilityPredictor(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, output_size):
super(VolatilityPredictor, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
# A. LSTM 层 (核心特征提取器)
# batch_first=True 表示输入数据的形状是 (Batch, Time_Steps, Features)
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
# B. 全连接层 (输出头)
# 把 LSTM 提取的复杂特征,压缩成一个数字(波动率)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
# x shape: (batch_size, sequence_length, input_size)
# 初始化隐状态 (Short-term memory) 和 细胞状态 (Long-term memory)
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device)
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device)
# 前向传播: 跑一遍历史数据
# out 包含每一步的输出,_ 包含最后的记忆状态
out, _ = self.lstm(x, (h0, c0))
# 我们只关心最后一步的输出 (基于所有历史做出的判断)
last_step_out = out[:, -1, :]
# 预测波动率
prediction = self.fc(last_step_out)
return prediction
# === 2. 模拟数据流 ===
# 假设我们看过去 30 天的数据 (Time_Steps=30)
# 每天有 3 个特征: [收盘价, 最高价, 最低价] (Input_Size=3)
batch_size = 10
seq_len = 30
input_dim = 3
# 生成假数据 (Batch, Time, Features)
dummy_input = torch.randn(batch_size, seq_len, input_dim)
# === 3. 实例化模型 ===
model = VolatilityPredictor(input_size=input_dim,
hidden_size=64, # LSTM 内部神经元数量
num_layers=2, # 堆叠两层 LSTM (更深)
output_size=1) # 输出一个数 (波动率)
# === 4. 预测 ===
# 上帝视角:根据过去30天的风吹草动,预测未来的混乱程度
predicted_sigma = model(dummy_input)
# 确保输出是正数 (波动率不能为负),通常过一个 Softplus 或 Abs
predicted_sigma = torch.abs(predicted_sigma)
print(f"输入数据形状: {dummy_input.shape}")
print(f"AI 预测的未来波动率 (前5个): \n{predicted_sigma[:5].detach().numpy()}")输入数据形状: torch.Size([10, 30, 3]) AI 预测的未来波动率 (前5个): [[0.10730536] [0.11040564] [0.10992784] [0.10752429] [0.10081851]]
相比 RNN:LSTM 解决了梯度消失 (Vanishing Gradient) 问题,能捕捉更长期的依赖关系(比如 30 天前的价格暴跌对今天的影响)。
相比 GARCH (传统统计模型):LSTM 不需要假设数据服从正态分布,它是一个非参数模型,能学习到更复杂的非线性关系(比如市场恐慌情绪的非理性传导)。
GARCH模型(广义自回归条件异方差)(Generalized Autoregressive Conditional Heteroskedasticity)
- 用途:专门用来预测“波动率”的统计学模型。
- 地位:它是传统计量经济学的霸主。
名词解释:
Heteroskedasticity (异方差):意思是“波动率不是常数,是会变的”。
Autoregressive (自回归):意思是“今天的波动,取决于昨天的波动”。
- 核心逻辑:“波动率是有惯性的” (Volatility Clustering)。
- 现象:如果昨天股市大跌(波动极大),今天大概率也会不平静。就像地震后必有余震。
- CS 翻译:这是一个 递归滤波器 (Recursive Filter)。
$$ \sigma_t^2 = \omega + \alpha \cdot \epsilon_{t-1}^2 + \beta \cdot \sigma_{t-1}^2 $$
- $\sigma_t^2$ (Output):今天的预测方差(波动率的平方)。
- $\omega$ (Omega):基础噪音 (Bias)。就算天下太平,市场也总有一点点波动。
- $\epsilon_{t-1}^2$ (Recent Shock):昨天实际发生的波动(残差的平方)。
- 昨天实际跌了多少?这个外部冲击有多大?
- $\alpha$ (Alpha) 是反应速度。
- $\sigma_{t-1}^2$ (Memory):昨天的预测方差(历史记忆)。
- 这就是惯性。昨天预测的风险,会“传递”一部分给今天。
# 注意:前面加了 % 符号,这是 Jupyter 的魔法命令,专门用来安装包
# -i https://pypi.org/simple 是强制使用官方源,绕过可能出错的镜像
%pip install yfinance arch torch matplotlib pandas -i https://pypi.org/simpleCollecting yfinance
Downloading yfinance-1.0-py2.py3-none-any.whl.metadata (6.0 kB)
Collecting arch
Downloading arch-8.0.0-cp310-cp310-win_amd64.whl.metadata (13 kB)
Requirement already satisfied: torch in d:\anaconda3\envs\datacompenv\lib\site-packages (2.5.1)
Requirement already satisfied: matplotlib in d:\anaconda3\envs\datacompenv\lib\site-packages (3.10.7)
Requirement already satisfied: pandas in d:\anaconda3\envs\datacompenv\lib\site-packages (2.3.3)
Requirement already satisfied: numpy>=1.16.5 in d:\anaconda3\envs\datacompenv\lib\site-packages (from yfinance) (2.0.1)
Requirement already satisfied: requests>=2.31 in d:\anaconda3\envs\datacompenv\lib\site-packages (from yfinance) (2.32.5)
Collecting multitasking>=0.0.7 (from yfinance)
Downloading multitasking-0.0.12.tar.gz (19 kB)
Preparing metadata (setup.py): started
Preparing metadata (setup.py): finished with status 'done'
Requirement already satisfied: platformdirs>=2.0.0 in d:\anaconda3\envs\datacompenv\lib\site-packages (from yfinance) (4.5.0)
Requirement already satisfied: pytz>=2022.5 in d:\anaconda3\envs\datacompenv\lib\site-packages (from yfinance) (2025.2)
Collecting frozendict>=2.3.4 (from yfinance)
Downloading frozendict-2.4.7-cp310-cp310-win_amd64.whl.metadata (24 kB)
Collecting peewee>=3.16.2 (from yfinance)
Downloading peewee-3.19.0-py3-none-any.whl.metadata (7.0 kB)
Requirement already satisfied: beautifulsoup4>=4.11.1 in d:\anaconda3\envs\datacompenv\lib\site-packages (from yfinance) (4.14.2)
Collecting curl_cffi<0.14,>=0.7 (from yfinance)
Downloading curl_cffi-0.13.0-cp39-abi3-win_amd64.whl.metadata (13 kB)
Requirement already satisfied: protobuf>=3.19.0 in d:\anaconda3\envs\datacompenv\lib\site-packages (from yfinance) (6.33.0)
Collecting websockets>=13.0 (from yfinance)
Downloading websockets-16.0-cp310-cp310-win_amd64.whl.metadata (7.0 kB)
Requirement already satisfied: cffi>=1.12.0 in d:\anaconda3\envs\datacompenv\lib\site-packages (from curl_cffi<0.14,>=0.7->yfinance) (2.0.0)
Requirement already satisfied: certifi>=2024.2.2 in d:\anaconda3\envs\datacompenv\lib\site-packages (from curl_cffi<0.14,>=0.7->yfinance) (2025.10.5)
Requirement already satisfied: scipy>=1.8 in d:\anaconda3\envs\datacompenv\lib\site-packages (from arch) (1.15.3)
Collecting statsmodels>=0.13.0 (from arch)
Downloading statsmodels-0.14.6-cp310-cp310-win_amd64.whl.metadata (9.8 kB)
Requirement already satisfied: packaging in d:\anaconda3\envs\datacompenv\lib\site-packages (from arch) (25.0)
Requirement already satisfied: filelock in d:\anaconda3\envs\datacompenv\lib\site-packages (from torch) (3.20.0)
Requirement already satisfied: typing-extensions>=4.8.0 in d:\anaconda3\envs\datacompenv\lib\site-packages (from torch) (4.15.0)
Requirement already satisfied: networkx in d:\anaconda3\envs\datacompenv\lib\site-packages (from torch) (3.4.2)
Requirement already satisfied: jinja2 in d:\anaconda3\envs\datacompenv\lib\site-packages (from torch) (3.1.6)
Requirement already satisfied: fsspec in d:\anaconda3\envs\datacompenv\lib\site-packages (from torch) (2025.10.0)
Requirement already satisfied: sympy==1.13.1 in d:\anaconda3\envs\datacompenv\lib\site-packages (from torch) (1.13.1)
Requirement already satisfied: mpmath<1.4,>=1.1.0 in d:\anaconda3\envs\datacompenv\lib\site-packages (from sympy==1.13.1->torch) (1.3.0)
Requirement already satisfied: contourpy>=1.0.1 in d:\anaconda3\envs\datacompenv\lib\site-packages (from matplotlib) (1.3.2)
Requirement already satisfied: cycler>=0.10 in d:\anaconda3\envs\datacompenv\lib\site-packages (from matplotlib) (0.12.1)
Requirement already satisfied: fonttools>=4.22.0 in d:\anaconda3\envs\datacompenv\lib\site-packages (from matplotlib) (4.60.1)
Requirement already satisfied: kiwisolver>=1.3.1 in d:\anaconda3\envs\datacompenv\lib\site-packages (from matplotlib) (1.4.9)
Requirement already satisfied: pillow>=8 in d:\anaconda3\envs\datacompenv\lib\site-packages (from matplotlib) (11.1.0)
Requirement already satisfied: pyparsing>=3 in d:\anaconda3\envs\datacompenv\lib\site-packages (from matplotlib) (3.2.5)
Requirement already satisfied: python-dateutil>=2.7 in d:\anaconda3\envs\datacompenv\lib\site-packages (from matplotlib) (2.9.0.post0)
Requirement already satisfied: tzdata>=2022.7 in d:\anaconda3\envs\datacompenv\lib\site-packages (from pandas) (2025.2)
Requirement already satisfied: soupsieve>1.2 in d:\anaconda3\envs\datacompenv\lib\site-packages (from beautifulsoup4>=4.11.1->yfinance) (2.8)
Requirement already satisfied: pycparser in d:\anaconda3\envs\datacompenv\lib\site-packages (from cffi>=1.12.0->curl_cffi<0.14,>=0.7->yfinance) (2.23)
Requirement already satisfied: six>=1.5 in d:\anaconda3\envs\datacompenv\lib\site-packages (from python-dateutil>=2.7->matplotlib) (1.17.0)
Requirement already satisfied: charset_normalizer<4,>=2 in d:\anaconda3\envs\datacompenv\lib\site-packages (from requests>=2.31->yfinance) (3.4.4)
Requirement already satisfied: idna<4,>=2.5 in d:\anaconda3\envs\datacompenv\lib\site-packages (from requests>=2.31->yfinance) (3.11)
Requirement already satisfied: urllib3<3,>=1.21.1 in d:\anaconda3\envs\datacompenv\lib\site-packages (from requests>=2.31->yfinance) (2.5.0)
Collecting patsy>=0.5.6 (from statsmodels>=0.13.0->arch)
Downloading patsy-1.0.2-py2.py3-none-any.whl.metadata (3.6 kB)
Requirement already satisfied: MarkupSafe>=2.0 in d:\anaconda3\envs\datacompenv\lib\site-packages (from jinja2->torch) (3.0.2)
Downloading yfinance-1.0-py2.py3-none-any.whl (127 kB)
Downloading curl_cffi-0.13.0-cp39-abi3-win_amd64.whl (1.6 MB)
---------------------------------------- 0.0/1.6 MB ? eta -:--:--
------ --------------------------------- 0.3/1.6 MB ? eta -:--:--
------------------- -------------------- 0.8/1.6 MB 3.0 MB/s eta 0:00:01
-------------------------------- ------- 1.3/1.6 MB 2.5 MB/s eta 0:00:01
---------------------------------------- 1.6/1.6 MB 2.2 MB/s 0:00:00
Downloading arch-8.0.0-cp310-cp310-win_amd64.whl (937 kB)
---------------------------------------- 0.0/937.9 kB ? eta -:--:--
---------------------------------------- 937.9/937.9 kB 7.3 MB/s 0:00:00
Downloading frozendict-2.4.7-cp310-cp310-win_amd64.whl (37 kB)
Downloading peewee-3.19.0-py3-none-any.whl (411 kB)
Downloading statsmodels-0.14.6-cp310-cp310-win_amd64.whl (9.6 MB)
---------------------------------------- 0.0/9.6 MB ? eta -:--:--
------- -------------------------------- 1.8/9.6 MB 10.1 MB/s eta 0:00:01
------------- -------------------------- 3.1/9.6 MB 8.4 MB/s eta 0:00:01
------------------------------ --------- 7.3/9.6 MB 11.9 MB/s eta 0:00:01
---------------------------------------- 9.6/9.6 MB 11.7 MB/s 0:00:00
Downloading patsy-1.0.2-py2.py3-none-any.whl (233 kB)
Downloading websockets-16.0-cp310-cp310-win_amd64.whl (178 kB)
Building wheels for collected packages: multitasking
Building wheel for multitasking (setup.py): started
Building wheel for multitasking (setup.py): finished with status 'done'
Created wheel for multitasking: filename=multitasking-0.0.12-py3-none-any.whl size=15703 sha256=fee5fb7c4e8b8b169cdaad7ea0977a92d8301293454866086fa59b81b4bafca0
Stored in directory: c:\users\马鑫悦\appdata\local\pip\cache\wheels\e9\25\85\25d2e1cfc0ece64b930b16972f7e4cc3599c43b531f1eba06d
Successfully built multitasking
Installing collected packages: peewee, multitasking, websockets, patsy, frozendict, curl_cffi, yfinance, statsmodels, arch
-------- ------------------------------- 2/9 [websockets]
------------- -------------------------- 3/9 [patsy]
Attempting uninstall: curl_cffi
------------- -------------------------- 3/9 [patsy]
Found existing installation: curl_cffi 0.14.0
------------- -------------------------- 3/9 [patsy]
Uninstalling curl_cffi-0.14.0:
------------- -------------------------- 3/9 [patsy]
Successfully uninstalled curl_cffi-0.14.0
------------- -------------------------- 3/9 [patsy]
---------------------- ----------------- 5/9 [curl_cffi]
------------------------------- -------- 7/9 [statsmodels]
------------------------------- -------- 7/9 [statsmodels]
------------------------------- -------- 7/9 [statsmodels]
------------------------------- -------- 7/9 [statsmodels]
------------------------------- -------- 7/9 [statsmodels]
------------------------------- -------- 7/9 [statsmodels]
------------------------------- -------- 7/9 [statsmodels]
------------------------------- -------- 7/9 [statsmodels]
------------------------------- -------- 7/9 [statsmodels]
------------------------------- -------- 7/9 [statsmodels]
------------------------------- -------- 7/9 [statsmodels]
------------------------------- -------- 7/9 [statsmodels]
------------------------------- -------- 7/9 [statsmodels]
------------------------------- -------- 7/9 [statsmodels]
------------------------------- -------- 7/9 [statsmodels]
------------------------------- -------- 7/9 [statsmodels]
------------------------------- -------- 7/9 [statsmodels]
------------------------------- -------- 7/9 [statsmodels]
----------------------------------- ---- 8/9 [arch]
----------------------------------- ---- 8/9 [arch]
---------------------------------------- 9/9 [arch]
Successfully installed arch-8.0.0 curl_cffi-0.13.0 frozendict-2.4.7 multitasking-0.0.12 patsy-1.0.2 peewee-3.19.0 statsmodels-0.14.6 websockets-16.0 yfinance-1.0
Note: you may need to restart the kernel to use updated packages.
DEPRECATION: Building 'multitasking' using the legacy setup.py bdist_wheel mechanism, which will be removed in a future version. pip 25.3 will enforce this behaviour change. A possible replacement is to use the standardized build interface by setting the `--use-pep517` option, (possibly combined with `--no-build-isolation`), or adding a `pyproject.toml` file to the source tree of 'multitasking'. Discussion can be found at https://github.com/pypa/pip/issues/6334 WARNING: The script pwiz.exe is installed in 'd:\Anaconda3\envs\datacompenv\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. WARNING: The script websockets.exe is installed in 'd:\Anaconda3\envs\datacompenv\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. WARNING: The script sample.exe is installed in 'd:\Anaconda3\envs\datacompenv\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from arch import arch_model
import torch
import torch.nn as nn
from torch.utils.data import TensorDataset, DataLoader
# ==========================================
# 第一步:数据自动流 (Data Pipeline)
# ==========================================
print("正在从华尔街拉取铜期货数据 (Copper Futures)...")
# 拉取 HG=F (铜期货) 过去 5 年的数据
ticker = "HG=F"
data = yf.download(ticker, start="2020-01-01", progress=False)
# 计算收益率 (Returns) = ln(今天价格/昨天价格)
# *100 是为了让 GARCH 模型更容易收敛 (它喜欢数值大一点)
returns = 100 * data['Close'].pct_change().dropna()
returns.name = 'Returns'
print(f"成功获取 {len(returns)} 天的数据。")
# ==========================================
# 第二步:旧神降临 (GARCH Model)
# ==========================================
print("\n正在运行 GARCH(1,1) 统计模型...")
# p=1 (自回归), q=1 (移动平均) 是最经典的配置
garch = arch_model(returns, vol='Garch', p=1, q=1)
garch_res = garch.fit(disp='off') # disp='off' 不打印啰嗦的训练过程
# 获取 GARCH 预测的波动率 (Conditional Volatility)
garch_vol = garch_res.conditional_volatility
# ==========================================
# 第三步:新神崛起 (LSTM Model) - 修正版
# ==========================================
print("\n正在训练 LSTM 神经网络...")
# --- 关键修正点:强制把数据变成一维 ---
# 如果 returns 是 DataFrame (N行1列),把它挤压成 Series (N行)
if isinstance(returns, pd.DataFrame):
returns = returns.iloc[:, 0] # 只取第一列
# 1. 数据预处理
def create_sequences(data, seq_length):
xs, ys = [], []
data = data.values # 此时 data 是一维数组
for i in range(len(data) - seq_length):
x = data[i:i+seq_length]
y = np.abs(data[i+seq_length])
xs.append(x)
ys.append(y)
return np.array(xs), np.array(ys)
SEQ_LEN = 10
X_np, y_np = create_sequences(returns, SEQ_LEN)
# 转成 PyTorch 张量
# 此时 X_np 是 (Batch, Seq), 我们需要 (Batch, Seq, 1)
X_tensor = torch.FloatTensor(X_np).unsqueeze(-1)
y_tensor = torch.FloatTensor(y_np).unsqueeze(-1)
# 再次确认维度 (如果不放心,打印出来看看)
print(f"修正后的输入维度: {X_tensor.shape}") # 应该是 [Batch, 10, 1]
# 2. 定义极简 LSTM 模型
class SimpleLSTM(nn.Module):
def __init__(self):
super().__init__()
self.lstm = nn.LSTM(input_size=1, hidden_size=64, batch_first=True)
self.fc = nn.Linear(64, 1)
self.relu = nn.ReLU()
def forward(self, x):
out, _ = self.lstm(x)
out = out[:, -1, :]
out = self.fc(out)
return self.relu(out)
# 3. 现场训练
model = SimpleLSTM()
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
epochs = 100
for i in range(epochs):
optimizer.zero_grad()
y_pred = model(X_tensor)
loss = criterion(y_pred, y_tensor)
loss.backward()
optimizer.step()
if (i+1) % 20 == 0:
print(f"Epoch {i+1}/{epochs}, Loss: {loss.item():.4f}")
# 4. 获取预测结果
with torch.no_grad():
lstm_vol = model(X_tensor).numpy().flatten()
print("LSTM 训练完成!")
# 第四步:巅峰对决 (Visualization)
# ==========================================
plt.figure(figsize=(12, 6))
# 为了画图对齐,我们要截掉 GARCH 的前10天 (因为 LSTM 需要10天窗口)
common_index = returns.index[SEQ_LEN:]
# A. 真实波动 (用绝对收益率表示) - 灰色的背景噪音
plt.plot(common_index, np.abs(returns[SEQ_LEN:]), color='gray', alpha=0.3, label='Realized Volatility (Noise)')
# B. GARCH 预测 - 蓝线 (平滑,反应慢)
plt.plot(common_index, garch_vol[SEQ_LEN:], color='blue', linewidth=1.5, label='GARCH (Traditional)')
# C. LSTM 预测 - 红线 (敏锐,拟合好)
plt.plot(common_index, lstm_vol, color='red', linewidth=2, label='LSTM (AI Model)')
plt.title("The Battle of Volatility: AI (LSTM) vs. Statistics (GARCH)\nTarget: Copper Futures (HG=F)", fontsize=14)
plt.ylabel("Volatility Magnitude")
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()正在从华尔街拉取铜期货数据 (Copper Futures)... 成功获取 1522 天的数据。 正在运行 GARCH(1,1) 统计模型... 正在训练 LSTM 神经网络... 修正后的输入维度: torch.Size([1512, 10, 1]) Epoch 20/100, Loss: 1.4554 Epoch 40/100, Loss: 1.4336 Epoch 60/100, Loss: 1.4114 Epoch 80/100, Loss: 1.3987 Epoch 100/100, Loss: 1.3845 LSTM 训练完成!
灰色背景:这是真实的市场噪音(每天铜价跳得有多欢)。你会看到它有时很低,有时突然炸一下(比如 2020 年或者 2022 年)。
蓝线 (GARCH):这是传统模型。
- 观察它的特点:它也能反应过来,但总是慢半拍。而且一旦波动起来,它很难马上平复下去(拖泥带水)。
红线 (LSTM):这是你的AI 模型。
观察它的特点:它对那些灰色的尖峰(突发事件)贴合得更紧密。
在市场剧烈变动时,LSTM 能比 GARCH 更快地捕捉到风险信号
组成
内在价值
定义:假设此时此刻立刻行权,能得到的收益。
计算逻辑:
- 如果铜价 $S=120$,成本 $K=100$ $\rightarrow$ 内在价值 = 20。
- 如果铜价 $S=80$,成本 $K=100$ $\rightarrow$ 内在价值 = 0 (因为你不会傻到去行权亏钱,期权最低是 0)。
别名:这部分也被称为“实值程度”。只有价内期权 (In-the-Money) 才有内在价值。
价内期权 (In-the-Money Option, ITM) 就是: 如果此时此刻不管是第几年,只要你现在立刻开机挖矿,你能赚到差价。
在代码和模型里,它对应着内在价值 > 0 的那种状态。
核心定义(针对看涨期权/Call Option)
矿山开采权本质上是一个看涨期权(你有权以成本 K 买入铜矿 S)。
S (Spot Price):现在的铜价(比如 120)。
K (Strike Price):你的挖矿成本(比如 100)。
所谓“价内” (ITM),就是 S>K。
场景:铜价 120,成本 100。
操作:挖!
结果:你每挖一吨,立刻赚 20 块。
状态:这就是价内。这 20 块就是内在价值。
另外两种状态(为了对比)
为了彻底搞懂“价内”,需要知道它的两个邻居:
价平 (At-the-Money, ATM):
状态:S=K(铜价 100 = 成本 100)。
结果:白忙活,不赚不赔。
内在价值:0。
价外 (Out-of-the-Money, OTM):
状态:S<K(铜价 80 < 成本 100)。
结果:挖一吨亏 20 块。
操作:你绝对不会行权(关机装死)。
内在价值:0(期权不会有负价值,最差就是废纸一张)。
“价内”并不代表你整个生意赚钱了。
期权费 (Premium):假设你买这个矿山花了 30 亿(沉没成本)。
现状:现在铜价 120,成本 100。这是价内。
行权收益:你赚了 20 亿现金流。
总账:20−30=−10 亿。
结论: 即使是价内,你可能总账还是亏的。但价内意味着你有资格回血。如果不挖,你亏 30 亿;挖了,你只亏 10 亿。所以只要是价内,通常都有行权的动力。
时间价值
时间价值由两个核心要素驱动:
A. 时间的长度 (Time to Expiration)
逻辑:离到期日越远,发生奇迹的概率越大。
例子:
期权A:还有 1 天到期,铜价 80。翻身概率几乎为 0,时间价值 ≈0。
期权B:还有 10 年到期,铜价 80。十年河东十年河西,翻身概率很大,时间价值可能 ≈20。
物理隐喻:这就是在 LSM 代码里的
T。时间越长,跑出来的路径越发散,向上的可能性越大。
B. 波动率 (Volatility) —— 这里Call back LSTM
逻辑:市场越乱,期权越值钱。
原因:期权是下有保底,上不封顶的。
如果市场死水一潭(波动率低),铜价就在 80 上下 1 块钱浮动,你永远翻不了身。
如果市场疯了(波动率高),铜价可能跌到 10(反正你不行权,跌多少都无所谓),也可能涨到 200(暴赚)。
混乱(波动)越大,你右边那个“赚钱区域”的面积就越大。
项目联系:你刚才用 LSTM 预测出的那条红线,如果它是向上走的(预测未来波动大),那么你的 LSM 模型 算出的时间价值就会暴涨。
影响因素
1. 标的资产价格 (Underlying Asset Price, S)
你的项目:当前的铜价。
逻辑:S 越高,挖矿越赚,矿山(期权)越值钱。
CS 类比:Input Data。这是系统的实时输入信号。
2. 行权价 (Strike Price, K)
你的项目:挖矿成本(比如 100元/吨)。
逻辑:K 越高(成本越高),你就越不想挖,矿山越不值钱。
CS 类比:Threshold (阈值)。这是你在代码里写死的常量
const K = 100。
3. 波动率 (Volatility, σ) —— 最关键!
你的项目:市场有多乱(你用 LSTM 预测的那个红线)。
逻辑:混乱 = 阶梯。波动率越大,期权越值钱(因为下有保底,上不封顶)。
CS 类比:Entropy (熵) 或 Randomness。系统的随机性越大,可能探索到的“高分区域”就越高。
4. 到期日 (Time to Maturity, T)
你的项目:你的采矿权还有几年过期?
逻辑:时间越长,发生奇迹(暴涨)的概率越大,期权越值钱。
CS 类比:Timeout。倒计时结束,游戏强制结束。
5. 无风险利率 (Risk-free Rate, r)
你的项目:国债利率(比如 3%)。
逻辑:
如果你决定现在不挖(不行权),你就不用付那笔成本 K。
你可以把这笔钱存银行吃利息。
所以利率 r 越高,拖延的收益就越大,看涨期权就越值钱。
CS 类比:Discount Factor (衰减因子)。未来的奖励打折到现在值多少钱。
原理
1. 无套利定价 (No-Arbitrage Pricing)
通俗解释:“天下没有免费的午餐”。
上帝视角:
如果在你的游戏里,玩家可以用 1 个金币买个苹果,转身去隔壁 NPC 那里卖 2 个金币。
结果:所有玩家都会疯狂刷这个 Bug,瞬间产生无限金币,游戏经济崩溃。
无套利原理:假设市场是完美的,这种 Bug 瞬间就会被修好(价格会被抹平)。
你的项目:
- BSM 和 LSM 模型都建立在这个假设上:你算出来的价格,是让市场上不存在“稳赚不赔”机会的那个唯一价格。
2. 对冲 (Hedging) —— 矿主最关心的!
通俗解释:“买保险”。
业务场景:
你作为一个矿主,你手里有大量的铜(你是 Long Copper)。
你最怕什么?怕铜价跌。
怎么对冲?你去期货市场上做空 (Short) 铜。
结果:如果铜价跌了,你矿山亏钱,但期货赚了。互相抵消,锁定利润。
CS 类比:Redundancy (冗余备份)。主服务器挂了(铜价跌),备用服务器(期货空单)立刻顶上,保证系统(现金流)不崩溃。
机器学习模式实现
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import matplotlib.pyplot as plt
# 锁死随机种子
np.random.seed(42)
torch.manual_seed(42)
# ==========================================
# 模块 1: 物理引擎 (修复了波动率单位 Bug)
# ==========================================
def generate_ou_paths(S0, K, T, r, sigma, theta, mu_ou, num_paths, steps):
dt = T / steps
prices = np.zeros((num_paths, steps + 1))
prices[:, 0] = S0
for t in range(1, steps + 1):
S_prev = prices[:, t-1]
dW = np.random.normal(0, np.sqrt(dt), num_paths)
# [核心修复] 注意这里最后乘了 S_prev
# 意思是:波动是价格的 20%,而不是固定的 0.2 元
dS = theta * (mu_ou - S_prev) * dt + sigma * S_prev * dW
prices[:, t] = S_prev + dS
prices[:, t] = np.maximum(prices[:, t], 0.01)
return prices
# ==========================================
# 模块 2: 决策大脑 (不变)
# ==========================================
class ValueNetwork(nn.Module):
def __init__(self):
super(ValueNetwork, self).__init__()
self.net = nn.Sequential(
nn.Linear(1, 64),
nn.ReLU(),
nn.Linear(64, 64),
nn.ReLU(),
nn.Linear(64, 1)
)
def forward(self, x):
return self.net(x)
def train_network(model, x_train, y_train, epochs=50): # 50 epoch 足够了
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.01)
inputs = torch.FloatTensor(x_train)
targets = torch.FloatTensor(y_train)
model.train()
for _ in range(epochs):
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
return model
# ==========================================
# 模块 3: Deep LSM 核心 (不变)
# ==========================================
def deep_lsm_valuation(prices, K, r, T):
num_paths, steps = prices.shape
steps -= 1
dt = T / steps
discount_factor = np.exp(-r * dt)
S0_norm = prices[0, 0]
cash_flows = np.maximum(prices[:, -1] - K, 0)
exercise_boundary = np.full(steps, np.nan)
print(f">>> Deep LSM 启动 (波动率修正版)...")
for t in range(steps - 1, 0, -1):
current_prices = prices[:, t]
itm_mask = current_prices > K
if np.sum(itm_mask) < 10:
cash_flows *= discount_factor
continue
X_itm = current_prices[itm_mask].reshape(-1, 1)
Y_future = cash_flows[itm_mask] * discount_factor
# 归一化
X_norm = X_itm / S0_norm
Y_norm = Y_future.reshape(-1, 1) / S0_norm
# 训练
value_net = ValueNetwork()
train_network(value_net, X_norm, Y_norm, epochs=50)
# 预测
value_net.eval()
with torch.no_grad():
pred_norm = value_net(torch.FloatTensor(X_norm)).numpy().flatten()
continuation_value = pred_norm * S0_norm
exercise_value = current_prices[itm_mask] - K
should_exercise = exercise_value > continuation_value
if np.any(should_exercise):
exercise_boundary[t] = np.min(current_prices[itm_mask][should_exercise])
full_exercise_decision = np.zeros(num_paths, dtype=bool)
full_exercise_decision[itm_mask] = should_exercise
cash_flows[full_exercise_decision] = exercise_value[should_exercise]
cash_flows[~full_exercise_decision] *= discount_factor
if t % 10 == 0:
print(f"Step {t}: AI 训练完成")
return np.mean(cash_flows * discount_factor), exercise_boundary
# ==========================================
# 模块 4: 运行
# ==========================================
S0 = 100
K = 100
T = 1.0
r = 0.05
sigma = 0.2 # 这里的 0.2 现在代表 20%
theta = 2.0
mu_ou = 100
num_paths = 2000
steps = 50
# 1. 生成 (这次波动会变大!)
print("1. 生成物理世界...")
ou_prices = generate_ou_paths(S0, K, T, r, sigma, theta, mu_ou, num_paths, steps)
# 2. 估值
deep_value, deep_boundary = deep_lsm_valuation(ou_prices, K, r, T)
print("\n" + "="*40)
print(f"Deep LSM 最终估值: {deep_value:.4f}")
print("="*40 + "\n")
# 3. 画图
plt.figure(figsize=(10, 6))
# 背景线
plt.plot(np.linspace(0, T, steps+1), ou_prices[:20, :].T, color='gray', alpha=0.2)
# 红线
time_axis = np.linspace(0, T, steps)
mask = np.isfinite(deep_boundary)
plt.plot(time_axis[mask], deep_boundary[mask], 'r-o', linewidth=2, label='AI Boundary')
plt.axhline(K, color='black', linestyle='--')
plt.title(f"Deep LSM (Fixed Volatility)\nOption Value: {deep_value:.4f}")
plt.ylim(80, 140)
plt.legend()
plt.show()1. 生成物理世界... >>> Deep LSM 启动 (波动率修正版)... Step 40: AI 训练完成 Step 30: AI 训练完成 Step 20: AI 训练完成 Step 10: AI 训练完成 ======================================== Deep LSM 最终估值: 6.7737 ========================================
觉得有用的话,点个赞
发表评论