利用python构建马科维茨
时间: 2023-05-30 21:03:06 浏览: 48
投资组合优化模型
马科维茨投资组合优化模型是一种经典的金融学模型,可以用于确定如何将一定数量的资金分配给不同的资产,以最大化预期收益或最小化风险。在本文中,我们将介绍如何使用Python构建一个马科维茨投资组合优化模型。
1. 数据准备
首先,我们需要准备一些数据来构建投资组合模型。我们可以使用pandas库中的数据读取函数来读取csv文件。为了方便起见,我们可以使用yfinance库从Yahoo Finance下载股票数据。
import pandas as pd
import yfinance as yf
#下载股票数据
symbols = ['AAPL', 'AMZN', 'GOOG', 'FB', 'TSLA']
data = yf.download(symbols,start="2020-01-01",end="2021-01-01")
#选择收盘价
prices = data['Adj Close']
接下来,我们需要计算每只股票的日收益率。我们可以使用pandas库的pct_change()函数来计算日收益率。
#计算日收益率
returns = prices.pct_change().dropna()
2. 构建投资组合优化模型
接下来,我们将使用SciPy库中的优化函数来构建投资组合优化模型。我们将优化目标设置为最小化投资组合的方差。我们还将设置一些约束条件,例如:资产的权重必须为正数,资产的权重之和必须等于1。
from scipy.optimize import minimize
#定义目标函数
def objective(weights, returns):
return weights.T @ returns.cov() @ weights
#定义约束条件
def constraints(weights):
return sum(weights)-1
cons = {'type':'eq', 'fun': constraints}
bounds = [(0,1) for i in range(len(symbols))]
#初始化权重
weights = [1/len(symbols) for i in range(len(symbols))]
#运行优化器
result = minimize(objective, weights, args=(returns,), constraints=cons, bounds=bounds)
print(result)
运行上述代码后,我们将得到最优权重,即每个资产在投资组合中的权重。
3. 结果分析
接下来,我们将使用最优权重计算投资组合的预期收益率和预期波动率。
#计算预期收益率
expected_return = returns.mean() @ result.x
print("Expected Return:", expected_return)
#计算预期波动率
expected_volatility = (result.x.T @ returns.cov() @ result.x)**0.5
print("Expected Volatility:", expected_volatility)
我们还可以使用matplotlib库将投资组合的预期收益率和预期波动率可视化。
import matplotlib.pyplot as plt
#绘制投资组合的有效前沿
def portfolio_variance(weights, returns):
return weights.T @ returns.cov() @ weights
def portfolio_return(weights, returns):
return weights @ returns.mean()
x = []
y = []
#计算有效前沿
for r in range(50):
ret = r/100
cons = ({'type':'eq', 'fun': constraints},
{'type':'eq', 'fun': lambda w: portfolio_return(w, returns) - ret})
result = minimize(portfolio_variance, weights, args=(returns,), constraints=cons, bounds=bounds)
if not result.success:
continue
x.append(portfolio_variance(result.x, returns)**0.5)
y.append(ret)
plt.plot(x, y, 'b-', linewidth=2)
plt.xlabel('Expected Volatility')
plt.ylabel('Expected Return')
plt.title('Efficient Frontier')
plt.show()
上述代码将绘制投资组合的有效前沿,即预期收益率和预期波动率之间的关系。我们可以使用这个图来选择最优的投资组合。
总结
在本文中,我们介绍了如何使用Python构建马科维茨投资组合优化模型。我们使用了yfinance库从Yahoo Finance下载股票数据,并使用SciPy库中的优化函数来计算最优权重。最后,我们使用matplotlib库将投资组合的有效前沿可视化。