R 按常用日期筛选xts对象
我被以下代码卡住了 为了参考从以下网站()获取的代码,我还通过R Studio编译代码R 按常用日期筛选xts对象,r,time-series,xts,quantmod,R,Time Series,Xts,Quantmod,我被以下代码卡住了 为了参考从以下网站()获取的代码,我还通过R Studio编译代码 library("quantmod") startDate = as.Date("2013-01-01") symbolLst<-c("WPL.AX","BHP.AX") symbolData <- new.env() getSymbols(symbolLst, env = symbolData, src = "yahoo", from = startDate) stockPair <
library("quantmod")
startDate = as.Date("2013-01-01")
symbolLst<-c("WPL.AX","BHP.AX")
symbolData <- new.env()
getSymbols(symbolLst, env = symbolData, src = "yahoo", from = startDate)
stockPair <- list(
a =coredata(Cl(eval(parse(text=paste("symbolData$\"",symbolLst[1],"\"",sep="")))))
,b = coredata(Cl(eval(parse(text=paste("symbolData$\"",symbolLst[2],"\"",sep="")))))
,hedgeRatio = 0.70 ,name=title)
spread <- stockPair$a - stockPair$hedgeRatio*stockPair$b
这些特定系列不匹配的原因是,与“必和必拓”相比,“WPL.AX”有一个额外的值(日期:2014年5月19日-矩阵长度不同)。加载数据时如何解决此问题
我还使用source=“google”测试了其他股票对,如“ANZ”、“WBC”,它生成两个相同长度的数组
> length(stockPair$a)
[1] 360
> length(stockPair$b)
[1] 359
在
stockPair
计算之前添加这样的代码,以将每个xts
集修剪到日期的交点:
common_dates <- as.Date(Reduce(intersect, eapply(symbolData, index)))
symbolData <- eapply(symbolData, `[`, i=common_dates)
common\u dates如果您不通过coredata
将xts对象转换为矩阵,那么您的代码工作正常。然后Ops.xts
将确保只减去具有相同索引的行。《财富》(106)
也适用
fortunes::fortune(106)
# If the answer is parse() you should usually rethink the question.
# -- Thomas Lumley
# R-help (February 2005)
stockPair <- list(
a = Cl(symbolData[[symbolLst[1]]])
,b = Cl(symbolData[[symbolLst[2]]])
,hedgeRatio = 0.70
,name = "title")
spread <- stockPair$a - stockPair$hedgeRatio*stockPair$b
财富:财富(106)
#如果答案是parse(),您通常应该重新思考这个问题。
#--托马斯·卢姆利
#R-help(2005年2月)
stockPair您需要找到尺寸不同的原因,而不是试图强迫它们相同。@MatthewLundberg抱歉,让我重新表述一下,这些特定系列不匹配的原因是“WPL.AX”比“BHP”有一个额外的值(日期:2014年5月19日)。加载数据时如何解决此问题?请在问题中说明,而不是“如何强制R使两个数组一致”。@MatthewLundberg我已适当更新了我的问题请注意
[
忽略参数名称,只使用位置匹配,因此i=common\u dates
中的i=
是不相关的。
fortunes::fortune(106)
# If the answer is parse() you should usually rethink the question.
# -- Thomas Lumley
# R-help (February 2005)
stockPair <- list(
a = Cl(symbolData[[symbolLst[1]]])
,b = Cl(symbolData[[symbolLst[2]]])
,hedgeRatio = 0.70
,name = "title")
spread <- stockPair$a - stockPair$hedgeRatio*stockPair$b
# merge stocks into a single xts object
stockPair <- do.call(merge, eapply(symbolData, Cl))
# ensure stockPair columns are in the same order as symbolLst, since
# eapply may loop over the environment in an order you don't expect
stockPair <- stockPair[,pmatch(symbolLst, colnames(stockPair))]
colnames(stockPair) <- c("a","b")
# add hedgeRatio and name as xts attributes
xtsAttributes(stockPair) <- list(hedgeRatio=0.7, name="title")
spread <- stockPair$a - attr(stockPair,'hedgeRatio')*stockPair$b