2017-10-05 110 views
0

数据帧我有IPC的历史价格数据框(^ MXX)和IM试图使矩阵滞后为列:如何使用申请()计算时间滞后于R中

for(i in 1:length(IPC$Close)-1){ 
    for(l in 1:length(IPC$Close)-1){ 
    Lags[l,i] <- log(IPC$Close[l+i]-log(IPC$Close[l])) 
    } 
} 

这工作,但......用不了这么多时间。 我如何介绍应用功能?

+1

嗨Alex,欢迎来到Stackoverflow。请通过[此链接](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)给出一个可重复的示例,以便其他人可以轻松地提供帮助您。 –

回答

0

我不明白你的公式非常好。但如果你试图计算滞后回报的矩阵,这可能是一个更好的办法,使用embed:要

# the data 
N=10 
set.seed(123) 
IPC=data.frame(Close=runif(N,10,20)) 
IPC$ret=c(NA,diff(log(IPC$Close))) 
#IPC 

# the matrix of lagged returns  
Nlags=2 
embed(diff(log(IPC$Close)), Nlags+1) 

      [,1]  [,2]  [,3] 
[1,] 0.29001164 -0.23840447 0.32850576 
[2,] 0.03005332 0.29001164 -0.23840447 
[3,] -0.61837953 0.03005332 0.29001164 
[4,] 0.37947945 -0.61837953 0.03005332 
[5,] 0.21382720 0.37947945 -0.61837953 
[6,] -0.19867561 0.21382720 0.37947945 
[7,] -0.06306525 -0.19867561 0.21382720 
+0

它的工作原理!非常感谢! – Alex

0

Asuuming计算/ lapply R中所有与sapply可能滞后

IPC=data.frame(Close=seq(100,120)) 
# both nested double sapply and outer worked identically in this case 
t1 <-sapply(1:length(IPC$Close), function(x) sapply(1:length(IPC$Close),function(y) log(IPC$Close[y])-log(IPC$Close[x]))) 
t2 <-outer(log(IPC$Close), log(IPC$Close), FUN = "-") 

# test case on simplier case 
a=seq(1,5) 
# both of the function below wll compute all the lags 
# sapply, since lapply will output listed which require more processing 
sapply(a, function(x) sapply(a, function(y) x-y)) 
outer(a, a, "-") 
# [,1] [,2] [,3] [,4] [,5] 
# [1,] 0 1 2 3 4 
# [2,] -1 0 1 2 3 
# [3,] -2 -1 0 1 2 
# [4,] -3 -2 -1 0 1 
# [5,] -4 -3 -2 -1 0 

但是如果你真的在处理股票价格,你应该仔细研究时间序列(动物园,xts)及其各自的功能,如lag()。虽然我觉得有时难以合作。

0

通常一个代表,如XTS采用时间序列类金融时间序列。在这种情况下,我们可以使用lag这样的xts方法:

library(quantmod) # also loads xts, zoo and TTR 

getSymbols("GOOG") # get GOOG OHLCV data 
## [1] "GOOG" 

class(GOOG) 
## [1] "xts" "zoo" 

# take last few rows of GOOG and then display the 
# original series closes (lag 0) with 3 lags 
lag(tail(Cl(GOOG)), 0:3) 
##   GOOG.Close GOOG.Close.1 GOOG.Close.2 GOOG.Close.3 
## 2017-09-26  924.86   NA   NA   NA 
## 2017-09-27  944.49  924.86   NA   NA 
## 2017-09-28  949.50  944.49  924.86   NA 
## 2017-09-29  959.11  949.50  944.49  924.86 
## 2017-10-02  953.27  959.11  949.50  944.49 
## 2017-10-03  957.79  953.27  959.11  949.50