# In[77]: # Import the CovarianceShrinkage object, it reduces/shrinks the errors/residuals while calculating the covariance matrix # Create the CovarianceShrinkage instance variable cs = CovarianceShrinkage(df4) # In[78]: # Difference in calculating covariance matrix through covariance shrinkage and through sample cov() method # Compute the sample covariance matrix of returns sample_cov = df4.pct_change().cov() * 252 # Compute the efficient covariance matrix of returns e_cov = cs.ledoit_wolf() # Display both the sample covariance_matrix and the efficient e_cov estimate print("Sample Covariance Matrix\n", sample_cov, "\n") print("Efficient Covariance Matrix\n", e_cov, "\n") # In[79]: # Although the differences between the sample covariance and the efficient covariance (found by shrinking errors) # may seem small, they have a huge impact on estimation of the optimal portfolio weights and the generation of the efficient # frontier. Practitioners generally use some form of efficient covariance for Modern Portfolio Theory. # In[80]: df4.head()
import pandas as pd import numpy as np from pypfopt.efficient_frontier import EfficientFrontier from pypfopt.objective_functions import negative_cvar from pypfopt.risk_models import CovarianceShrinkage ##Importar série de dados df = pd.read_excel(r'C:\Users\Jhona\OneDrive\Área de Trabalho\PRBR11.xlsx', index_col='Data') ##Obter os retornos dos ativos returns = pd.DataFrame() for i in df: returns[i] = df[i].pct_change().dropna() ##Criar a matrix de covariância eficiente covMatrix = CovarianceShrinkage(df) e_cov = covMatrix.ledoit_wolf() ##Fronteira ef = EfficientFrontier(None, e_cov) ##Encontrando o CVaR 95% minimizando optimal_weights = ef.custom_objective(negative_cvar, returns) print(optimal_weights)