如何针对指定风险水平优化投资组合并设置std约束提取对应权重
投资组合目标风险下权重获取与约束设置方案
方案1:基于你现有蒙特卡洛模拟代码快速实现
你现有的随机采样逻辑可以直接通过数组筛选得到目标结果,相比遍历列表效率更高,实现代码如下:
import numpy as np # 将你已生成的列表转为numpy数组方便批量运算 returns = np.array(returns) std_arr = np.array(std) w_arr = np.array(w) # 1. 先过滤符合风险区间要求(0.045 < std < 0.075)的有效样本 valid_mask = (std_arr > 0.045) & (std_arr < 0.075) valid_returns = returns[valid_mask] valid_std = std_arr[valid_mask] valid_w = w_arr[valid_mask] # 2. 筛选std接近0.06的样本,可自行调整tolerance控制误差范围 target_std = 0.06 tolerance = 1e-4 target_mask = np.abs(valid_std - target_std) < tolerance # 3. 在符合目标风险的样本中选取收益最高的,即为有效前沿上对应风险的最优组合 if target_mask.sum() > 0: target_rets = valid_returns[target_mask] max_ret_idx = np.argmax(target_rets) target_weight = valid_w[target_mask][max_ret_idx] print(f"最优权重:{target_weight}") print(f"对应组合收益:{target_rets[max_ret_idx]:.4f},实际风险:{valid_std[target_mask][max_ret_idx]:.4f}") else: print("无符合误差要求的样本,可调大tolerance或增加模拟次数")
该方案的优点是不用改动你现有模拟逻辑,缺点是受随机采样限制,无法得到完全精准的std=0.06的结果。
方案2:基于凸优化的精准求解方案
如果需要完全匹配目标std=0.06的约束,建议使用scipy.optimize做凸优化求解,比随机采样效率高、结果准:
from scipy.optimize import minimize import numpy as np # 目标函数:最大化组合收益等价于最小化负的组合收益 def neg_port_ret(weight): return -portfolioreturn(weight) # 约束条件:权重和为1、组合std等于0.06 constraints = [ {"type": "eq", "fun": lambda w: np.sum(w) - 1}, {"type": "eq", "fun": lambda w: portfoliostd(w) - 0.06} ] # 边界条件:权重范围0~1(不允许做空,若允许做空可改为(-1,1)) n_assets = df.shape[1] bounds = tuple((0, 1) for _ in range(n_assets)) # 初始权重用平均权重 init_w = np.ones(n_assets) / n_assets # 运行优化 res = minimize(neg_port_ret, init_w, method="SLSQP", bounds=bounds, constraints=constraints) if res.success: optimal_w = res.x print(f"最优权重:{optimal_w}") print(f"对应组合收益:{-res.fun:.4f},实际风险:{portfoliostd(optimal_w):.4f}") else: print("优化失败,目标std不在可行风险范围内,请检查参数设置")
如果需要全局保留0.045 < std < 0.075的约束,只需将上述约束改为两个不等式约束即可:
constraints = [ {"type": "eq", "fun": lambda w: np.sum(w) - 1}, {"type": "ineq", "fun": lambda w: portfoliostd(w) - 0.045}, {"type": "ineq", "fun": lambda w: 0.075 - portfoliostd(w)} ]
内容的提问来源于stack exchange,提问作者Fumez123
相关产品推荐
相关产品推荐

