python有效边界_Markowitz有效边界和投资组合优化基于Python(附代码)
时间: 2024-03-22 17:42:38 浏览: 27
PyPortfolioOpt:python中的金融投资组合优化,包括经典有效前沿,Black-Litterman,分层风险平价
5星 · 资源好评率100%
Markowitz有效边界和投资组合优化是金融领域中常用的方法之一,Python可以很方便地实现这些方法。
首先,我们需要导入必要的库,如pandas、numpy、matplotlib和cvxopt:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from cvxopt import matrix, solvers
```
接下来,我们需要准备我们的数据。假设我们有一个包含10只股票的投资组合,并且我们有每只股票的收益率和协方差矩阵。我们可以使用pandas读取我们的数据,并使用numpy计算协方差矩阵:
```python
stocks = pd.read_csv('stock_data.csv', index_col=0)
returns = np.log(stocks / stocks.shift(1))
mean_returns = returns.mean()
cov_matrix = returns.cov()
```
接下来,我们可以使用以下代码计算有效边界:
```python
def portfolio_std(weights):
return np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
def portfolio_return(weights):
return np.dot(weights.T, mean_returns)
def optimal_portfolio(n):
n = len(mean_returns)
P = matrix(cov_matrix.values)
q = matrix(np.zeros((n, 1)))
G = matrix(np.concatenate((-np.transpose(np.array(mean_returns)), -np.identity(n)), 0))
h = matrix(np.concatenate((-np.ones((1, 1)) * 0.07, np.zeros((n, 1))), 0))
solvers.options['show_progress'] = False
sol = solvers.qp(P, q, G, h)
return np.array(sol['x']).flatten()
n_portfolios = 100
means, stds = np.column_stack([
(portfolio_return(optimal_portfolio(n)), portfolio_std(optimal_portfolio(n)))
for n in range(1, n_portfolios + 1)
])
```
这样就可以得到有效边界上的多个投资组合的收益率和风险(标准差)。最后,我们可以使用matplotlib绘制有效边界:
```python
plt.plot(stds, means, 'o', markersize=5)
plt.xlabel('risk')
plt.ylabel('return')
plt.title('Efficient Frontier')
plt.show()
```
完整的代码示例如下:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from cvxopt import matrix, solvers
# read stock data
stocks = pd.read_csv('stock_data.csv', index_col=0)
returns = np.log(stocks / stocks.shift(1))
mean_returns = returns.mean()
cov_matrix = returns.cov()
# portfolio functions
def portfolio_std(weights):
return np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
def portfolio_return(weights):
return np.dot(weights.T, mean_returns)
def optimal_portfolio(n):
n = len(mean_returns)
P = matrix(cov_matrix.values)
q = matrix(np.zeros((n, 1)))
G = matrix(np.concatenate((-np.transpose(np.array(mean_returns)), -np.identity(n)), 0))
h = matrix(np.concatenate((-np.ones((1, 1)) * 0.07, np.zeros((n, 1))), 0))
solvers.options['show_progress'] = False
sol = solvers.qp(P, q, G, h)
return np.array(sol['x']).flatten()
# efficient frontier
n_portfolios = 100
means, stds = np.column_stack([
(portfolio_return(optimal_portfolio(n)), portfolio_std(optimal_portfolio(n)))
for n in range(1, n_portfolios + 1)
])
# plot efficient frontier
plt.plot(stds, means, 'o', markersize=5)
plt.xlabel('risk')
plt.ylabel('return')
plt.title('Efficient Frontier')
plt.show()
```
请注意,这只是一个简单的示例。在实际应用中,可能需要更多的数据和更复杂的模型来获得更准确的结果。
阅读全文