Carregando pacotes

library(quantmod)
library(forecast)
library(lmtest)
library(DEoptim)
library(quantmod)
library(PortfolioAnalytics)
library(PerformanceAnalytics)
library(quadprog)
library(fPortfolio)
library(CovTools)

loading the assets

pdados <- function(symbols,StartDat,EndDat){
  symbolData <- new.env()
  getSymbols(symbols, env = symbolData, src = "yahoo", from = StartDat, to = EndDat)
  plist <- eapply(symbolData,Ad)
  nomlist <- names(plist)
  pframe <- do.call(merge, plist)
  colnames(pframe) <- nomlist
  pframe <- pframe[,sort(nomlist)]
  plist <- eapply(symbolData, Vo)
  nomlist <- paste("v",names(plist),sep = "_")
  pframevol <- do.call(merge, plist)
  colnames(pframevol) <- nomlist
  pframevol <- pframevol[,sort(nomlist)]
  merge(pframe,pframevol)
}

StartDat <- as.Date("2016-01-01")
EndDat <- as.Date("2020-08-25")
symbols <- c("^BVSP","MRFG3.SA","VALE3.SA","BRL=X","RAIL3.SA","BOVA11.SA","VIVT3.SA","JHSF3.SA","BBDC4.SA","BRML3.SA","BBSE3.SA","B3SA3.SA","CYRE3.SA")
pframe <- pdados(symbols,StartDat,EndDat)
pframe <- pframe[!is.na(pframe$BVSP),]
pframe <- pframe[,1:13]
rets <- ROC(pframe[,1:length(symbols)])
rets <- rets[-1,]
BVSP <- rets[,7]
rets <- rets[,-7]
colnames(rets) <- c("B3","BBDC4","BBSE3","BOVA11","USD","BRML3","CYRE3","JHSF3","MRFG3","RAIL3","VALE3","VIVT3")
n <- dim(rets)[2]
per <- dim(rets)[1]
nomat <- names(rets)
carteira1 <- rets[,c(2,3,4,5,9,10,11)] # With BOVA and Dolar
carteira2 <- rets[,c(1,2,4,6,8,9,11,12)] # Without Dolar

Portfolio 1 Minimum Variance without restrictions

carteira1_estima <- carteira1[paste("/","2017-12-31",sep = "")]
carteira1_estima <- carteira1_estima[-dim(carteira1_estima)[1]]

carteira1_teste <- carteira1[paste("2018-01-01","/",sep = "")]

cova1 <- cov(carteira1_estima, use = "pairwise.complete.obs", method = "pearson")
retesp1 <- apply(carteira1_estima,2, mean, na.rm = T)
riscoretorig1 <- data.frame(Risco = diag(cova1)^0.5,Retorno = retesp1)

Mport1vm <- portfolio.spec(assets = colnames(carteira1_teste))
Mport1vm <- add.constraint(Mport1vm, type = "weight_sum", min = 1, max = 1.1)
Mport1vm <- add.constraint(Mport1vm, type = "box", max = 0.4, min = -0.4)
Mport1vm <- add.objective(Mport1vm, type = "risk", name = "var")
Mport1vm <- optimize.portfolio(R = carteira1_teste, portfolio = Mport1vm, optimize_method = "DEoptim")
Pesos <- summary(Mport1vm)$weights
Weight_MV1 <- as.vector(Pesos)
Weight_MV1
## [1] -0.1233613348  0.3569774971  0.3343226585  0.3640018520 -0.0189860209
## [6]  0.0001548459  0.0955990461
ret1vm <- Return.portfolio(carteira1_teste,Weight_MV1)
retesp1vm <- sum(Weight_MV1 * retesp1)
desvesp1vm <- t(Weight_MV1) %*% cova1 %*% Weight_MV1
r1vm <- Return.cumulative(ret1vm)

Portfolio 2 Minimum Variance without restrictions

carteira2_estima <- carteira2[paste("/","2017-12-31",sep = "")]
carteira2_estima <- carteira2_estima[-dim(carteira2_estima)[1]]

carteira2_teste <- carteira2[paste("2018-01-01","/",sep = "")]

cova2 <- cov(carteira2_estima, use = "pairwise.complete.obs", method = "pearson")
retesp2 <- apply(carteira2_estima,2, mean, na.rm = T)
riscoretorig2 <- data.frame(Risco = diag(cova2)^0.5,Retorno = retesp2)

Mport2vm <- portfolio.spec(assets = colnames(carteira2_teste))
Mport2vm <- add.constraint(Mport2vm, type = "weight_sum", min = 1, max = 1.1)
Mport2vm <- add.constraint(Mport2vm, type = "box", max = 0.4, min = -0.4)
Mport2vm <- add.objective(Mport2vm, type = "risk", name = "var")
Mport2vm <- optimize.portfolio(R = carteira2_teste, portfolio = Mport2vm, optimize_method = "DEoptim")
Pesos <- summary(Mport2vm)$weights
Weight_MV2 <- as.vector(Pesos)
ret2vm <- Return.portfolio(carteira2_teste,Weight_MV2)
retesp2vm <- sum(Weight_MV2 * retesp2)
desvesp2vm <- t(Weight_MV2) %*% cova2 %*% Weight_MV2
r2vm <- Return.cumulative(ret2vm)
comp <- data.frame(Carteira1 = c(r1vm,retesp1vm,desvesp1vm), Carteira2 = c(r2vm,retesp2vm,desvesp2vm), row.names = c("Retorno Acumulado","Ret. Esperado Diário", "Desv. Esp. Diário"))
mergxtslist <- function(xtslist,nomes){
  rests = do.call("merge.xts",xtslist)
  colnames(rests) = nomes
  rests[rowSums(!is.na(rests)) >= length(xtslist),]
}
result <- mergxtslist(list(ret1vm,ret2vm),c("Carteira 1","Carteira 2"))
charts.PerformanceSummary(result, main = "COMPARAÇÃO DE CARTEIRAS")

# PERCEBA QUE A CARTEIRA COM DÓLAR E ALGUNS ATIVOS COM RECEITA E DESPESA DOLARIZADA TEVE UMA VARIAÇÃO E UM DRAWDONW MENOR. 

.

Tangency Portfolio 1

carteira1_estima <- as.data.frame(carteira1_estima)
data1 <- timeSeries(ts(carteira1_estima, frequency = 1, start = c(2016,1,1)))
data1 <- na.omit(data1)
Spec1 <- portfolioSpec()
setTargetReturn(Spec1) <- mean(colMeans(data1, na.rm = T)) 
setRiskFreeRate(Spec1) <- 0.0002  
setNFrontierPoints(Spec1) <- 100
PT1 <- tangencyPortfolio(data1,Spec1,constraints = c("maxW[1:7]=0.4","maxsumW[1:7]=1.1"))
PT1
## 
## Title:
##  MV Tangency Portfolio 
##  Estimator:         covEstimator 
##  Solver:            solveRquadprog 
##  Optimize:          minRisk 
##  Constraints:       maxW maxsumW 
## 
## Portfolio Weights:
##  BBDC4  BBSE3 BOVA11    USD  MRFG3  RAIL3  VALE3 
## 0.4000 0.0000 0.1609 0.0000 0.0000 0.0758 0.3633 
## 
## Covariance Risk Budgets:
##  BBDC4  BBSE3 BOVA11    USD  MRFG3  RAIL3  VALE3 
## 0.3332 0.0000 0.0971 0.0000 0.0000 0.0624 0.5073 
## 
## Target Returns and Risks:
##   mean    Cov   CVaR    VaR 
## 0.0019 0.0211 0.0456 0.0317 
## 
## Description:
##  Mon Sep 07 18:49:45 2020 by user: Home
Weight_PT1 <- getWeights(PT1)
PMV1 <- minvariancePortfolio(data1,Spec1,constraints = c("maxW[1:7]=0.4","maxsumW[1:7]=1.1"))
PMV1 <- getWeights(PMV1)
PMV1
##       BBDC4       BBSE3      BOVA11         USD       MRFG3       RAIL3 
## 0.000000000 0.078355193 0.400000000 0.400000000 0.120612063 0.001032744 
##       VALE3 
## 0.000000000

Tangency Portfolio 2

carteira2_estima <- as.data.frame(carteira2_estima)
data2 <- timeSeries(ts(carteira2_estima, frequency = 1, start = c(2016,1,1)))
data2 <- na.omit(data2)
Spec2 <- portfolioSpec()
setTargetReturn(Spec2) <- mean(colMeans(data2, na.rm = T)) 
setRiskFreeRate(Spec2) <- 0.0002  
setNFrontierPoints(Spec2) <- 100
PT2 <- tangencyPortfolio(data2,Spec2,constraints = c("maxW[1:7]=0.4","maxsumW[1:7]=1.1"))
PT2
## 
## Title:
##  MV Tangency Portfolio 
##  Estimator:         covEstimator 
##  Solver:            solveRquadprog 
##  Optimize:          minRisk 
##  Constraints:       maxW maxsumW 
## 
## Portfolio Weights:
##     B3  BBDC4 BOVA11  BRML3  JHSF3  MRFG3  VALE3  VIVT3 
## 0.3693 0.3562 0.0000 0.0000 0.0000 0.0000 0.2095 0.0649 
## 
## Covariance Risk Budgets:
##     B3  BBDC4 BOVA11  BRML3  JHSF3  MRFG3  VALE3  VIVT3 
## 0.3230 0.3740 0.0000 0.0000 0.0000 0.0000 0.2765 0.0265 
## 
## Target Returns and Risks:
##   mean    Cov   CVaR    VaR 
## 0.0019 0.0183 0.0376 0.0274 
## 
## Description:
##  Mon Sep 07 18:49:46 2020 by user: Home
getWeights(PT2)
##         B3      BBDC4     BOVA11      BRML3      JHSF3      MRFG3      VALE3 
## 0.36934297 0.35623057 0.00000000 0.00000000 0.00000000 0.00000000 0.20953863 
##      VIVT3 
## 0.06488783
Weight_PT2 <- getWeights(PT2)
PMV2 <- minvariancePortfolio(data2,Spec2,constraints = c("maxW[1:7]=0.4","maxsumW[1:7]=1.1"))
PMV2 <- getWeights(PMV2)
PMV2
##          B3       BBDC4      BOVA11       BRML3       JHSF3       MRFG3 
## 0.124019771 0.000000000 0.400000000 0.000000000 0.004570618 0.189482602 
##       VALE3       VIVT3 
## 0.000000000 0.281927010

FRONTIER

fronteira1 = portfolioFrontier(data1,Spec1,constraints = c("maxW[1:7]=0.4","maxsumW[1:7]=1.1"))
fronteira2 <- portfolioFrontier(data2,Spec2,constraints = c("maxW[1:7]=0.4","maxsumW[1:7]=1.1"))

frontierPlot(fronteira1,col = 1:2,pch = 19, main = "Carteira 1")

frontierPlot(fronteira2, col = 3:4, pch = 19, main = "Carteira 2")

## Carteira 2 mais arriscada mas tem um maior retorno esperado
cva <- cov(cbind(data1,data1$BOVA11))
MVCf <- shrinkEstimator(cbind(data1,data1$BOVA11))
MVCc1 <- CovEst.2003LW(cbind(data1,data1$BOVA11))
MVCc2 <- CovEst.2010RBLW(cbind(data1,data1$BOVA11))
dft <- data.frame(cov = diag(cva)^0.5,shrinkEstimator = diag(MVCf$Sigma)^0.5,CovEst.2003LW = diag(MVCc1$S)^0.5,CovEst.2010RBLW = diag(MVCc2$S)^0.5)

mvtportf <- function(cov,eresp){
  icov = solve(cov)
  uns = rep(1,ncol(cov))
  mv = icov %*% uns
  mv = mv/sum(mv)
  tp = icov %*% as.vector(eresp)
  tp = tp/sum(tp)
  data.frame(VM = mv, PT = tp)
}
# CARTEIRA 1
excret <- colMeans(data1,na.rm = T) - 0.0003
CAmostral <- mvtportf(cov(data1),excret)
CEncolhida <- mvtportf(CovEst.2010RBLW(data1)$S,excret)
CEncolhida
##                  VM         PT
## BBDC4  -0.024762385 -1.3379313
## BBSE3   0.044939875  0.6056662
## BOVA11  0.355495957  0.3627595
## USD     0.591413196  1.7796778
## MRFG3   0.056006993  0.2846688
## RAIL3   0.002368486 -0.1311461
## VALE3  -0.025462123 -0.5636948
comp_cov <- data.frame(CEncolhida,CAmostral)
comp_cov
##                  VM         PT          VM.1       PT.1
## BBDC4  -0.024762385 -1.3379313 -0.0427238947 -1.2106936
## BBSE3   0.044939875  0.6056662  0.0324385829  0.5341521
## BOVA11  0.355495957  0.3627595  0.3987423732  0.4279528
## USD     0.591413196  1.7796778  0.6000855104  1.6238462
## MRFG3   0.056006993  0.2846688  0.0447887065  0.2315425
## RAIL3   0.002368486 -0.1311461 -0.0002162242 -0.1155854
## VALE3  -0.025462123 -0.5636948 -0.0331150541 -0.4912145
r1 <- Return.portfolio(carteira1_teste,CEncolhida$PT)
r1pt <- Return.cumulative(r1)
r1vm <- Return.portfolio(carteira1_teste,CEncolhida$VM)
r1vm <- Return.cumulative(r1vm)
r1apt <- Return.portfolio(carteira1_teste,CAmostral$PT)
r1apt <- Return.cumulative(r1apt)
r1avm <- Return.portfolio(carteira1_teste,CAmostral$VM)
r1avm <- Return.cumulative(r1avm)
ret_comp <- data.frame(TangEnc= r1pt, TangAm = r1apt,VMEnc = r1vm,VMAm = r1avm)
ret_comp
##                   portfolio.returns portfolio.returns.1 portfolio.returns.2
## Cumulative Return          1.574129            1.435397            0.463403
##                   portfolio.returns.3
## Cumulative Return           0.4687871
# CARTEIRA 2
excret2 <- colMeans(data2,na.rm = T) - 0.0003
dim(cov(data2))
## [1] 8 8
CAmostral2 <- mvtportf(cov(data2),excret2)
CEncolhida2 <- mvtportf(CovEst.2010RBLW(data2)$S,excret2)
comp_cov2 <- data.frame(CEncolhida2,CAmostral2)
comp_cov2
##                 VM         PT        VM.1       PT.1
## B3      0.14869090  0.7802460  0.13988028  0.8557248
## BBDC4  -0.12301371  0.8905842 -0.15592758  0.9921344
## BOVA11  0.57944567 -0.5657255  0.67383000 -0.7746154
## BRML3  -0.01712415 -0.1605537 -0.03660023 -0.1680745
## JHSF3   0.01473266 -0.1862862  0.01203432 -0.1937108
## MRFG3   0.18189940 -0.3962214  0.17281976 -0.4130498
## VALE3  -0.05546982  0.4544733 -0.06847297  0.4924992
## VIVT3   0.27083906  0.1834833  0.26243643  0.2090921
r2 <- Return.portfolio(carteira2_teste,CEncolhida2$PT) 
r2pt <- Return.cumulative(r2) 
r2vm <- Return.portfolio(carteira2_teste,CEncolhida2$VM)
r2vm <- Return.cumulative(r2vm)
r2apt <- Return.portfolio(carteira2_teste,CAmostral2$PT)
r2apt <- Return.cumulative(r2apt)
r2avm <- Return.portfolio(carteira2_teste,CAmostral2$VM)
r2avm <- Return.cumulative(r2avm)
ret_comp2 <- data.frame(TangEnc= r2pt, TangAm = r2apt,VMEnc = r2vm,VMAm = r2avm)
ret_comp2
##                   portfolio.returns portfolio.returns.1 portfolio.returns.2
## Cumulative Return         0.2762074            0.311839           0.4998784
##                   portfolio.returns.3
## Cumulative Return           0.5002247
inicio <- as.Date("2016-01-01")
fim <- as.Date("2020-08-25")
tickers <- c("^BVSP","MRFG3.SA","VALE3.SA","COGN3.SA","RAIL3.SA","BRML3.SA","BBAS3.SA","BBDC4.SA","ITUB4.SA")

ativos <- pdados(tickers,inicio,fim)
## pausing 1 second between requests for more than 5 symbols
## pausing 1 second between requests for more than 5 symbols
## pausing 1 second between requests for more than 5 symbols
## pausing 1 second between requests for more than 5 symbols
## pausing 1 second between requests for more than 5 symbols
ativos <- ativos[!is.na(ativos$BVSP),]
ativos <- ativos[,1:9]


rets <- ROC(ativos[,1:8])
rets <- rets[-1,]
BVSP <- rets[,4]
rets <- rets[,-4]
colnames(rets) <- c("BBAS3","BBDC4","BRML3","COGN3","ITUB4","MRFG3","RAIL3")
n <- dim(rets)[2]
per <- dim(rets)[1]
nomat <- names(rets)

restima <- rets[paste("/","2017-12-31",sep = "")]
restima <- restima[-dim(restima)[1]]
rteste <- rets[paste("2018-01-01","/",sep = "")]
dates <- c(as.Date("2017-12-31"), time(rteste[endpoints(rteste,on = "quarters")]))
cova <- cov(restima, use = "pairwise.complete.obs", method = "pearson")
retesp <- apply(restima,2, mean, na.rm = T)
riscoretorig <- data.frame(Risco = diag(cova)^0.5,Retorno = retesp)
riscoretorig
##            Risco      Retorno
## BBAS3 0.03072318 0.0017822187
## BBDC4 0.02255189 0.0019793997
## BRML3 0.02140317 0.0011447707
## COGN3 0.02525609 0.0014631155
## ITUB4 0.01938621 0.0014577836
## MRFG3 0.02161196 0.0003263846
## RAIL3 0.04337674 0.0015638615
rf <- 0.0002
# Portfolio Variância Mínima
icov <- solve(cova)
uns <- rep(1,n)
vm <- icov %*% uns
vm <- vm/sum(vm)
vm <- as.vector(vm)
retorno <- Return.portfolio(rteste,vm)

# Portfolio Ingênuo (B&H)
pesos <- rep(1/7,7)
ing <- Return.portfolio(rteste,pesos)

# Timing de Volatilidade (B&H)
cov <- cov(restima, use = "pairwise.complete.obs")
var <- diag(cov)
wVT <- (1/var)^4/sum((1/var)^4)
t(wVT)
##           BBAS3     BBDC4     BRML3      COGN3     ITUB4     MRFG3        RAIL3
## [1,] 0.01084366 0.1286592 0.1954697 0.05199662 0.4314801 0.1808639 0.0006868301
retVT <- Return.portfolio(rteste, as.vector(wVT))

mergxtslist <- function(xtslist,nomes){
  rests = do.call("merge.xts",xtslist)
  colnames(rests) = nomes
  rests[rowSums(!is.na(rests)) >= length(xtslist),]
}

comp <- mergxtslist(list(retorno,ing,retVT),c("Portfolio Variância Mínima","Portfolio Ingenuo","Portfolio Timing Volatilidade"))
summary(comp)
##      Index            Portfolio Variância Mínima Portfolio Ingenuo   
##  Min.   :2018-01-02   Min.   :-0.1479083         Min.   :-1.682e-01  
##  1st Qu.:2018-08-28   1st Qu.:-0.0104374         1st Qu.:-9.342e-03  
##  Median :2019-05-04   Median : 0.0005852         Median : 1.464e-03  
##  Mean   :2019-04-30   Mean   : 0.0001755         Mean   : 7.902e-05  
##  3rd Qu.:2019-12-26   3rd Qu.: 0.0120115         3rd Qu.: 1.045e-02  
##  Max.   :2020-08-24   Max.   : 0.1208230         Max.   : 1.465e-01  
##  Portfolio Timing Volatilidade
##  Min.   :-1.424e-01           
##  1st Qu.:-9.990e-03           
##  Median : 1.512e-03           
##  Mean   : 4.523e-05           
##  3rd Qu.: 1.094e-02           
##  Max.   : 1.219e-01
apply(comp,2,sd)
##    Portfolio Variância Mínima             Portfolio Ingenuo 
##                    0.02214822                    0.02272293 
## Portfolio Timing Volatilidade 
##                    0.02186062
Return.annualized(comp)
##                   Portfolio Variância Mínima Portfolio Ingenuo
## Annualized Return                -0.01876044        -0.0456267
##                   Portfolio Timing Volatilidade
## Annualized Return                   -0.04867054
sd.annualized(comp)
##                               Portfolio Variância Mínima Portfolio Ingenuo
## Annualized Standard Deviation                  0.3515921         0.3607154
##                               Portfolio Timing Volatilidade
## Annualized Standard Deviation                     0.3470266
SharpeRatio(comp,Rf = rf)
##                               Portfolio Variância Mínima Portfolio Ingenuo
## StdDev Sharpe (Rf=0%, p=95%):              -0.0011074010      -0.005324039
## VaR Sharpe (Rf=0%, p=95%):                 -0.0006306149      -0.003152822
## ES Sharpe (Rf=0%, p=95%):                  -0.0002405691      -0.001131209
##                               Portfolio Timing Volatilidade
## StdDev Sharpe (Rf=0%, p=95%):                  -0.007080023
## VaR Sharpe (Rf=0%, p=95%):                     -0.004124426
## ES Sharpe (Rf=0%, p=95%):                      -0.001652894
lapply(comp,table.Drawdowns)
## $`Portfolio Variância Mínima`
##         From     Trough         To   Depth Length To Trough Recovery
## 1 2020-02-20 2020-03-18       <NA> -0.4753    127        17       NA
## 2 2018-04-13 2018-09-13 2019-09-13 -0.2535    351       106      245
## 3 2018-02-02 2018-03-21 2018-04-10 -0.1249     44        31       13
## 4 2020-01-16 2020-02-10 2020-02-19 -0.0854     25        18        7
## 5 2019-12-16 2019-12-23 2020-01-14 -0.0601     18         6       12
## 
## $`Portfolio Ingenuo`
##         From     Trough         To   Depth Length To Trough Recovery
## 1 2020-01-03 2020-03-23       <NA> -0.5220    161        54       NA
## 2 2018-02-02 2018-09-13 2019-01-14 -0.2631    231       152       79
## 3 2019-02-06 2019-05-17 2019-07-04 -0.1540    101        68       33
## 4 2019-07-11 2019-08-26 2019-09-20 -0.0997     52        33       19
## 5 2019-09-23 2019-10-08 2019-10-22 -0.0404     22        12       10
## 
## $`Portfolio Timing Volatilidade`
##         From     Trough         To   Depth Length To Trough Recovery
## 1 2020-01-06 2020-03-23       <NA> -0.5102    160        53       NA
## 2 2018-01-29 2018-09-13 2019-01-03 -0.2498    228       156       72
## 3 2019-02-05 2019-05-17 2019-09-20 -0.1640    157        69       88
## 4 2019-10-29 2019-11-26 2019-12-13 -0.0545     32        19       13
## 5 2019-09-27 2019-10-08 2019-10-16 -0.0507     14         8        6
charts.PerformanceSummary(comp)

when comparing a portfolio consisting of BBDC4, BBSE3, BOVA11, DOLLAR, MRFG3, RAIL3 and VALE3, that is, a balance between defensive assets (BBDC4, BOVA11, RAIL3, VALE3), dollar assets (MRFG3, USD, VALE3) and aggressive assets (MRFG3), with a portfolio composed of BBDC4, B3, BOVA11, BRML3, JHSF3, MRFG3, VALE3, VIVT3, that is, also a balance between defensive assets (B3, BBDC4, BOVA11, VALE3, VIVT3) and offensive (JHSF3, MRFG3), the results showed that the dollar hedged portfolio proved to be resilient in backtesting, accumulating a higher return for both the minimum variance and the tangent.

when setting up the efficient frontier of both portfolios, it was noticed that, even having a smaller cumulative return in the test period, the frontier of portfolio 2 indicates a higher expected return as a greater variance, or that is, shifted to the right and upwards compared to border 1. In this sense, it is concluded that the dollar is a good hedge for a portfolio, however, it can decrease the return in scenarios with a large rise in the stock market.