Michael Zak
2008-Nov-27 18:17 UTC
[R] How to optimize a trading singal generator (for-loop)?
Hi guys, I've got some performance troubles with my trading signal generator, which indicates when the system goes long or short. I'm playing with some historical data and the for-loop isn't doing his job very efficient. Is there some vectorial solution for this? Here the for-loop: > trade.long <- 0 > trade.short <- 0 > for (j in peak.days : dim(commodities[[i]])[1]) { > # Trading Signal Long > if (commodities[[i]][j, "High"] >= commodities[[i]][j, "HighestHigh"] && trade.long == 0) { > commodities[[i]][j, "Long"] <- 1 > trade.long <- 1 > } > if (commodities[[i]][j, "Low"] <= commodities[[i]][j, "emaH"] && trade.long == 1) { > commodities[[i]][j, "Long"] <- -1 > trade.long <- 0 > } > # Trading Signal Short > if (commodities[[i]][j, "Low"] <= commodities[[i]][j, "LowestLow"] && trade.short == 0) { > commodities[[i]][j, "Short"] <- 1 > trade.short <- 1 > } > if (commodities[[i]][j, "High"] >= commodities[[i]][j, "emaL"] && trade.short == 1) { > commodities[[i]][j, "Short"] <- -1 > trade.short <- 0 > } > } # for (j in peak.days : dim(commodities[[i]])[1]) Any ideas are very appreciated, because this for-loop takes about 2 - 3 hours to finish... Thank you, Michael