我已经建立了以下模型,只回测间谍。 我的问题是我想将这种交易策略应用于多个代码(例如qqq和间谍)。
我该怎么做? 见下文:
getSymbols("spy",from ="2000-01-01", to="2015-01-01")
SPY<-adjustOHLC(SPY)
rsi <- RSI(Cl(SPY),2)
smashort<-SMA(Cl(SPY),10)
smalong<-SMA(Cl(SPY),200)
adx<-ADX(HLC(SPY),10)
adx<-adx[,4]
close<-Cl(SPY)
signal<-ifelse(rsi<15 & close<smashort & smalong<close &adx>27,1,0)
for(i in 1:nrow(signal))
{signal<-ifelse(lag(signal)==1 & close<smashort,1,ifelse(rsi<15 & close<smashort & smalong<close & adx>27,1,0))}
signal<-lag(signal,1)
signal[is.na(signal)] <- 0
ret <- ROC(Cl(SPY))
ret[1] <- 0
equity<-exp(cumsum(ret*signal))
plot(equity)
请参阅下面的多重代码版本:
stockData <- new.env() #Make a new environment for quantmod to store data in
symbols = c("TLT", "USO")
getSymbols(symbols, src='yahoo',from = "2016-9-01",to = Sys.Date())
for(symbol in symbols){
assign(symbol,adjustOHLC(get(symbol, pos=.GlobalEnv), symbol.name=symbol,
adjust=c("split"), use.Adjusted=FALSE))
}
x <- list()
for (i in 1:length(symbols)) {
x[[i]] <- get(symbols[i], pos=stockData) # get data from stockData environment
x[[i]]$sma <-SMA(Cl(x[[i]]),10)
x[[i]]$rsi <-RSI(Cl(x[[i]]),2)
x[[i]]$close <-(Cl(x[[i]]))
x[[i]]$signal<-ifelse(x[[i]]$rsi<15 & x[[i]]$close<x[[i]]$sma,1,0)
for(i in length(x[[i]]$signal))
{x[[i]]$signal<-ifelse(lag(x[[i]]$signal)==1 & x[[i]]$close<x[[i]]$sma,1,ifelse(x[[i]]$rsi<15 & x[[i]]$close<x[[i]]$sma,1,0))}
}
&#13;
答案 0 :(得分:1)
使用quantstrat
可以轻松完成您想要做的事情。请参阅包中的demo文件夹(请参阅demo文件夹中的RSI策略),或在线查看有关它的多个教程。
devtools::install_github("braverock/quantstrat")
在您的代码段中,当您尝试循环向量操作时,此部分没有意义:
for(i in length(x[[i]]$signal))
{x[[i]]$signal<-ifelse(lag(x[[i]]$signal)==1 & x[[i]]$close<x[[i]]$sma,1,ifelse(x[[i]]$rsi<15 & x[[i]]$close<x[[i]]$sma,1,0))}
同样for(i in length(x[[i]]$signal))
只返回i =向量的长度。也许你想要像for(i in 1:NROW(x[[i]]$signal))
这样的东西。
看起来你想要这样的东西:
x <- list()
for (i in 1:length(symbols)) {
x[[i]] <- get(symbols[i], pos=stockData) # get data from stockData environment
x[[i]]$sma <-SMA(Cl(x[[i]]),10)
x[[i]]$rsi <-RSI(Cl(x[[i]]),2)
x[[i]]$close <-(Cl(x[[i]]))
x[[i]]$signal<-ifelse(x[[i]]$rsi<15 & x[[i]]$close<x[[i]]$sma,1,0)
x[[i]]$signal2 <-ifelse(lag.xts(x[[i]]$signal) ==1 & x[[i]]$close<x[[i]]$sma,1,ifelse(x[[i]]$rsi<15 & x[[i]]$close<x[[i]]$sma,1,0))
}
答案 1 :(得分:0)
x <- list()
for (i in 1:length(symbols)) {
x[[i]] <- get(symbols[i], pos=stockData) # get data from stockData environment
x[[i]]$sma <-SMA(Cl(x[[i]]),10)
x[[i]]$rsi <-RSI(Cl(x[[i]]),2)
x[[i]]$close <-(Cl(x[[i]]))
x[[i]]$signal<-ifelse(x[[i]]$rsi<10 & x[[i]]$close<x[[i]]$sma,1,0)
for(k in 1:nrow(x[[i]]$signal))
{x[[i]]$signal<-ifelse(lag(x[[i]]$signal)==1 & x[[i]]$close<x[[i]]$sma,1,ifelse(x[[i]]$rsi<10 & x[[i]]$close<x[[i]]$sma,1,0))}
x[[i]]$signal<-lag(x[[i]]$signal,1)
x[[i]]$signal[is.na(x[[i]]$signal)] <- 0
x[[i]]$ret <- ROC(Cl(x[[i]]$close))
x[[i]]$ret[1] <- 0
x[[i]]$equity<-exp(cumsum(ret*x[[i]]$signal))
plot(x[[i]]$equity)
}
&#13;
`