0

我有两个时间序列,一个是每日时间序列,另一个是离散时间序列。在我的情况下,我需要合并股价和评级,但是合并的时间序列根据股票价格保持每日日期,并且评级通过股票代码和日期与每日数据相匹配。一个简单的合并命令只会查找确切的日期和代码并将 NA 应用于不合适的情况。但我想寻找确切的匹配项,并用最后一次评分填写日期。

 Daily time series:

         ticker       date        stock.price
          AA US Equity 2004-09-06  1
          AA US Equity 2004-09-07  2
          AA US Equity 2004-09-08  3
          AA US Equity 2004-09-09  4
          AA US Equity 2004-09-10  5
          AA US Equity 2004-09-11  6

  Discrete time series
          ticker        date        Rating Last_Rating
          AA US Equity   2004-09-08   A         A+
          AA US Equity   2004-09-11   AA        A
          AAL LN Equity  2005-09-08   BB        BB
          AAL LN Equity  2007-09-09   AA        AA-
          ABE SM Equity  2006-09-10   AA        AA-
          ABE SM Equity  2009-09-11   AA        AA-


  Required Output:

           ticker       date        stock.price  Rating
          AA US Equity 2004-09-06    1             A+
          AA US Equity 2004-09-07    2             A+
          AA US Equity 2004-09-08    3             A
          AA US Equity 2004-09-09    4             A
          AA US Equity 2004-09-10    5             A
          AA US Equity 2004-09-11    6             AA

我将非常感谢您的帮助。

4

1 回答 1

1

也许这就是您想要的解决方案。na.locf时间序列包中的函数zoo可用于向前(或向后)携带值。

library(zoo)
library(plyr)
options(stringsAsFactors=FALSE)

daily_ts=data.frame(
    ticker=c('A','A','A','A','B','B','B','B'),
    date=c(1,2,3,4,1,2,3,4),
    stock.price=c(1.1,1.2,1.3,1.4,4.1,4.2,4.3,4.4)
    )
discrete_ts=data.frame(
    ticker=c('A','A','B','B'),
    date=c(2,4,2,4),
    Rating=c('A','AA','BB','BB-'),
    Last_Rating=c('A+','A','BB+','BB')
    )

res=ddply(
    merge(daily_ts,discrete_ts,by=c("ticker","date"),all=TRUE),
    "ticker",
    function(x) 
        data.frame(
            x[,c("ticker","date","stock.price")],
            Rating=na.locf(x$Rating,na.rm=FALSE),
            Last_Rating=na.locf(x$Last_Rating,na.rm=FALSE,fromLast=TRUE)
            )
    )

res=within(
    res,
    Rating<-ifelse(
        is.na(Rating),
        Last_Rating,Rating
        )
    )[,setdiff(colnames(res),"Last_Rating")]

res

#  ticker date stock.price Rating
#1      A    1         1.1     A+
#2      A    2         1.2      A
#3      A    3         1.3      A
#4      A    4         1.4     AA
#5      B    1         4.1    BB+
#6      B    2         4.2     BB
#7      B    3         4.3     BB
#8      B    4         4.4    BB-
于 2013-10-29T00:43:04.370 回答