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")
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)