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("yuceweight.csv") # saves to file print(cleaned_weights) ef.portfolio_performance(verbose=True)如何绘图表示
时间: 2024-02-25 11:51:46 浏览: 33
可以使用matplotlib库绘制有效前沿图。代码示例如下:
```
import numpy as np
import matplotlib.pyplot as plt
# 计算有效前沿
ef = EfficientFrontier(mu3, S3)
raw_frontier = ef.efficient_frontier()
cleaned_frontier = ef.clean_frontier()
# 绘制有效前沿图
fig, ax = plt.subplots()
ax.plot(cleaned_frontier[0], cleaned_frontier[1], label='Efficient Frontier')
ax.plot(np.sqrt(np.diagonal(S3)), mu3, 'o', markersize=5, label='Stocks')
ax.set_title('Efficient Frontier')
ax.set_xlabel('Volatility')
ax.set_ylabel('Expected Return')
ax.legend()
plt.show()
```
此代码将有效前沿和各个资产的预期收益率和波动率作为散点图进行可视化,并标注有效前沿的位置。可以通过修改mu3和S3变量中的值来适应不同的投资组合。
相关问题
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()修改后面的代码,与前面匹配
可以使用以下代码来绘制资产收益-标准差的散点图,并用颜色描绘夏普比率:
```
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变量中的值来适应不同的投资组合。
import pandas as pd # 读取包含股票收盘价数据的表格 df = pd.read_csv("E:/应统案例大赛/附件1-股票交易数据/yuce5.csv",encoding='utf-8', index_col=0, parse_dates=True) # 计算前一天的收盘价数据 df_shift = df.shift(1) # 计算每支股票的每日收益率 returns = (df - df_shift) / df_shift # 打印结果 print(returns.head())UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 0: invalid continuation byte
这个错误通常是由于尝试使用错误的字符编码解码包含非ASCII字符的文本文件导致的。
解决此问题的方法是使用正确的字符编码打开文件。如果不确定文件的字符编码,可以尝试使用一些自动检测字符编码的工具,如chardet库。
下面是一个示例代码,展示如何解决此问题:
```python
import pandas as pd
import chardet
# 自动检测文件的字符编码
with open('E:/应统案例大赛/附件1-股票交易数据/yuce5.csv', 'rb') as f:
result = chardet.detect(f.read())
# 用检测到的字符编码打开文件
df = pd.read_csv('E:/应统案例大赛/附件1-股票交易数据/yuce5.csv', encoding=result['encoding'], index_col=0, parse_dates=True)
# 计算前一天的收盘价数据
df_shift = df.shift(1)
# 计算每支股票的每日收益率
returns = (df - df_shift) / df_shift
# 打印结果
print(returns.head())
```
在这个示例中,我们首先使用`chardet.detect()`函数自动检测文件的字符编码,然后再使用检测到的字符编码打开文件。最终得到了正确的结果。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)