Note that there are some explanatory texts on larger screens.

plurals
  1. POR: Backtesting a trading strategy. Beginners to quantmod and R
    text
    copied!<p>I'm very new to R and trying to backtest a strategy I've programmed already in WealthLab. </p> <p>Several stuff I don't understand (and it doesn't work obviously:)</p> <ol> <li><p>I don't get the Close Prices nicely into a vector...or some kind of vector but it starts with structure and I don't really understand what this function does. Thats why my series[,1] call probably doesn't work.</p></li> <li><p>n &lt;- nrow(series) doesn't work either, but I need that for the Loop</p></li> </ol> <p>So I guess if I get These 2 questions answered my strategy should work...I'm very thankful for any help..R seems quite complicated even with programming experience in other languages</p> <pre><code>#rm(list = ls(all = TRUE)) #import data, default is yahoo require(quantmod) series &lt;- getSymbols('AAPL',from='2013-01-01') #generate HLOC series close &lt;- Cl(AAPL) open &lt;- Op(AAPL) low &lt;-Lo(AAPL) high &lt;- Hi(AAPL) #setting parameters lookback &lt;- 24 #24 days ago startMoney &lt;- 10000 #Empty our time series for position and returns f &lt;- function(x) 0 * x position &lt;- apply(series[,1],FUN=f) colnames(position)="long_short" returns &lt;- 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 &lt;- 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]&lt;open[i] &amp;&amp; low[i-1] &lt; open[i]){ #go long position[i] = 1 } else if(open[i-lookback]&gt;open[i] &amp;&amp; high[i-1] &gt; 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 } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload