本文介绍了在两列上使用 Rollapply的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做类似的事情,我在这里不幸的是,我无法解决.

I'm trying to do something similar I was asking for here and unfortunately I cannot work it out.

这是我的数据框(data),价格的时间序列:

This is my data frame (data), a time series of prices:

Date          Price   Vol
1998-01-01     200      0.3
1998-01-02     400      0.4
1998-01-03     600     -0.2
1998-01-04     100      0.1
...
1998-01-20     100      0.1
1998-01-21     200     -0.4
1998-01-21     500      0.06
....
1998-02-01     100      0.2
1998-02-02     200      0.4
1998-02-03     500      0.3
1998-02-04     100      0.1
etc.

我想告诉 R

  • 取Vol"的第 1 个值除以Price"的第 20 个值,然后
  • 然后将Vol"的第 2 个值除以Price"的第 21 个值.
  • 将Vol"的第 3 个值除以Price"的第 22 个值,然后

在我的另一篇文章中,我能够使用这个函数来计算 20 天持有期的回报:

In my other post, I was able to use this function to calculate a return over a holding period of 20 days:

> data.xts <- xts(data[, -1], data[, 1])
> hold <- 20
> f <- function(x) log(tail(x, 1)) - log(head(x, 1))
> data.xts$returns.xts <- rollapply(data.xts$Price, FUN=f, 
  width=hold+1, align="left", na.pad=T)

有没有办法对上述问题做一些非常相似的事情?所以像

Is there a way to do something very similar for the problem stated above? So something like

f1 <- function(x,y) head(x, 1) / tail(y,1)

其中 x 是Vol",y 是Price",然后应用rollapply"?

where x is "Vol" and y is "Price" and then apply "rollapply"?

非常感谢

更新:@G 博士:感谢您的建议.稍加改动,就达到了我想要的效果!

UPDATE: @ Dr G:Thanks for your suggestions. With a slight change, it did what I wanted!

data.xts <- xts(data[, -1], data[, 1])
hold <- 20
data.xts$quo <- lag(data.xts[,2], hold) / data.xts[,1]

现在我的问题是,生成的数据框如下所示:

Now my problem is, that the resulting data frame looks like this:

    Date          Price   Vol     quo
1 1998-01-01     200      0.3     NA
2 1998-01-02     400      0.4     NA
3 1998-01-03     600     -0.2     NA
4 1998-01-04     100      0.1     NA
...
21 1998-01-20    180      0.2     0.003 

我知道必须有 NA 作为结果,但仅针对最后 20 个观察结果,而不是前 20 个观察结果.上述公式计算正确的值,但是将它们从第 21 行而不是第一行开始.你知道我怎么能改变吗?

I know that there must be NA's as an outcome, but only for the last 20 observations, not the first 20 ones. The formula stated above calculates the correct values, however puts them starting at the 21st row instead of the first row. Do you know how I could change that?

推荐答案

实际上比这更容易.只需这样做:

It's actually easier than that. Just do this:

data.xts <- xts(data[, -1], data[, 1])
hold <- 20
returns.xts = data.xts[,2] / lag(data.xts[,1], hold)

实际上,为此使用 zoo 而不是 xts 也可以:

Actually for this using zoo instead of xts would work as well:

data.zoo<- zoo(data[, -1], data[, 1])
hold <- 20
returns.zoo = data.zoo[,2] / lag(data.zoo[,1], -hold)

唯一改变的是滞后的符号(动物园惯例与 xts 不同)

Only thing that changes is the sign of the lags (zoo convention is different than xts)

这篇关于在两列上使用 Rollapply的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 09:57