R - 股票市场数据从csv到xts [英] R - Stock market data from csv to xts
问题描述
我有一个CSV数据:
日期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
这些是秘鲁股市的股票收盘价,我想将它们转换为xts,这样我就可以找到最佳投资组合和其他东西,但我找不到方式将这个CSV转换为XTS。我已经查看了这里的许多问题的答案,但没有一个工作。
我得到的一些错误是:
- 索引在数据行中有XXXX个错误条目
- 模糊数据。
csv代表逗号
em> -separated-values因此问题中显示的布局不是csv。我们将假设数据真的是csv形式,而不是显示的问题的形式。如果它确实是问题中显示的形式而不是csv,则省略 read.zoo $ c中的 sep =,
$ c>下面。此外,如果有其他偏差,您可能需要进一步修改参数。请参阅?read.zoo
和
这里我们使用 read.zoo
在动物园包中读取数据作为动物园对象 z
,然后将其转换为xts, x
。
请参阅 R新闻4/1 ,专门处理Excel日期的日期处理,注意到如果正在使用Mac版本的Excel,我们可能需要稍微修改代码(如参考文献中所述)。
library(xts)#这个也加载动物园有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)
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?
解决方案 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)
这篇关于R - 股票市场数据从csv到xts的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!