我对 R 非常陌生,并试图回测我已经在 WealthLab 中编程的策略。
一些我不明白的东西(而且它显然不起作用:)
我没有将收盘价很好地放入向量......或某种向量,但它从结构开始,我真的不明白这个函数的作用。这就是为什么我的 series[,1] 调用可能不起作用的原因。
n <- nrow(series) 也不起作用,但循环需要它
所以我想如果我得到这两个问题的回答,我的策略应该会奏效......我非常感谢任何帮助......即使有其他语言的编程经验,R 似乎也很复杂
#rm(list = ls(all = TRUE))
#import data, default is yahoo
require(quantmod)
series <- getSymbols('AAPL',from='2013-01-01')
#generate HLOC series
close <- Cl(AAPL)
open <- Op(AAPL)
low <-Lo(AAPL)
high <- Hi(AAPL)
#setting parameters
lookback <- 24 #24 days ago
startMoney <- 10000
#Empty our time series for position and returns
f <- function(x) 0 * x
position <- apply(series[,1],FUN=f)
colnames(position)="long_short"
returns <- apply(series[,1],FUN=f)
colnames(returns)="Returns"
trades = returns
colnames(trades)="Trades"
amount = returns
colnames(amount) = "DollarAmount"
amt[seq(1,lookback)] = startMoney
#Calculate all the necessary values in a loop with our trading strategy
n <- nrow(series)
for(i in seq(lookback+1,n)){
#get the return
if(position[i-1] == 1){
#we were long
returns[i] = close[i]/close[i-1] - 1
} else if(position[i-1] == -1){
#we were short
returns[i] = close[i-1]/close[i] - 1
}
#long/short position
if(open[i-lookback]<open[i] && low[i-1] < open[i]){
#go long
position[i] = 1
} else if(open[i-lookback]>open[i] && high[i-1] > open[i]){
# go short
position[i] = -1
} else {
position[i] = position[i-1]
}
#mark a trade if we did one
if(position[i] != position[i-1]) trades[i] = 1
#Calculate the dollar amount
amount[i] = amount[i-1]*exp(returns[i])
if(trades[i]) amount[i] = amount[i] - 2
}