查看全集:💎Quantopia量化分析56讲
移动平均缺陷:
卡尔曼优势:
# 获取苹果公司股价数据
data = yf.download('AAPL', start='2018-01-01', end='2022-12-31')
prices = data['Close']
# 构建状态空间模型 (假设局部恒定趋势)
kf = KalmanFilter(
transition_matrices=[1], # 状态保持不变
observation_matrices=[1], # 直接观测价格
initial_state_mean=prices.iloc[0],
initial_state_covariance=1,
observation_covariance=10, # 假设观测噪声较大
transition_covariance=0.1 # 允许趋势缓慢变化
)
# 执行滤波
state_means, state_covs = kf.filter(prices.values)
# 可视化结果
plt.figure(figsize=(12,6))
plt.plot(prices, label='原始价格', alpha=0.4)
plt.plot(prices.index, state_means, 'r-', lw=2, label='卡尔曼滤波')
plt.plot(prices.rolling(30).mean(), 'g--', label='30日MA')
plt.title('趋势提取效果对比')
plt.legend()
plt.grid(True)
参数调优技巧:
# 使用EM算法优化参数
kf = kf.em(prices.values, n_iter=10)
optimized_means, _ = kf.filter(prices.values)
市场模型:
其中:
# 获取标普500和苹果收益率数据
market = yf.download('SPY', start='2015-01-01', end='2020-01-01')['Close'].pct_change().dropna()
stock = yf.download('AAPL', start='2015-01-01', end='2020-01-01')['Close'].pct_change().dropna()
# 数据对齐
common_idx = market.index.intersection(stock.index)
market, stock = market.loc[common_idx], stock.loc[common_idx]
# 构建动态回归模型
observation_matrix = np.ones((len(market), 1, 2)) # [截距项, 市场收益]
observation_matrix[:, 0, 1] = market.values
kf = KalmanFilter(
n_dim_state=2,
n_dim_obs=1,
transition_matrices=np.eye(2), # 参数随机游走
observation_matrices=observation_matrix,
initial_state_mean=[0, 1],
initial_state_covariance=np.eye(2),
observation_covariance=0.1,
transition_covariance=[[0.0001,0],[0,0.0001]] # 控制参数变化速度
)
# 执行滤波
state_means, _ = kf.filter(stock.values)
# 可视化时变Beta
plt.figure(figsize=(12,6))
plt.plot(common_idx, state_means[:,1], label='动态Beta')
plt.axhline(y=1, ls='--', color='gray', label='市场中性')
plt.title('苹果股票Beta系数动态变化')
plt.xlabel('日期')
plt.ylabel('Beta值')
plt.legend()
策略应用:
# 使用更稳定的KalmanFilter实现
from filterpy.kalman import KalmanFilter
kf = KalmanFilter(dim_x=2, dim_z=1)
kf.x = np.array([30., 10.]) # 初始状态
kf.P = np.diag([100., 100.]) # 初始不确定性
kf.F = np.array([[1., dt], [0., 1.]]) # 状态转移
kf.H = np.array([[1., 0.]]) # 观测函数
kf.Q = np.eye(2)*0.01 # 过程噪声
kf.R = np.array([[obs_noise**2]]) # 观测噪声
当存在非线性关系时,可采用:
扩展卡尔曼滤波(EKF)
def f(x, dt):
return np.dot(F, x) + B
def h(x):
return np.dot(H, x)
kf = ExtendedKalmanFilter(
transition_functions=f,
observation_functions=h,
...
)
无迹卡尔曼滤波(UKF)
from filterpy.kalman import UnscentedKalmanFilter
from filterpy.common import Q_discrete_white_noise
ukf = UnscentedKalmanFilter(
dim_x=3, dim_z=1,
dt=1, hx=hx, fx=fx,
points=MerweScaledSigmaPoints(3, alpha=.1, beta=2., kappa=0.),
...
)
该公式中:
应满足:
其中表示状态向量的维度,表示自由度为n的卡方分布。
订单簿动态建模:
# L2订单簿数据示例
observations = np.load('orderbook.npy')
kf = KalmanFilter(
transition_matrices=..., # 基于市场微观结构理论
observation_matrices=...,
transition_covariance=...,# 反映市场波动率
observation_covariance=... # 取决于数据质量
)
动态跟踪组合权重:
其中:
这是一个最小化跟踪误差平方的优化问题,目标是使投资组合收益率尽可能贴近基准组合收益率。通过卡尔曼滤波实时调整权重。
综合练习:构建结合价格趋势和交易量的多因子滤波模型,预测短期价格走势
通过本教程的深度学习,您已掌握:
下一步可探索: