Search code examples
rquantmod

Time series from csv in wrong order


I got a problem with the following R script:

    library(quantmod)
    mydata = read.csv("C:/AAD.DE.csv")   
    ### getSymbols("AAPL",src="yahoo")  
    sma20 <- SMA(mydata[,"Close"],20)


write.csv(   
  data.frame( date=index(mydata[,"Date"])
, coredata(mydata)
, coredata(sma20)
 ),   
  row.names=FALSE,   
  file="C:/neu_AAD.DE.csv" 
)

The SMA is calculated but in the wrong order. So I have to order the file ascending before calculating the SMA? I think the date in the file is used as a string and not as a date?

I don't use getSymbols("AAPL",src="yahoo") because it only returns data from 2007 until now and no older data.


Solution

  • I haven't used quantmod library, but yahooSeries() function in fImport library can give you the full length of data.

    For data order, you should convert string date to Date format and the order it, here is the code:

    library(fImport)
    mydata <- yahooSeries(symbols = "AAPL", nDaysBack = 100000)
    mydata <- as.data.frame(mydata, stringsAsFactors = FALSE)
    mydata <- cbind(rownames(mydata), mydata)
    names(mydata) <- c("Date", "Open", "High", "Low", "Close", "Volume", "Adj.Close")
    rownames(mydata) <- NULL
    mydata$Date <- as.Date(mydata$Date)
    mydata <- mydata[order(mydata$Date), ]