from pypfopt.efficient_frontier import EfficientFrontier from pypfopt import risk_models from pypfopt import expected_returns yuce = pd.read_excel("E:/应统案例大赛/附件1-股票交易数据/yuceclose.xlsx",index_col=0) # 计算预期收益和样本协方差矩阵 mu3 = expected_returns.mean_historical_return(yuce) # 使用历史数据计算预期收益 S3 = risk_models.sample_cov(yuce) # 使用历史数据计算协方差矩阵 # Optimize for maximal Sharpe ratio ef = EfficientFrontier(mu3, S3) raw_weights = ef.max_sharpe() cleaned_weights = ef.clean_weights() ef.save_weights_to_file("yuceweight1.csv") # saves to file print(cleaned_weights) ef.portfolio_performance(verbose=True) # 设置无风险回报率为0 risk_free = 0 # 计算每项资产的夏普比率 RandomPortfolios['Sharpe'] = (RandomPortfolios.Returns - risk_free) / RandomPortfolios.Volatility # 绘制收益-标准差的散点图,并用颜色描绘夏普比率 plt.scatter(RandomPortfolios.Volatility, RandomPortfolios.Returns, c=RandomPortfolios.Sharpe) plt.colorbar(label='Sharpe Ratio') plt.show()修改后面的代码,与前面匹配
时间: 2024-02-25 12:51:55 浏览: 127
Efficient Frontier using different risk return measure:用于寻找最佳投资组合和绘制差异的有效边界的代码。 风险回报措施-matlab开发
可以使用以下代码来绘制资产收益-标准差的散点图,并用颜色描绘夏普比率:
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 读取预测收盘价数据
yuce = pd.read_excel("E:/应统案例大赛/附件1-股票交易数据/yuceclose.xlsx", index_col=0)
# 计算预期收益和样本协方差矩阵
mu3 = expected_returns.mean_historical_return(yuce) # 使用历史数据计算预期收益
S3 = risk_models.sample_cov(yuce) # 使用历史数据计算协方差矩阵
# 使用EfficientFrontier类优化投资组合
ef = EfficientFrontier(mu3, S3)
raw_weights = ef.max_sharpe()
cleaned_weights = ef.clean_weights()
ef.save_weights_to_file("yuceweight1.csv") # 保存权重到文件
print(cleaned_weights)
ef.portfolio_performance(verbose=True)
# 生成随机投资组合
np.random.seed(1)
n_samples = 10000
weights = np.random.dirichlet(np.ones(len(yuce.columns)), n_samples)
returns = weights.dot(mu3)
volatility = np.sqrt(np.diag(weights @ S3 @ weights.T))
df = pd.DataFrame({'Returns': returns, 'Volatility': volatility})
# 计算夏普比率
risk_free = 0
df['Sharpe'] = (df.Returns - risk_free) / df.Volatility
# 绘制资产收益-标准差的散点图,并用颜色描绘夏普比率
plt.scatter(df.Volatility, df.Returns, c=df.Sharpe, cmap='viridis')
plt.colorbar(label='Sharpe Ratio')
plt.xlabel('Volatility')
plt.ylabel('Expected Return')
plt.show()
```
此代码将资产收益-标准差作为散点图进行可视化,并用颜色描绘夏普比率。可以通过修改yuce变量中的值来适应不同的投资组合。
阅读全文