Search code examples
rxtsquantmod

Save quantmod::getSymbols output to csv file and then read csv as a xts object


What the easy way to save download stock symbol data (by quantmod) in csv file and read with original xts format?

getSymbols("000001.SZ", from = "1990-10-01", auto.assign = TRUE)
write.csv(`000001.SZ`, "000001_yahoo.csv")
my_zoo <- read.csv("000001_yahoo.csv")

But the data will not be in a xts format.

And I get an error if I use read.zoo() to change the read.csv result.

my_zoo <- read.csv("000001_yahoo.csv")
PAYH <- read.zoo(my_zoo, format = "%Y-%m-%d", sep = ",",
                 header = TRUE, index.column = "Date")

## Error in read.zoo(my_zoo, format = "%Y-%m-%d", sep = ",", header = TRUE,  : 
##   index has 8106 bad entries at data rows: 1 2 3 4 5 6 7 8 9 10 11 12 13 14
##  15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
## 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
##  65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
## 90 91 92 93 94 95 96 97 98 99 100 ..

What's the function to easy save and load xts data?


Solution

  • Assuming that it is important that the file be in csv format use write.zoo and read.csv.zoo like this. Note that getSymbols adds some xts attributes that are not needed so zap them to ensure that the original object and the read-in object are identical.

    library(quantmod) # also loads xts and zoo
    getSymbols("000001.SZ", from = "1990-10-01")
    xtsAttributes(`000001.SZ`) <- NULL
    
    write.zoo(`000001.SZ`, "000001_yahoo.csv", sep = ",")
    
    z <- read.csv.zoo("000001_yahoo.csv", check.names = FALSE)
    x <- as.xts(z)
    
    identical(`000001.SZ`, x)
    ## [1] TRUE