import numpy as np
def portstats(ExpReturn, ExpCovariance, PortWts):
PortRisk = 0
for i in range(len(PortWts)):
for j in range(len(PortWts)):
PortRisk += PortWts[i] * PortWts[j] * ExpCovariance[i * 3 + j]
PortReturn = np.sum(ExpReturn * np.array(PortWts))
return np.sqrt(PortRisk), PortReturn
# 组合中每个证券的预期收益率
ExpReturn = [0.000540, 0.000275, 0.000236]
# 组合中证券的协方差矩阵
ExpCovariance = 0.0001 * np.array([5.27, 2.80, 1.74,
2.80, 4.26, 1.67,
1.74, 1.67, 2.90])
ExpCovariance = ExpCovariance.tolist()
# 组合中每个证券的初始权重(初始投资金额)/初始总金额
PortWts = 1.0 / 3 * np.array([1, 1, 1])
PortWts = PortWts.tolist()
# 调用portstats函数
[PortRisk, PortReturn] = portstats(ExpReturn, ExpCovariance, PortWts)
print(PortRisk, PortReturn)
# 计算结果
风险(标准差) PortRisk= 0.016617
组合收益率 PortReturn= 3.5033e-004
import numpy as np
import matplotlib.pyplot as plt # 绘图
import scipy.optimize as sco
def frontcon(ExpReturn, ExpCovariance, NumPorts):
noa = len(ExpReturn)
def statistics(weights):
weights = np.array(weights)
z = np.dot(ExpCovariance, weights)
x = np.dot(weights, z)
port_returns = (np.sum(ExpReturn * weights.T))
port_variance = np.sqrt(x)
num1 = port_returns / port_variance
return np.array([port_returns, port_variance, num1])
# 定义一个函数对 方差进行最小化
def min_variance(weights):
return statistics(weights)[1]
bnds = tuple((0, 1) for x in range(noa))
# 在不同目标收益率水平(target_returns)循环时,最小化的一个约束条件会变化。
target_returns = np.linspace(min(ExpReturn), max(ExpReturn), NumPorts)
target_variance = []
PortWts = []
for tar in target_returns:
# 在最优化时采用两个约束,1.给定目标收益率,2.投资组合权重和为1。
cons = ({
'type': 'eq', 'fun': lambda x: statistics(x)[0] - tar}, {
'type': 'eq', 'fun': lambda x: np.sum(x) - 1})
res = sco.minimize(min_variance, noa * [1. / noa, ], method='SLSQP', bounds=bnds, constraints=cons)
target_variance.append(res['fun'])
PortWts.append(res["x"])
target_variance = np.array(target_variance)
return [target_variance, target_returns, PortWts]
ExpReturn = np.array([0.00540, 0.00275, 0.00236])
ExpCovariance = 0.0001 * np.array([[5.27, 2.80, 1.74],
[2.80, 4.26, 1.67],
[1.74, 1.67, 2.90]])
NumPorts = 10
[target_variance, target_returns, PortWts] = frontcon(ExpReturn, ExpCovariance, NumPorts)
plt.plot(target_variance, target_returns)
plt.title("Mean-Variance-Efficient Frontier")
plt.xlabel("Risk(Standard Deviation)")
plt.ylabel("Expected Return")
plt.show()