Problems to plot graph with chartSeries function of the quantmod package from a data.frame to R

Asked

Viewed 117 times

4

I’m having trouble plotting a Candlesticks chart from a file data.frame.

Code example

# Pacotes necessários ---------------------------------------------- 
library(BatchGetSymbols)
library(quantmod)
# Inputs necessários ------------------------------------------------------
#data inicial
first.date <- as.Date("2018-01-01")
#data final
last.date <- Sys.Date()
#frequencia das observações
freq.data <- 'daily'
# Ativos a serem baixados
tickers <- c("^BVSP")
# Importando ativos -------------------------------------------------------
ibov <- BatchGetSymbols(tickers = tickers, 
                      first.date = first.date,
                      last.date = last.date, 
                      freq.data = freq.data,
                      cache.folder = file.path(tempdir(), 
                                               'BGS_Cache') ) 
ibov<-as.data.frame(ibov)

With this code are imported the data for an example. What I would like to learn would be how to plot this data using the function.

chartSeries

From the date.frame ibov, I tried to do it this way:

ibov <- xts(ibov, order.by = ibov$df.tickers.ref.date)
chartSeries(ibov)

But the error is appearing:

Error in (function (cl, name, valueClass)  : 
assignment of an object of class “character” is not valid for @‘yrange’ in 
an object of class “chob”; is(value, "numeric") is not TRUE

1 answer

4


It worked that way for me:

library(tidyverse)
ibov <- xts(
  ibov$df.tickers %>% select(-ref.date, -ticker), 
  order.by = ibov$df.tickers$ref.date
  )
chartSeries(ibov)

I also deleted that line from your code: ibov<-as.data.frame(ibov).

The idea is that when converting to an object of type xts there can be no variable of type character in the date frame..

Another solution given that you already have the data.frame transformed would be to do so:

ibov <- xts(ibov %>% select_if(is.numeric), order.by = ibov$df.tickers.ref.date)
chartSeries(ibov)
  • this is not clear in your question, but anyway.. what you need is to take out all the columns that are not numeric from the data.frame. I will update with a possible solution

  • 2

    Thank you very much Daniel, this other solution has solved the problem perfectly, thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.