我试图滞后我从雅虎市场下载的一些价格,但我不希望滞后得到修复。我想把它放在哪里取决于另一个DF或值滞后期间的变化。
这会提取并格式化数据:
library("quantmod")
library("PerformanceAnalytics")
library(dplyr)
nameOfStrategy <- "GSPC MACD"
#Specify dates for downloading data, training models and running simulation
trainingStartDate = as.Date("2000-01-01")
trainingEndDate = as.Date("2010-01-01")
outofSampleStartDate = as.Date("2010-01-02")
#Download the data
symbolData <- new.env() #Make a new environment for quantmod to store data in
getSymbols("^GSPC", env = symbolData, src = "yahoo", from = trainingStartDate)
trainingData <- window(symbolData$GSPC, start = trainingStartDate, end = trainingEndDate)
testData <- window(symbolData$GSPC, start = outofSampleStartDate)
indexReturns <- Delt(Cl(window(symbolData$GSPC, start = outofSampleStartDate)))
colnames(indexReturns) <- "GSPC Buy&Hold"
这是我用来查找市场信号然后组织数据的代码:
signalB <- ifelse(MACD12$macd > MACD12$signal & lag.xts(MACD12$macd) < lag.xts(MACD12$signal),1,NA)
#If fastMA > slowMA on change go long
signalS <- ifelse(MACD12$macd < MACD12$signal & lag.xts(MACD12$macd) > lag.xts(MACD12$signal),-1,NA)
#Combines Buy and sell signals
Tsignal <- merge(signalB,signalS)
#Gets number of days---dont know when period starts but doesnt matter since we just want difference in days
Tsignal$dates =indexTZ(Tsignal)
Tsignal$dates =index(Tsignal)
#Combines Buy and Sell signal into overall signal
Tsignal$Signal <- ifelse(is.na(Tsignal$Buy),ifelse(is.na(Tsignal$Sell),NA,-1),1)
Tsignal$Tdate <- 0
#Gets 'Date' only if signal either buy or sell
Tsignal$Tdate <- ifelse(!is.na(Tsignal$Signal),Tsignal$dates,NA)
#Finds difference between the Sell sig and the last signal **** In this case it will work but future buying twice before
# selling will result in not getting returns of one of the purchases
Tsignal$lag <- ifelse(Tsignal$Signal == -1,diff(na.locf(Tsignal$Tdate)),NA)
Tsignal$lag <- ifelse(is.na(Tsignal$lag),0,Tsignal$lag)
问题在于:
lag(Cl(trainingData),Tsignal$lag))
#Warning message:
#In if (n == 0) return(x) :
#the condition has length > 1 and only the first element will be used
它返回所有价格,但在0期间滞后(即只返回价格)。虽然Tsignal $滞后有很多零,但整个值都有大于1的值。
我需要它在Tsignal $ lag = 0的日期返回相同的价格并且返回价格滞后于Tsignal $ lag指定的期数。
目前我正在使用dplyr lag函数,但我尝试了其他具有lag函数的包,我得到了同样的错误。写这个我想我可能要做'for'功能,但我不确定,我对R来说还不够新。
提前感谢您的帮助!
答案 0 :(得分:0)
dplyr和stats滞后函数都需要整数表示滞后期数(?dplyr :: lag),但是你的Tsignal $ lag是一个向量。要保留在xts域中,一个建议是使用滞后值作为收盘价的直接指数抵消,如
Cl(trainingData)[(1:nrow(trainingData))-coredata(Tsignal$lag),]