用python实现马科维茨有效边界图
时间: 2023-07-12 21:30:33 浏览: 187
要实现马科维茨有效边界图,需要以下步骤:
1. 安装必要的Python库,如numpy、pandas、matplotlib等。
2. 创建一个投资组合的收益率和波动率数据集。可以使用历史数据或模拟数据。
3. 计算投资组合的预期收益率、预期波动率和协方差矩阵。
4. 使用numpy中的linspace函数生成各个预期收益率水平下的最小方差投资组合的权重组合。
5. 计算每个最小方差投资组合的预期收益率和波动率。
6. 使用matplotlib中的scatter函数绘制最小方差投资组合的预期收益率和波动率散点图。
7. 使用scipy.optimize库中的minimize函数计算每个预期收益率水平下的最优投资组合。
8. 计算每个最优投资组合的预期收益率和波动率。
9. 使用matplotlib中的plot函数绘制最优投资组合的有效边界。
下面是示例代码:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import minimize
# 创建数据集
returns = np.random.normal(0.05, 0.1, 100)
volatility = np.random.normal(0.1, 0.05, 100)
data = pd.DataFrame({'returns': returns, 'volatility': volatility})
# 计算预期收益率、预期波动率和协方差矩阵
mu = data['returns'].mean()
sigma = data['volatility'].std()
cov_matrix = np.cov(data['returns'], data['volatility'])
# 生成权重组合
num_portfolios = 1000
results = np.zeros((3 + len(data.columns), num_portfolios))
for i in range(num_portfolios):
weights = np.random.random(len(data.columns))
weights /= np.sum(weights)
portfolio_return = np.dot(weights, data['returns'])
portfolio_volatility = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
results[0, i] = portfolio_return
results[1, i] = portfolio_volatility
results[2, i] = portfolio_return / portfolio_volatility
for j in range(len(weights)):
results[j+3, i] = weights[j]
# 绘制最小方差投资组合散点图
min_volatility_idx = np.argmin(results[1])
min_volatility_return = results[0, min_volatility_idx]
min_volatility_volatility = results[1, min_volatility_idx]
plt.scatter(results[1,:], results[0,:], c=results[2,:], cmap='YlOrRd', alpha=0.5)
plt.scatter(min_volatility_volatility, min_volatility_return, c='b', marker='*', s=500)
plt.xlabel('Volatility')
plt.ylabel('Returns')
plt.colorbar()
# 计算最优投资组合
def objective(weights):
portfolio_return = np.dot(weights, data['returns'])
portfolio_volatility = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
return -portfolio_return / portfolio_volatility
constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1})
bounds = [(0, 1)] * len(data.columns)
initial_weights = np.ones(len(data.columns)) / len(data.columns)
optimal_weights = minimize(objective, initial_weights, method='SLSQP', bounds=bounds, constraints=constraints)
optimal_weights = optimal_weights.x
# 计算最优投资组合的预期收益率和波动率
optimal_return = np.dot(optimal_weights, data['returns'])
optimal_volatility = np.sqrt(np.dot(optimal_weights.T, np.dot(cov_matrix, optimal_weights)))
# 绘制最优投资组合的有效边界
frontier_returns = []
frontier_volatilities = []
for r in np.linspace(min(results[0,:]), max(results[0,:]), num=100):
constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1},
{'type': 'eq', 'fun': lambda x, r=r: np.dot(x, data['returns']) - r})
bounds = [(0, 1)] * len(data.columns)
initial_weights = np.ones(len(data.columns)) / len(data.columns)
optimal_weights = minimize(objective, initial_weights, method='SLSQP', bounds=bounds, constraints=constraints)
optimal_weights = optimal_weights.x
frontier_returns.append(r)
frontier_volatilities.append(np.sqrt(np.dot(optimal_weights.T, np.dot(cov_matrix, optimal_weights))))
plt.plot(frontier_volatilities, frontier_returns, 'g--', linewidth=2)
plt.show()
```
此代码将生成一个包含最小方差投资组合散点图和有效边界图的matplotlib图形。
阅读全文