0

我正在 R 中回测交易策略。到目前为止,我的策略代码等有效。但我正在努力为曲线下的区域着色。基本上,我希望有一个从 Date0 到 Date1 的完整绿色区域,其中我在这个特定标题上的时间跨度很长,我希望从 Date2 到 Date3 有一个红色区域,其中我的时间跨度很短。

这是我的代码。多边形虽然此时会生成奇怪的区域......显然我的变量 longArea 和 shortArea 不正确..但是我需要在这里编写什么代码?对不起,我的评论是德语:-)

## rm(list = ls(all = TRUE)) ## please don't do this, or if must comment it out!
require(quantmod)
require(far)

#setting parameters, bis und mit series zum anpassen
strategyTitle<-"Strategy"
lookback <- 24 #24 days ago
startMoney <- 1
#import data, default is yahoo
#getSymbols l?dt die Daten automatisch in eine Varialbe die wie das Symbol
#heisst. series<-getSymbols funktioniert NICHT wie erwartet, sondern l?dt
#nur den Namen des Symbols in die Variable
series<-getSymbols('AAPL',from='1990-01-01',auto.assign = FALSE)


#generate HLOC series
close <- as.double(Cl(series))
open <- as.double(Op(series))
low <-as.double(Lo(series))
high <- as.double(Hi(series))


#So werden die einzelnen Vektoren auf 0 gesetzt, wie Trades etc.
f <- function(x) 0 * x
position <- apply(series[,1],1, FUN=f)
returns <- apply(series[,1],1, FUN=f)
trades <- apply(series[,1],1, FUN=f)
amount <- apply(series[,1],1, FUN=f)
amount[seq(1,lookback)] = startMoney
longArea <- apply(series[,1],1, FUN=f)
shortArea <- apply(series[,1],1, FUN=f)

#n ist die Anzahl der Datenpunkte f?r unser Symbol
n <- nrow(series)

#buy and hold portfolio berechnen
calcBuyAndHold<- function(portfolio, start, end, closePrices, initialAmount){
  for(i in seq(start,end)){
    if(i == start){
      portfolio[i] <- initialAmount
    } else {
      portfolio[i] <- portfolio[i-1] * (closePrices[i]/closePrices[i-1])
    }
  }
  return(portfolio)
}

buyAndHold <- apply(series[,1],1, FUN=f)
buyAndHold <- calcBuyAndHold(buyAndHold,1,n,close,startMoney)

#Strategieberechnung
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]
  }

  #Calculate the dollar amount
  amount[i] = amount[i-1]*(1+returns[i])

  #mark a trade if we did one. Aber nicht mit 0 und 1, sondern mit dem Wert
  #der Strategy, damit der Plot-Punkt am richtigen Ort gezeichnet wird
  if(position[i] != position[i-1]) {
    trades[i] = amount[i]
  } else {
    trades[i] = NA
  }

  #Für die grün/roten Gebiete unter der Strategiekurve
  if(position[i] == 1){
    #long
    longArea[i] = amount[i];
    shortArea[i] = NA
  } else {
    #short
    longArea[i] = NA;
    shortArea[i] = amount[i];
  }
}


#Plotting
#zoo() ist ein Objekt f?r irregular time series-> so wird das Datum korrekt
#dargestellt
amt<-zoo(amount,time(series))
bah<-zoo(buyAndHold,time(series))
tr<-zoo(trades,time(series))

#um das Maximum und Minimum der y-Achse korrekt zu setzen
grange<-range(amt,bah)

#Kurven, Plots und eingef?rbte Bereiche
plot(amt,type="l",main=strategyTitle, ylim=grange, xlab="Date", ylab=paste("Amount(Startvalue:",startMoney,")"), col="blue")
lines(bah, type="l",col="red")
points(tr,col="green")
polygon(time(series),longArea,col="green")
polygon(time(series),shortArea,col="red")

#lty=c(1,1) gives the legend appropriate symbols (lines)
#lwd=c(2.5,2.5),col=c("blue","red")) gives the legend lines the correct color and width
legend(min(time(series)),grange[2],c("Strategy","Buy and Hold"), col=c("blue", "red"), lty=c(1,1), lwd=c(2.5,2.5))
4

0 回答 0