0

I obtained the daily closing price in the form of a zoo object from get.hist.quote where the dates are retained. The log returns is calculated and trimmed to remove NA values.

stockEBAY$Data retrains the dates as the x value for later plotting using autoplot.zoo stockEBAY$LogReturns retrains the dates as the x value for later plotting using autoplot.zoo

library("tseries")
library("zoo")
library("ggplot2")
AnalyzeStock <- function(ticker){
  DailyClosingPrice <- get.hist.quote(ticker,quote="Close",quiet=TRUE)  
  logreturns <- log(lag(DailyClosingPrice))-log(DailyClosingPrice)
  logreturns <- na.trim(logreturns, sides = "both")
  list(Data=DailyClosingPrice, LogReturns=logreturns)
}
stockEBAY <- AnalyzeStock("EBAY")
autoplot.zoo(stockEBAY$Data) + 
  xlab("Year") + ylab("Closing Price (U.S. Dollars)")

Plot of EBAY stock with year retained as x axis

However to create the volatility, I had to create a new data frame based on the function but I don't know how to write it so that the original dates from stockEBAY$LogReturns are retained in the new data frame.

Vol <- function(d, logreturns)
{
  var = 0
  lam = 0
  varlist <- c()
  for (r in logreturns) {
    lam = lam*(1 - 1/d) + 1
    var = (1 - 1/lam)*var + (1/lam)*r^2
    varlist <- c(varlist, var)
  }
  sqrt(varlist)
}
#retrieve volatility for decays 10, 30, and 100
vol10 <- Vol(10,stockEBAY$LogReturns)
vol30 <- Vol(30,stockEBAY$LogReturns)
vol100 <- Vol(100,stockEBAY$LogReturns)
plot(vol10,type="l",xlab="Year",ylab="Volatility")
lines(vol30,type="l", col="red")
lines(vol100,type="l",col="blue")

overlaying volatility plots, but the dates were not retained as the x axis and instead is now index, which messes up the graph

vol10, vol30, vol100 all have the x axis as index but is missing the original dates.

I would like it so that the new data frames of vol10, vol30, and vol100 all retain the original dates from stockEBAY$LogReturns.

Or, could there be a possibility that the new volatility columns could be appended to the original stockEBAY$LogReturns data frame?

I need a way to solve for the volatility column more succinctly from a function and retain the dates from the original zoo object into the new data frames for later plot overlay.

As long as I could plot and overlay the 3 volatility columns on top of each other so that the x axis could be retained as dates, not index, that is the goal.

Thanks

Edit: the zoo object is frustrating,....this doesn't work well

> stockEBAY$LogReturns$vol10 <- Vol(10,stockEBAY$LogReturns)
Error in NextMethod("[<-") : 
  number of items to replace is not a multiple of replacement length
In addition: Warning messages:
1: In doTryCatch(return(expr), name, parentenv, handler) :
  invalid graphics state
2: In doTryCatch(return(expr), name, parentenv, handler) :
  invalid graphics state
> stockEBAY$LogReturns$vol30 <- Vol(30,stockEBAY$LogReturns)
Error: all(sapply(args, function(x) is.zoo(x) || !is.plain(x) || (is.plain(x) &&  .... is not TRUE
> stockEBAY$LogReturns$vol100 <- Vol(100,stockEBAY$LogReturns)
Error: all(sapply(args, function(x) is.zoo(x) || !is.plain(x) || (is.plain(x) &&  .... is not TRUE
> autoplot.zoo(stockEBAY$LogReturns$vol10)
437gf083
  • 17
  • 1
  • 10
  • 1
    You can add the new data to the original dataframe with e.g. `stockEBAY$vol10 <- Vol(10,stockEBAY$LogReturns)` and then you have the dates already there. – Andrew Gustar Apr 19 '17 at 16:43
  • I'm getting errors when I do that `> stockEBAY$LogReturns$vol10 <- Vol(10,stockEBAY$LogReturns) Error in NextMethod("[<-") : number of items to replace is not a multiple of replacement length In addition: Warning messages: 1: In doTryCatch(return(expr), name, parentenv, handler) : invalid graphics state 2: In doTryCatch(return(expr), name, parentenv, handler) : invalid graphics state > stockEBAY$LogReturns$vol30 <- Vol(30,stockEBAY$LogReturns) Error: all(sapply(args, function(x) is.zoo(x) || !is.plain(x) || (is.plain(x) && .... is not TRUE` – 437gf083 Apr 19 '17 at 16:48
  • No, just `stockEBAY$vol10 <-`, not `stockEBAY$LogReturns$vol10 <-`. All this does is add a new variable `vol10` to an existing dataframe. – Andrew Gustar Apr 19 '17 at 16:51
  • doing this does not retain dates when I try to graph it because the original zoo object does not have dates with a column name to reference from autoplot.zoo...please show me the syntax of how to graph it w/ the dates intact – 437gf083 Apr 19 '17 at 16:55
  • You're right - the zoo object has the dates buried in an attribute. I have posted a solution that should give you a df you can work with. – Andrew Gustar Apr 19 '17 at 17:10

2 Answers2

1

Thanks, Andrew Gustar for the starter code, I got this to output the graph I wanted, but if anyone else has a better way to code it, I'm all ears

stockEBAY$LogReturns$vol10 <- Vol(10,stockEBAY$LogReturns$Close)
stockEBAY$LogReturns$vol30 <- Vol(30,stockEBAY$LogReturns$Close)
stockEBAY$LogReturns$vol100 <- Vol(100,stockEBAY$LogReturns$Close)
plot(stockEBAY$LogReturns$vol10,type="l",xlab="Year",ylab="Volatility", ylim = c(0,0.35))
par(new=TRUE)
plot(stockEBAY$LogReturns$vol30,type="l",xlab="Year",ylab="Volatility", ylim = c(0,0.35),  col="red")
par(new=TRUE)
plot(stockEBAY$LogReturns$vol100,type="l",xlab="Year",ylab="Volatility", ylim = c(0,0.35),  col="blue")

The graph

437gf083
  • 17
  • 1
  • 10
0

The dates are held in an attribute of the zoo object. You can get to them with attr(stockEBAY$LogReturns,"index"). So you could set up a new df to use for plotting as follows...

df <- data.frame(Date=as.Date(attr(stockEBAY$LogReturns,"index")),
                 vol10=vol10,
                 vol30=vol30,
                 vol100=vol100)

and then plot using df$Date as the x axis.

plot(x=df$Date,y=df$vol10,type="l",xlab="Year",ylab="Volatility")
lines(df$Date,df$vol30,type="l", col="red")
lines(df$Date,df$vol100,type="l", col="blue")
Andrew Gustar
  • 17,295
  • 1
  • 22
  • 32
  • I tried this, got an error, thanks`> df <- data.frame(Date=as.Date(attr(stockEBAY$Data,"index")), + vol10=vol10, + vol30=vol30, + vol100=vol100) Error in data.frame(Date = as.Date(attr(stockEBAY$Data, "index")), vol10 = vol10, : arguments imply differing number of rows: 4671, 18680` – 437gf083 Apr 19 '17 at 17:15
  • Sorry - you got an earlier draft of my answer - see new version above. The Data and LogReturns parts of the `zoo` object differ by one day. – Andrew Gustar Apr 19 '17 at 17:19
  • I'm trying to learn it the plot w/ lines way but there's random horizontal/multiple connected lines underneath the graph that shouldn't be there http://imgur.com/KqN5DjC – 437gf083 Apr 19 '17 at 17:24
  • Strange. I don't get that when I run it - mine looks the same as the graph you posted in your answer. I am still defining `vol10` etc as in your original code, rather than the slightly different form you use in your answer. – Andrew Gustar Apr 19 '17 at 17:31
  • not sure, the code connects random dots together that shouldn't be connected, as depicted in the previous link. thanks for all your help. – 437gf083 Apr 19 '17 at 17:42
  • Your plot with the spurious lines looks as if there are two red and two blue series being plotted. It might be worth going back to the start and trying a clean run through of the code in your question (but not the last three lines doing the `plot`), followed by my code in the answer above. – Andrew Gustar Apr 19 '17 at 17:52
  • I think I know why...somehow, my code still thinks that I'm doing a plot.zoo() when I call the plot() function, because I used autoplot.zoo() earlier. unless I use a different r markdown code chunk, it plots the weird interconnecting plot. I have no idea how to turn off zoo once I call it because library(zoo) takes over the plot() function and reads it as plot.zoo(). thanks for all your help, I learned a lot, but the code that I have above is sufficient, I think – 437gf083 Apr 19 '17 at 18:34