1

I'm using this following code to find the volatility of Tesla:

library(quantmod)
library(ggplot2)

Tesla <-  getSymbols("TSLA", src = "yahoo", from = "2014-10-01", to = "2019-11-25", auto.assign = FALSE)

vol.tesla <- volatility(Tesla[ ,6])


graf_vol_tesla <- ggplot(vol.tesla, aes(x = index(vol.tesla), y = vol.tesla))+ geom_line(color = "violetred4") +
  ggtitle("volatility Tesla") + xlab("Date") + ylab("Volatility") +
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_x_date(date_labels = "%b %y", date_breaks = "9 months")

graf_vol_tesla

However, it comes this as the output instead of the image. Anybody knows how to fix it? Thanks in advance!

'Don't know how to automatically pick scale for object of type xts/zoo. Defaulting to continuous. Error: Invalid input: date_trans works with objects of class Date only'

MDEWITT
  • 2,338
  • 2
  • 12
  • 23

1 Answers1

1

You just need to convert your index(vol.tesla) to a valid date object so that ggplot can plot it. Use as.Date to do this as shown below:

library(ggplot2)
library(quantmod)

Tesla <-  getSymbols("TSLA", src = "yahoo", from = "2014-10-01", to = "2019-11-25", auto.assign = FALSE)

vol.tesla <- volatility(Tesla[ ,6])

graf_vol_tesla <- ggplot(vol.tesla, aes(x = as.Date(index(vol.tesla)), 
                                        y = vol.tesla))+ geom_line(color = "violetred4") +
  ggtitle("volatility Tesla") + xlab("Date") + ylab("Volatility") +
  theme(plot.title = element_text(hjust = 0.5))+
  scale_x_date(date_labels = "%b %y", date_breaks = "9 months")


graf_vol_tesla

enter image description here

MDEWITT
  • 2,338
  • 2
  • 12
  • 23
  • @OmarCharmingKhodr excellent to hear. if it works, please accept the answer so others know it solved your problem (checkmark beneath the up/down vote) – MDEWITT Nov 26 '19 at 16:15