INTRODUÇÃO

Este relatório tem por objetivo organizar o estudo de otimização de portfólio.

  • Etapa 1: Selecionar ativos;
  • Etapa 2: Otimizar o Portfólio;
  • Etapa 3: Realizar análise de Desempenho e Risco.

ETAPA 1 - SELEÇÃO DE ATIVOS

Inicialmente, serão considerados alguns ativos, sem maior aprofundamento. São eles:

  • Ibovespa (^BVSP);
  • Bradesco (BBDC3.SA);
  • Itaú (ITUB3.SA);
  • Petrobras (PETR3.SA);
  • Gerdau (GOAU3.SA);
  • Cemig (CMIG3.SA).

Para obtenção dos dados será utilizada a função getsymbols do pacote quantmod.

#PACOTES UTILIZADOS: ----
library(quantmod)

#IMPORTAÇÃO DOS DADOS: ----
ibovespa <- getSymbols(Symbols = '^BVSP',
                       from = Sys.Date()-90,
                       to = Sys.Date(),
                       auto.assign = FALSE)

bradesco <- getSymbols(Symbols = 'BBDC3.SA',
                       from = Sys.Date()-90,
                       to = Sys.Date(),
                       auto.assign = FALSE)

itau <- getSymbols(Symbols = 'ITUB3.SA',
                       from = Sys.Date()-90,
                       to = Sys.Date(),
                       auto.assign = FALSE)

petrobras <- getSymbols(Symbols = 'PETR3.SA',
                       from = Sys.Date()-90,
                       to = Sys.Date(),
                       auto.assign = FALSE)

gerdau <- getSymbols(Symbols = 'GOAU3.SA',
                       from = Sys.Date()-90,
                       to = Sys.Date(),
                       auto.assign = FALSE)

cemig <- getSymbols(Symbols = 'CMIG3.SA',
                       from = Sys.Date()-90,
                       to = Sys.Date(),
                       auto.assign = FALSE)

O código acima “cria” objetos com os preços de abertura, fechamento, mais alto, mais baixo, ajustado e volume operações para cada ação. O obejto é do tipo xts (série temporal). O próximo passo consiste em “juntar” o preço ajustado de todas os ativos em uma tabela única contendo uma coluna com as datas.

#PACOTES UTILIZADOS: ----
library(magrittr)
library(tibble)
library(janitor)
library(dplyr)

#ORGANIZANDO AS TABELAS: ----
tabela_ibovespa <- ibovespa %>% 
  as.data.frame() %>% # transforma em tabela (xts -> data.frame)
  rownames_to_column() %>% # transforma a data da linha em coluna
  clean_names() %>% #altera o nome das colunas
  select(rowname, bvsp_adjusted) %>% 
  rename("data" = rowname)

tabela_bradesco <- bradesco %>% 
  as.data.frame() %>% # transforma em tabela (xts -> data.frame)
  rownames_to_column() %>% # transforma a data da linha em coluna
  clean_names() %>% #altera o nome das colunas
  select(rowname, bbdc3_sa_adjusted) %>% 
  rename("data" = rowname)

tabela_itau <- itau %>% 
  as.data.frame() %>% # transforma em tabela (xts -> data.frame)
  rownames_to_column() %>% # transforma a data da linha em coluna
  clean_names() %>% #altera o nome das colunas
  select(rowname, itub3_sa_adjusted) %>% 
  rename("data" = rowname)


tabela_petrobras <- petrobras %>% 
  as.data.frame() %>% # transforma em tabela (xts -> data.frame)
  rownames_to_column() %>% # transforma a data da linha em coluna
  clean_names() %>% #altera o nome das colunas
  select(rowname, petr3_sa_adjusted) %>% 
  rename("data" = rowname)

tabela_gerdau <- gerdau %>% 
  as.data.frame() %>% # transforma em tabela (xts -> data.frame)
  rownames_to_column() %>% # transforma a data da linha em coluna
  clean_names() %>% #altera o nome das colunas
  select(rowname, goau3_sa_adjusted) %>% 
  rename("data" = rowname)

tabela_cemig <- cemig %>% 
  as.data.frame() %>% # transforma em tabela (xts -> data.frame)
  rownames_to_column() %>% # transforma a data da linha em coluna
  clean_names() %>% #altera o nome das colunas
  select(rowname, cmig3_sa_adjusted) %>% 
  rename("data" = rowname)


consolidado <- tabela_ibovespa %>% 
  bind_cols(tabela_bradesco[2],
             tabela_itau[2],
             tabela_petrobras[2],
             tabela_gerdau[2],
             tabela_cemig[2])


#MELHOR MANEIRA PARA JUNTAR AS COLUNAS (olha se as datas estão batendo)
consolidado <- tabela_ibovespa %>% 
  full_join(tabela_bradesco, by = c('data' = 'data')) %>% 
  full_join(tabela_itau, by = c('data' = 'data')) %>% 
  full_join(tabela_petrobras, by = c('data' = 'data')) %>% 
  full_join(tabela_gerdau, by = c('data' = 'data')) %>%
  full_join(tabela_cemig, by = c('data' = 'data'))


consolidado
##          data bvsp_adjusted bbdc3_sa_adjusted itub3_sa_adjusted
## 1  2023-06-30        118087          14.58685          24.18762
## 2  2023-07-03        119673          14.77616          24.54068
## 3  2023-07-04        119076          14.63377          24.51107
## 4  2023-07-05        119549          14.65372          24.66901
## 5  2023-07-06        117426          14.31456          24.65914
## 6  2023-07-07        118898          14.46419          24.97503
## 7  2023-07-10        117942          14.47416          24.72824
## 8  2023-07-11        117220          14.34448          24.42222
## 9  2023-07-12        117666          14.25471          24.25441
## 10 2023-07-13        119264          14.54399          24.43209
## 11 2023-07-14        117711          14.48414          24.18530
## 12 2023-07-17        118219          14.65372          24.52094
## 13 2023-07-18        117841          14.59387          24.38274
## 14 2023-07-19        117552          14.55396          24.18530
## 15 2023-07-20        118083          14.64374          24.55055
## 16 2023-07-21        120217          15.06271          24.78747
## 17 2023-07-24        121342          14.80335          24.59004
## 18 2023-07-25        122008          14.72355          24.59991
## 19 2023-07-26        122560          14.84325          24.61966
## 20 2023-07-27        119990          14.51406          24.30376
## 21 2023-07-28        120187          14.71357          24.42222
## 22 2023-07-31        121943          14.81332          24.43209
## 23 2023-08-01        121248          14.76345          24.41989
## 24 2023-08-02        120859          14.80065          24.46929
## 25 2023-08-03        120586          14.65084          24.25196
## 26 2023-08-04        119508          13.95176          24.06426
## 27 2023-08-07        119380          13.86188          24.01487
## 28 2023-08-08        119090          13.81194          23.78766
## 29 2023-08-09        118409          13.71207          23.58021
## 30 2023-08-10        118350          13.86188          23.57033
## 31 2023-08-11        118065          13.79197          23.44191
## 32 2023-08-14        116810          13.78198          23.22458
## 33 2023-08-15        116171          13.70208          23.18507
## 34 2023-08-16        115592          13.50235          23.07640
## 35 2023-08-17        114982          13.25267          22.99738
## 36 2023-08-18        115409          13.36253          23.13568
## 37 2023-08-21        114429          13.29262          22.84920
## 38 2023-08-22        116156          13.38250          23.24434
## 39 2023-08-23        118135          13.53231          23.43203
## 40 2023-08-24        117026          13.26266          23.11592
## 41 2023-08-25        115837          13.19275          22.90847
## 42 2023-08-28        117121          13.45241          23.44191
## 43 2023-08-29        118404          13.56227          23.66912
## 44 2023-08-30        117535          13.38250          23.30361
## 45 2023-08-31        115742          13.22271          23.02701
## 46 2023-09-01        117893          13.19275          23.12355
## 47 2023-09-04        117777          13.14000          23.11366
## 48 2023-09-05        117331          12.98000          22.68856
## 49 2023-09-06        115985          12.80000          22.54027
## 50 2023-09-08        115313          12.80000          22.58970
## 51 2023-09-11        116883          12.98000          22.92583
## 52 2023-09-12        117968          13.11000          23.08400
## 53 2023-09-13        118176          13.15000          23.28172
## 54 2023-09-14        119392          13.20000          23.29161
## 55 2023-09-15        118758          13.13000          23.35093
## 56 2023-09-18        118288          13.15000          23.37070
## 57 2023-09-19        117846          13.04000          23.44000
## 58 2023-09-20        118695          13.06000          23.65000
## 59 2023-09-21        116145          12.50000          23.09000
## 60 2023-09-22        116009          12.51000          22.88000
## 61 2023-09-25        115925          12.45000          22.97000
## 62 2023-09-26        114193          12.27000          22.69000
## 63 2023-09-27        114327          12.27000          22.67000
##    petr3_sa_adjusted goau3_sa_adjusted cmig3_sa_adjusted
## 1           31.98603          11.33930          19.13457
## 2           32.53685          11.67195          18.73841
## 3           32.61416          11.73065          18.31253
## 4           32.60450          11.68173          18.02532
## 5           32.18897          11.58389          17.77772
## 6           32.01503          11.84805          17.79752
## 7           32.01503          11.87741          17.78762
## 8           31.76377          11.95567          17.90647
## 9           31.66714          12.03394          17.72820
## 10          32.13099          12.26875          18.09465
## 11          31.45454          12.10243          17.83714
## 12          31.46421          12.11221          17.99561
## 13          31.19363          12.17091          17.91637
## 14          31.36757          12.04373          17.39146
## 15          31.60916          12.21983          17.33204
## 16          32.18897          12.11221          17.34194
## 17          32.85574          12.38616          18.02532
## 18          33.44522          12.91448          18.13426
## 19          33.30026          12.88513          18.66908
## 20          31.42555          12.80686          18.18378
## 21          31.95704          12.84599          18.22340
## 22          33.63848          13.01231          18.26301
## 23          32.93306          13.04166          18.31253
## 24          32.70113          12.90469          18.72850
## 25          33.16497          12.93404          18.71860
## 26          31.77344          12.86556          18.77802
## 27          31.98603          12.79707          18.49081
## 28          31.96671          12.43508          18.76812
## 29          32.33392          12.11221          19.26332
## 30          32.32426          11.97524          19.53073
## 31          32.34358          11.89697          19.62977
## 32          32.49820          11.84805          19.70900
## 33          32.43055          11.86762          19.57034
## 34          33.38723          11.87741          19.70900
## 35          33.13599          11.73065          19.65948
## 36          33.32925          11.76000          19.08505
## 37          33.00070          11.49000          19.33265
## 38          33.50000          11.71000          19.70900
## 39          35.41000          11.73000          19.53073
## 40          35.32000          11.55000          18.84735
## 41          35.04000          11.49000          19.08505
## 42          35.40000          11.48000          19.11476
## 43          35.53000          11.73000          19.21380
## 44          35.50000          11.93000          19.66939
## 45          34.54000          11.74000          19.50102
## 46          35.69000          11.81000          19.57034
## 47          35.20000          12.00000          19.44159
## 48          36.82000          11.76000          19.17418
## 49          37.00000          11.65000          18.81764
## 50          36.71000          11.51000          18.85726
## 51          36.46000          11.66000          19.14447
## 52          36.86000          11.85000          19.37226
## 53          36.38000          11.76000          19.63967
## 54          37.45000          11.86000          19.80804
## 55          36.90000          11.76000          19.80804
## 56          37.36000          11.58000          19.80804
## 57          37.36000          11.50000          19.80804
## 58          37.41000          11.64000          19.71890
## 59          36.87000          11.39000          19.80804
## 60          37.14000          11.26000          19.50102
## 61          37.38000          11.23000          19.60006
## 62          36.35000          11.21000          19.68000
## 63          37.70000          11.21000          19.51000

ETAPA 2 - OTIMIZAÇÃO DE PORTFÓLIO

Nesta seção, o objeto “consolidado” será utilizado para otimização de portfólio. Em primeiro lugar, vamos transformar esta tabela em um objeto de série temporal (para tanto, será utilizada a função timeSeries do pacote com o mesmo nome). Em seguida, será utilizada a função returns do pacote timeSeries para cálculo dos retornos diários de cada uma das ações.

#PACOTES NECESSÁRIOS ----
library(timeSeries)
## Carregando pacotes exigidos: timeDate
## 
## Attaching package: 'timeSeries'
## The following object is masked from 'package:zoo':
## 
##     time<-
library(fBasics)
## 
## Attaching package: 'fBasics'
## The following object is masked from 'package:TTR':
## 
##     volatility
library(fPortfolio)
## Carregando pacotes exigidos: fAssets
#OBJETO DE SÉRIE TEMPORAL ----
retornos_ts <- timeSeries(consolidado[,-1], consolidado[,1]) 
retornos_ts <- returns(retornos_ts)


# CÁLCULO DO RISCO E RETORNO INDIVIDUAL (CADA AÇÃO) ----
retornos_acao <- basicStats(retornos_ts) %>% 
  rownames_to_column() %>% 
  rename("estatistica" = rowname) %>% 
  dplyr::filter(estatistica == 'Mean' | estatistica == 'Stdev')


#CÁLCULO DO RISCO E RETORNO DO PORTFÓLIO ----
fronteira_eficiente <- portfolioFrontier(retornos_ts)
frontierPlot(fronteira_eficiente)

VISUALIZAÇÃO INTERATIVA

library(ggplot2)
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:timeSeries':
## 
##     filter
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
tabela_retorno <- retornos_ts %>% 
  as.data.frame() %>% 
  rownames_to_column() %>% 
  rename("data" = rowname) %>% 
  mutate(data = as.Date(data))

grafico <- tabela_retorno %>% 
  ggplot() +
  geom_line(mapping = aes(x = data, y = bvsp_adjusted))
  geom_point(mapping = aes(x = data, y = bvsp_adjusted))
## mapping: x = ~data, y = ~bvsp_adjusted 
## geom_point: na.rm = FALSE
## stat_identity: na.rm = FALSE
## position_identity
ggplotly(grafico)