I am trying to see how “winning percentage” affects returns for a trading strategy.
I download the prices of S&P and calculating the daily returns. Then, I randomly select x% of these returns and say I correctly predicted it’s direction so the return is positive. For the remainder 1-x%, I say I am wrong and the return is negative. I replicate this process say 1000 times and collect the annualised geometric return.
I vary x from 0.5 to 0.6 at 0.01 increment intervals.
Here is my code:
library(quantmod)
library(multicore)
getSymbols("^GSPC", from = "1950-1-1")
ret <- ROC(GSPC)[-1,4]
set.seed(123)
winpct <- seq(0.5, 0.6, 0.01)
ret <- coredata(ret)
system.time(res <- simplify2array(mclapply(winpct, function(x) replicate(1000, drawsample(ret, x)))))
drawsample <- function(ret, winpct){
len = length(ret)
ret = abs(ret)
win = sample(1:len, round(winpct * len))
a = c(ret[win], -ret[-win])
return(prod(1 + a) ^ (252 / length(a)) - 1)
}
Time taken:
user system elapsed
18.904 0.842 5.580
Are there any further optimisations I can do to speed things up?
I made the following two tweaks:
1/ use
exp(sum(a))rather thanprod(1+a). I think you want this anyways, as you have created a log returns series withROC(GSPC)[-1,6]. According torbenchmarkthis got me a speedup of about 7%.2/ sample from
c(-1,-1)for the length of theretseries, and then multiply with the ret series, to obtain the signed series of returns. This got me another 30%.Note that in my code, i’ve re-named your
aasbin.Benchmarking against your
drawsample()i get ~37% speedup.On my MBP, here are the benchmarks: