數據幀我有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]))
}
}
這工作,但......用不了這麼多時間。 我如何介紹應用功能?
數據幀我有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]))
}
}
這工作,但......用不了這麼多時間。 我如何介紹應用功能?
我不明白你的公式非常好。但如果你試圖計算滯後回報的矩陣,這可能是一個更好的辦法,使用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
它的工作原理!非常感謝! – Alex
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()。雖然我覺得有時難以合作。
通常一個代表,如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
嗨Alex,歡迎來到Stackoverflow。請通過[此鏈接](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)給出一個可重複的示例,以便其他人可以輕鬆地提供幫助您。 –