我有一个我想要处理的OHLC股票报价数组。
Open High Low Close Volume
2003-01-05 6111.01 6145.00 6102.70 6145.00 956
2003-01-08 6145.00 6190.00 5960.00 6135.05 8771
2003-01-09 6120.01 6250.00 6120.00 6225.00 10579
2003-01-10 6240.00 6285.00 6225.10 6261.00 8882
2003-01-13 6231.00 6325.00 6231.00 6270.00 8015
2003-01-14 6279.00 6295.00 6180.01 6190.00 8461
公司在@给定日期进行了拆分,因此我需要在该日期之前将所有开,高,低,关闭列除以1000。 当我正在学习R基础知识时,我想为这项任务找出很好的R解决方案。 我设法编写的最好的代码是(无法找到如何申请给定的cols,股票$ Open不起作用):
apply(stock, 2, function(stock) stock/((index(stock)<"2007-07-20")*1000) )
然而,结果很奇怪,其中很多都是inf:
2006-10-26 Inf Inf Inf Inf Inf
2006-10-27 Inf Inf Inf Inf Inf
2006-10-30 Inf Inf Inf Inf Inf
2006-10-31 Inf Inf Inf Inf Inf
2006-11-01 Inf Inf Inf Inf Inf
2006-11-02 Inf Inf Inf Inf Inf
2006-11-03 Inf Inf Inf Inf Inf
2006-11-07 Inf Inf Inf Inf Inf
非常感谢提前!
答案 0 :(得分:2)
我不熟悉OHLC array
,但假设索引方法有效:
relevantRows<-index(stock) < "2007-07-20"
一旦你有一个包含所有相关行的向量(实际上是一个逻辑向量,对于应该更改的行保持为TRUE),你可以像这样简单地使用它:
stock$Open[relevantRows]<-stock$Open[relevantRows]/1000
有可能(取决于OHLC array
s的内部),即使这样也有效:
stock[relevantRows, c("Open", "High", "Low", "Close")]<-stock[relevantRows, c("Open", "High", "Low", "Close")]/1000
答案 1 :(得分:2)
如果日期不是在2007年7月20日之前,则(index(stock)<"2007-07-20")
为FALSE
,因此(index(stock)<"2007-07-20")*1000
为零。您的Inf
值是除以零的结果。
你可以试试这个:
stock[index(stock) < "2007-07-20", -5] <- stock[index(stock) < "2007-07-20", -5] / 1000
答案 2 :(得分:1)
您可以使用TTR包中的adjRatios
功能执行此操作。看起来你已经有了一个xts对象,所以我使用的是:
library(quantmod)
x <- structure(c(6111.01, 6145, 6120.01, 6240, 6231, 6279, 6145, 6190,
6250, 6285, 6325, 6295, 6102.7, 5960, 6120, 6225.1, 6231, 6180.01,
6145, 6135.05, 6225, 6261, 6270, 6190, 956, 8771, 10579, 8882,
8015, 8461), .Dim = c(6L, 5L), .Dimnames = list(NULL, c("Open",
"High", "Low", "Close", "Volume")), index = structure(c(1041746400,
1042005600, 1042092000, 1042178400, 1042437600, 1042524000), tzone = "",
tclass = "Date"), class = c("xts", "zoo"), .indexCLASS = "Date", .indexTZ = "")
s <- xts(1/1000,as.Date("2003-01-10"))
r <- adjRatios(s,,Cl(x))
OHLC(x) * drop(r[,"Split"]) * drop(r[,"Div"])
如果您正在使用Yahoo Finance中的数据,那么您可以使用quantmod中的adjustOHLC
函数自动从Yahoo中提取拆分和分红数据并调整系列。有关更多选项,请参阅?adjustOHLC
。