zhe_charmander
zhe_charmander

Reputation: 11

Trying to find volatility in R but my code won't work

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'

Upvotes: 1

Views: 80

Answers (1)

MDEWITT
MDEWITT

Reputation: 2368

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

Upvotes: 1

Related Questions