PyCharm 代码无法运行的常见问题及解决方法:最小化组合风险的权重计算
该代码缺少主函数定义和调用,需要添加以下代码:
def objective_function(weights, cov):
portfolio_variance = np.dot(weights.T, np.dot(cov, weights))
return portfolio_variance
weights_initial = np.ones(len(codes))/len(codes) #初始化权重
bounds = tuple((0,1) for i in range(len(codes))) #约束:权重必须介于0和1之间
constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1}) #约束条件:权重之和为1
result = minimize(objective_function, weights_initial, args=(cov,), bounds=bounds, constraints=constraints)
print('最小化组合风险的权重为:', result.x)
完整代码如下:
import akshare as ak
import numpy as np
import pandas as pd
from scipy.optimize import minimize
# 读入5支股票 2015-01-01 到 2021-12-31 日收盘价数据,并计算对数收益率
def get_ret(code):
data = ak.stock_zh_a_hist(symbol=code, period='daily', start_date='20150101', end_date='20211231', adjust='')
data.index = pd.to_datetime(data['日期'], format='%Y-%m-%d') #设置日期索引
close = data['收盘'] #日收盘价
close.name = code
ret = np.log(close/close.shift(1)) #日收益率
return ret
codes = ['000001', '000651', '300015', '600519', '000625']
ret = pd.DataFrame()
for code in codes:
ret_ = get_ret(code)
ret = pd.concat([ret, ret_], axis=1)
ret = ret.dropna()
R_cov = ret.cov() #计算协方差
cov = np.array(R_cov)
def objective_function(weights, cov):
portfolio_variance = np.dot(weights.T, np.dot(cov, weights))
return portfolio_variance
weights_initial = np.ones(len(codes))/len(codes) #初始化权重
bounds = tuple((0,1) for i in range(len(codes))) #约束:权重必须介于0和1之间
constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1}) #约束条件:权重之和为1
result = minimize(objective_function, weights_initial, args=(cov,), bounds=bounds, constraints=constraints)
print('最小化组合风险的权重为:', result.x)
原文地址: https://www.cveoy.top/t/topic/n3wa 著作权归作者所有。请勿转载和采集!