R - Stock market data from csv to xts

懵懂的女人 提交于 2019-11-30 16:14:17

问题


I have this data in a CSV:

Date  ALICORC1 ALT   ATACOBC1 AUSTRAC1 CONTINC1 BVN   DNT
40886 5.8      0.1   0.9      0.28     5.45     38.2  1.11
40889 5.8      0.1   0.88     0.28     5.37     37.7  1.04
40890 5.8      0.09  0.87     0.27     5.33     37.4  0.99
40891 5.7      0.1   0.85     0.27     5.3      37.5  0.91

These are stock closing prices from the Peruvian Stock Market, and I want to convert them to xts so I can find the optimal portfolio and other stuff, but I can't find the way to convert this CSV to xts. I've checked out the answer to many of the questions here but none of them worked.

Some of the errors I've got are:

  • Index has XXXX bad entries at data rows
  • Ambiguous data.

Can anybody help me?


回答1:


csv stands for comma-separated-values so the layout shown in the question is not csv. We will assume that the data really is in csv form and not in the form shown the question. If it truly is in the form shown in the question rather than csv then omit the sep="," argument in read.zoo below. Also if there are other deviations you may need to modify the arguments further. See ?read.zoo and the Reading Data in Zoo vignette in the zoo package.

Here we use read.zoo in the zoo package to read in the data as a zoo object, z, and then we convert it to xts, x.

See R News 4/1 which specifically treats date handling of Excel dates noting that we may need to modify the code below slightly if the Mac version of Excel is being used (as described there in the reference).

library(xts) # this also loads zoo which has read.zoo

toDate <- function(x) as.Date(x, origin = "1899-12-30")
z <- read.zoo("myfile.csv", header = TRUE, sep = ",", FUN = toDate)
x <- as.xts(z)


来源:https://stackoverflow.com/questions/9335917/r-stock-market-data-from-csv-to-xts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!